diff --git a/CODEOWNERS b/CODEOWNERS index 6d009889e9f39a8a68f1d79a14fc728b89d053dd..c07dcbcb07683ecb03d698d85d0c99d91107d5e9 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -222,7 +222,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-system-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-settings.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-settings.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-document.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-environment.md @qinxiaowang @@ -258,7 +258,7 @@ zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14 diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 75896e868631ea644d2f1ed28beaacad9b5a8303..623145619dbee26958ac53e7bce4ed40e213b860 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -7,16 +7,16 @@ - [OpenHarmony Release Notes](../release-notes/Readme.md) - Quick Start - Getting Started - - [Preparations](quick-start/start-overview.md) - - [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) - - [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) - - [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) - - [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md) + - [Preparations](quick-start/start-overview.md) + - [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) + - [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) + - [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) + - [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md) - Development Fundamentals - - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - - [Resource File Categories](quick-start/basic-resource-file-categories.md) - - [SysCap](quick-start/syscap.md) + - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) + - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) + - [Resource File Categories](quick-start/basic-resource-file-categories.md) + - [SysCap](quick-start/syscap.md) - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) @@ -33,20 +33,19 @@ - [Device Usage Statistics](device-usage-statistics/Readme-EN.md) - [DFX](dfx/Readme-EN.md) - [Internationalization](internationalization/Readme-EN.md) - - [Native APIs](napi/Readme-EN.md) + - [Using Native APIs in Application Projects](napi/Readme-EN.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) - - [Codelabs](https://gitee.com/openharmony/codelabs/blob/master) + - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) + - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - APIs - - [JS and TS APIs](reference/apis/Readme-EN.md) - - Native APIs - - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - - [Node_API](reference/native-lib/third_party_napi/napi.md) + - [JS and TS APIs](reference/apis/Readme-EN.md) + - Native APIs + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) - Contribution - [How to Contribute](../contribute/documentation-contribution.md) - diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md index 283037aedc8c219bee48511898dd300a0c05dc3b..0d2303bf4f84c2ddc6f34a13d28b02a3762893b0 100644 --- a/en/application-dev/ability/ability-brief.md +++ b/en/application-dev/ability/ability-brief.md @@ -2,19 +2,19 @@ An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. -The ability framework model has two forms. +The ability framework model has two forms: -- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. -- Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. +- FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. +- Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. | Item | FA Model | Stage Model | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | -| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | +| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Intra-process object sharing| Not supported. | Supported. | -| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.| +| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json5` file is used to describe the HAP and component information. The entry file name can be specified.| | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | In addition, the following differences exist in the development process: @@ -27,8 +27,4 @@ In addition, the following differences exist in the development process: ![lifecycle](figures/lifecycle.png) - For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). -## Samples -The following sample is provided to help you better understand how to develop abilities: -- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability/fa-brief.md index cca353bb06253a17bbc7cfec2b823c67b8568ad0..dac1a3277b9bfeecefc7f341d63073a3b9ed35fd 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability/fa-brief.md @@ -34,17 +34,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. ![fa-threading-model](figures/fa-threading-model.png) -## Samples -The following sample is provided to help you better understand how to develop abilities: - -- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc) -- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti) - -- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA) -- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo) -- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) -- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH) -- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) -- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) -- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) -- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability/fa-dataability.md index c2a72cef31d5416c5a062689bac28af2d7e41c5b..faad709b280730f5f96c79a905fe6385f04fce62 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -1,9 +1,12 @@ # Data Ability Development + ## 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. + ## Available APIs **Table 1** Data ability lifecycle APIs @@ -18,7 +21,7 @@ Data ability providers can customize data access-related APIs such as data inser |denormalizeUri?(uri: string, callback: AsyncCallback\): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| |insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\): void|Inserts a data record into the database.| |openFile?(uri: string, mode: string, callback: AsyncCallback\): void|Opens a file.| -|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\>): void|Obtains the MIME type of a file.| +|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback>): void|Obtains the MIME type of a file.| |getType?(uri: string, callback: AsyncCallback\): void|Obtains the MIME type matching the data specified by the URI.| |executeBatch?(ops: Array\, callback: AsyncCallback\>): void|Operates data in the database in batches.| |call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void|Calls a custom API.| @@ -115,7 +118,7 @@ Import the basic dependency packages and obtain the URI string for communicating The basic dependency packages include: - @ohos.ability.featureAbility -- @ohos.data.dataability +- @ohos.data.dataAbility - @ohos.data.rdb #### Data Ability API Development @@ -283,9 +286,3 @@ The basic dependency packages include: ] ); ``` - -## Samples - -The following sample is provided to help you better understand how to develop Data abilities: - -- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility) diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 8a790318cf11494e519496096993bee63d567ce8..df433bbf7f7e9d9ff8c24ef389e965bc74ece74c 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -348,9 +348,3 @@ 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) - -## Samples - -The following samples are provided to help you better understand how to develop a widget on the FA model: -- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) -- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher) diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md index 296ca6b1afa2e3e3fdc05da9a3489dfd234ee991..5700907bccb27931f1f8f39f9bf2884391ab1609 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability/fa-pageability.md @@ -261,7 +261,3 @@ export default { }, } ``` -## Samples -The following sample is provided to help you better understand how to develop a Page ability: - -- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 86e863eddf5bb5ab8f550e32a2e90fa45022143d..60961112f9084872f53efbe53cea62d2c8513365 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -399,9 +399,3 @@ export default { } }; ``` - -## Samples - -The following samples are provided to help you better understand how to develop a Service ability: -- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) -- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) diff --git a/en/application-dev/ability/figures/page-ability-lifecycle.png b/en/application-dev/ability/figures/page-ability-lifecycle.png index edb49acd0647f3af7355ceda987c5ca812866128..b35954967bb9c733725da2f0700481932619ae45 100644 Binary files a/en/application-dev/ability/figures/page-ability-lifecycle.png and b/en/application-dev/ability/figures/page-ability-lifecycle.png differ diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 4b05e88f1ccdb990a454a538a001aadb7bc45a80..19c43dcc322e08fad315341396fabfad9d99d0a1 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -1,22 +1,22 @@ # Ability Development ## When to Use -Unlike the FA model, the [stage model](stage-brief.md) requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop abilities based on the stage model, implement the following logic: -- Create abilities for an application that involves screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. +Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json5` and `app.json5` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: +- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Call abilities. For details, see [Call Development](stage-call.md). - Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). - Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). ### Launch Type -The ability supports three launch types: singleton, multi-instance, and instance-specific. Each launch type, specified by `launchType` in the `module.json` file, specifies the action that can be performed when the ability is started. +An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json5` file. Depending on the launch type, the action performed when the ability is started differs, as described below. -| Launch Type | Description |Description | +| Launch Type | Description |Action | | ----------- | ------- |---------------- | | 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.| +| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| -By default, the singleton mode is used. The following is an example of the `module.json` file: +By default, the singleton mode is used. The following is an example of the `module.json5` file: ```json { "module": { @@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 2** Ability APIs + |API|Description| |:------|:------| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| @@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme ``` import AbilityStage from "@ohos.application.AbilityStage" ``` -2. Implement the `AbilityStage` class. +2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. ```ts export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -70,7 +71,7 @@ To create Page abilities for an application in the stage model, you must impleme ```js import Ability from '@ohos.application.Ability' ``` -4. Implement the lifecycle callbacks of the `Ability` class. +4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**. In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). ```ts @@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - windowStage.loadContent("pages/index").then((data) => { - console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) + windowStage.loadContent("pages/index").then(() => { + console.log("MainAbility load content succeed") }).catch((error) => { console.error("MainAbility load content failed with error: "+ JSON.stringify(error)) }) @@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme } ``` ### Obtaining AbilityStage and Ability Configurations -Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: +Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. + +The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: + ```ts import AbilityStage from "@ohos.application.AbilityStage" export default class MyAbilityStage extends AbilityStage { @@ -140,14 +144,14 @@ export default class MainAbility extends Ability { console.log("MainAbility ability name" + abilityInfo.name) let config = this.context.config - console.log("MyAbilityStage config language" + config.language) + console.log("MainAbility config language" + config.language) } } ``` ### Requesting Permissions -If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permissions for calendar access as an example. +If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json5`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. -Declare the required permissions in the `module.json` file. +Declare the required permission in the `module.json5` file. ```json "requestPermissions": [ { @@ -155,7 +159,7 @@ Declare the required permissions in the `module.json` file. } ] ``` -Request the permissions from consumers in the form of a dialog box: +Request the permission from consumers in the form of a dialog box: ```ts let context = this.context let permissions: Array = ['ohos.permission.READ_CALENDAR'] @@ -166,11 +170,11 @@ context.requestPermissionsFromUser(permissions).then((data) => { }) ``` ### Notifying of Environment Changes -Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by the configuration item in **Settings** or the icon in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). +Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md). For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations. -The following example shows the implement of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed. +The following example shows the implementation of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed. ```ts import Ability from '@ohos.application.Ability' import ConfigurationConstant from '@ohos.application.ConfigurationConstant' @@ -184,7 +188,7 @@ export default class MyAbilityStage extends AbilityStage { } ``` -The following example shows the implement of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. +The following example shows the implementation of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change. ```ts import Ability from '@ohos.application.Ability' import ConfigurationConstant from '@ohos.application.ConfigurationConstant' @@ -205,7 +209,7 @@ export default class MainAbility extends Ability { ``` ## Starting an Ability ### Available APIs -The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). +The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). **Table 3** AbilityContext APIs |API|Description| @@ -227,17 +231,16 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -context.startAbility(want).then((data) => { - console.log("Succeed to start ability with data: " + JSON.stringify(data)) +context.startAbility(want).then(() => { + console.log("Succeed to start ability") }).catch((error) => { console.error("Failed to start ability with error: "+ JSON.stringify(error)) }) ``` ### Starting an Ability on a Remote Device -This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications. +>This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications. In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows: - ```ts let context = this.context var want = { @@ -245,8 +248,8 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -context.startAbility(want).then((data) => { - console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) +context.startAbility(want).then(() => { + console.log("Succeed to start remote ability") }).catch((error) => { console.error("Failed to start remote ability with error: " + JSON.stringify(error)) }) @@ -268,7 +271,7 @@ function getRemoteDeviceId() { } } ``` -Request the permission `ohos.permission.DISTRIBUTED_DATASYNC ` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions). +Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions). ### Starting an Ability with the Specified Page If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows: @@ -312,13 +315,9 @@ struct Index { console.info('Index onPageShow') let newWant = globalThis.newWant if (newWant.hasOwnProperty("uri")) { - router.push({ uri: newWant.uri }); + router.push({ url: newWant.uri }); globalThis.newWant = undefined } } } ``` - -## Samples -The following sample is provided to help you better understand how to develop an ability on the stage model: -- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index e402454ddf6afd1b1aab71601e52b19d8010b425..aaa9a9918345c52015969245c3bbba3efbb81048 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -247,7 +247,3 @@ try { Logger.error(TAG, `caller release failed with ${error}`) } ``` - -## Samples -The following sample is provided to help you better understand how to develop an ability call in the stage model: -- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability/stage-formextension.md index c54ae466d615b05da05ebbde0faf2ff8e97f7c7b..5fa0f92eea67dc6b90a69c7ad32a9ec97a62b540 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -358,8 +358,3 @@ 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) - -## Samples - -The following sample is provided to help you better understand how to develop a widget on the stage model: -- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability/stage-serviceextension.md index 3438462d05164099ce3e9c258ef05c8e3668f6fb..6f83c084a783856c871848171af24e430611356d 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability/stage-serviceextension.md @@ -26,7 +26,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p 1. Create a Service Extension ability. -2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined and override the lifecycle callbacks of the base class. The code sample is as follows: +2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined (**entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts** by default) and override the lifecycle callbacks of the base class. The code sample is as follows: ```js import rpc from '@ohos.rpc' @@ -61,9 +61,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p 2. Register the Service Extension ability. - Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. + Declare the Service Extension ability in the **module.json5** file by setting its **type** attribute to **service**. - **module.json configuration example** + **module.json5 configuration example** ```json "extensionAbilities":[{ @@ -75,8 +75,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p "srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts" }] ``` - -## Samples - -The following sample is provided to help you better understand how to develop Service Extension abilities: -- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index 3e2a7ca7eb90522c4966f2c7cd8b71feffe2aaff..faca786c9039e58ac0bd590e7b004c8b75a8890b 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. They are organized as follows: -- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) +- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) - Native APIs diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 893cdaee07d01a1ede85a24ecf80af4f6246a128..d7e79c16e839de0c60a2999f32b1c86ff6745578 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -53,8 +53,8 @@ To make you better understand how functions work together and jumpstart your app API references encompass all components and APIs available in OpenHarmony, helping you use and integrate APIs more effectively. They are organized as follows: -- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/ts-universal-events-click.md) +- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/js-components-common-attributes.md) - [JS and TS APIs](reference/apis/js-apis-DataUriUtils.md) - Native APIs - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index 0a69a2e0f79a874def98d2be58d26d6dec0c3874..b43d1961722f6e6265f0a8b649208c1737f05726 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -71,7 +71,3 @@ httpRequest.request( } ); ``` - -## Samples -The following sample is provided to help you better understand how to develop the HTTP data request feature: -- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http) diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 9444946bda64eadb546cfd282e8d5e4e2f670256..15f38e97a75585520cf60534d03a4c1812001716 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th tcp.off('close'); }, 30 * 1000); ``` - -## Samples -The following sample is provided to help you better understand how to develop the socket connection feature: -- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket) diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index 303b306528897e501b5c258615023f736ee1f9b0..4bb8e42f8496f1db1392929ebae9311105ea2268 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -6,6 +6,7 @@ The distributed data objects allow data across devices to be processed like loca ## Available APIs +For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). ### Creating a Distributed Data Object Instance @@ -93,7 +94,7 @@ The following example shows how to implement a distributed data object synchroni // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. ``` -4. Observe the data changes of the distributed data object. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes. +4. Observe the data changes of the distributed data object. You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. The sample code is as follows: @@ -107,7 +108,7 @@ The following example shows how to implement a distributed data object synchroni }); } } - + // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. local_object.on("change", this.changeCallback.bind(this)); ``` @@ -138,13 +139,13 @@ The following example shows how to implement a distributed data object synchroni ```js console.info("name " + local_object["name"]); ``` -7. Unsubscribe from data changes. You can specify the callback to unsubscribe from. If you do not specify the callback, all data change callbacks of the distributed data object will be unsubscribed from. +7. Unsubscribe from data changes. You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. The sample code is as follows: ```js - // Unsubscribe from the specified data change callback. + // Unregister the specified data change callback. local_object.off("change", changeCallback); - // Unsubscribe from all data change callbacks. + // Unregister all data change callbacks. local_object.off("change"); ``` 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. @@ -156,13 +157,13 @@ The following example shows how to implement a distributed data object synchroni 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, this API unsubscribes from all callbacks of this distributed data object. +9. Unsubscribe from the status changes of the distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. The sample code is as follows: ```js - // Unsubscribe from the specified status change callback. + // Unregister the specified status change callback. local_object.off("status", statusCallback); - // Unsubscribe from all status change callbacks. + // Unregister all status change callbacks. local_object.off("status"); ``` 10. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. @@ -171,4 +172,12 @@ The following example shows how to implement a distributed data object synchroni ```js local_object.setSessionId(""); ``` +## Development Example + +The following example is provided for you to better understand the development of distributed data objects: + +- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) + +When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network. + diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index b504f5b2a9e944ff429f178d341546c27e700089..dd1594215a10d1c93c9825444253484ed8956e05 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -6,20 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat ## Available APIs +For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). -The table below describes the APIs provided by the OpenHarmony DDS module. **Table 1** APIs provided by the DDS -| Category | API | Description | -| -------------------------- | ------------------------------------------------------------ | ----------------------------------------------- | -| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| -| Obtaining a distributed KV store | getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**.| -| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data. | -| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | -| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void | Subscribes to data changes in the KV store. | -| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| API | Description | +| ------------------------------------------------------------ | ----------------------------------------------- | +| createKVManager(config:KVManagerConfig,callback:AsyncCallback<KVManager>):void
createKVManager(config:KVManagerConfig):Promise<KVManager> | Creates a **KVManager** object for database management.| +| getKVStore<TextendsKVStore>(storeId:string,options:Options,callback:AsyncCallback<T>):void
getKVStore<TextendsKVStore>(storeId:string,options:Options):Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| +| put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback<void>):void
put(key:string,value:Uint8Array\|string\|number\|boolean):Promise<void> | Inserts and updates data. | +| delete(key:string,callback:AsyncCallback<void>):void
delete(key:string):Promise<void> | Deletes data. | +| get(key:string,callback:AsyncCallback<Uint8Array\|string\|boolean\|number>):void
get(key:string):Promise<Uint8Array\|string\|boolean\|number> | Queries data. | +| on(event:'dataChange',type:SubscribeType,observer:Callback<ChangeNotification>):void
on(event:'syncComplete',syncCallback:Callback<Array<[string,number]>>):void | Subscribes to data changes in the KV store. | +| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. | @@ -34,11 +34,14 @@ The following uses a single KV store as an example to describe the development p ``` 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. - 1. Create a **KvManagerConfig** object based on the application context. - 2. Create a **KvManager** instance. + + (1) Create a **KvManagerConfig** object based on the application context. + (2) Create a **KvManager** instance. + The sample code is as follows: - ```js + + ``` let kvManager; try { const kvManagerConfig = { @@ -60,10 +63,13 @@ The following uses a single KV store as an example to describe the development p console.log("An unexpected error occurred. Error:" + e); } ``` - + + 3. Create and obtain a single KV store. - 1. Declare the ID of the single KV store to create. - 2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. + + (1) Declare the ID of the single KV store to create. + + (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. The sample code is as follows: ```js @@ -90,10 +96,11 @@ The following uses a single KV store as an example to describe the development p } ``` - > ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
- > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. + > **NOTE** + > + > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. -4. Subscribe to changes in the distributed data.
+4. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store: ```js kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { @@ -102,8 +109,10 @@ The following uses a single KV store as an example to describe the development p ``` 5. Write data to the single KV store. - 1. Construct the key and value to be written into the single KV store. - 2. Write key-value pairs into the single KV store. + + (1) Construct the key and value to be written into the single KV store. + + (2) Write key-value pairs into the single KV store. The following is the sample code for writing key-value pairs of the string type into the single KV store: @@ -124,8 +133,10 @@ The following uses a single KV store as an example to describe the development p ``` 6. Query data in the single KV store. - 1. Construct the key to be queried from the single KV store. - 2. Query data from the single KV store. + + (1) Construct the key to be queried from the single KV store. + + (2) Query data from the single KV store. The following is the sample code for querying data of the string type from the single KV store: ```js @@ -150,7 +161,11 @@ The following uses a single KV store as an example to describe the development p 7. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data. - The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms. + > **NOTE** + > + > The APIs of the `deviceManager` module are system interfaces. + + The following is the sample code for synchronizing data in a single KV store: ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -159,7 +174,7 @@ The following uses a single KV store as an example to describe the development p deviceManager.createDeviceManager("bundleName", (err, value) => { if (!err) { devManager = value; - // Obtain deviceIds. + // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync(). let deviceIds = []; if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); @@ -168,6 +183,7 @@ The following uses a single KV store as an example to describe the development p } } try{ + // 1000 indicates that the maximum delay is 1000 ms. kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); }catch (e) { console.log("An unexpected error occurred. Error:" + e); diff --git a/en/application-dev/database/database-mdds-overview.md b/en/application-dev/database/database-mdds-overview.md index 2262558e38e892854b4de12cf124a88569cabf84..26efa7491805e871017db3593f5fa50d947717f5 100644 --- a/en/application-dev/database/database-mdds-overview.md +++ b/en/application-dev/database/database-mdds-overview.md @@ -1,8 +1,12 @@ -# Distributed Data Service Overview +# Distributed Data Service Overview -The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. +The distributed data service (DDS) implements distributed database collaboration across devices for applications. -## Basic Concepts +Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. + +You do not need to care about the implementation of the database locking mechanism. + +## Basic Concepts - **KV data model** @@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. -## Working Principles +## Working Principles The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: @@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ![](figures/en-us_image_0000001183386164.png) -## Constraints +## Constraints - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The KV data model specifications supported by the DDS are as follows: diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 85cd4ac9597996309f980c9d5b7e99072f7ca953..688835122445f6800d83a76fa0633b0be64f385c 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -2,61 +2,56 @@ ## When to Use -On the basis of the SQLite database, the relational database (RDB) allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store. +A relational database (RDB) store allows you to manage local data with or without native SQL statements based on SQLite. ## Available APIs -For details about RDB APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). ### Creating or Deleting an RDB Store -The following table describes the APIs available for creating and deleting an RDB store. +The table below describes the APIs available for creating and deleting an RDB store. **Table 1** APIs for creating and deleting an RDB store | API| Description| | -------- | -------- | -|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.| -| deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| +|getRdbStore(config:StoreConfig,version:number):Promise<RdbStore> | Obtains an RDB store. This API 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.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store.| +| deleteRdbStore(name:string):Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **name**: name of the RDB store to delete.| ### Managing Data in an RDB Store -The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. +The **RDB** module provides APIs for inserting, deleting, updating, and querying data in a local RDB store. -- **Inserting data** +- **Inserting Data** - The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. + The **RDB** module provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. - **Table 2** APIs for inserting data + **Table 2** API 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.| + | RdbStore | insert(name:string,values:ValuesBucket):Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **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 + **Table 3** API 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.| + | RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\ | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
Return value: number of rows updated.
- **values**: data to update, which is stored in **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 + **Table 4** API 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 updated.| - | 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.| + | RdbStore | delete(rdbPredicates:RdbPredicates):Promise\ | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
Return value: number of rows updated.
- **rdbPredicates**: conditions for deleting data.| - **Querying data** @@ -69,74 +64,45 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | 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.| - | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise 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.| - | 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.| + | RdbStore | query(rdbPredicates:RdbPredicates,columns:Array):Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise 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.| + | RdbStore | querySql(sql:string,bindArgs?:Array<ValueType>):Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| ### Using Predicates -The RDB provides **RdbPredicates** for you to set database operation conditions. +The **RDB** module provides **RdbPredicates** for you to set database operation conditions. + +The table below lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). **Table 6** APIs for using RDB store predicates | Class| API| Description| | -------- | -------- | -------- | -| RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | 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.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| -| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| -| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| -| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | 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.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | 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.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | 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.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | 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.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| -| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| 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.| +| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| +| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates** object.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| +| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates** object.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** object to match a string that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.| + ### 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**. +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. + +For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). -> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
+> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set | Class| API| Description| | -------- | -------- | -------- | -| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| -| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| -| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| -| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| -| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| -| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| -| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| -| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| -| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| -| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| -| 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.| +| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set.| +| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row.| +| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row.| +| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close():void | Closes the result set.| @@ -144,32 +110,29 @@ A result set can be regarded as a row of data in the queried results. It allows **Setting Distributed Tables** -**Table 8** APIs for setting distributed tables +**Table 8** API for setting distributed tables | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void; | Sets a list of distributed tables. This method uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| -| RdbStore | setDistributedTables(tables: Array\): Promise\; | Sets a list of distributed tables. This method uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| RdbStore | setDistributedTables(tables: Array\): Promise\; | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** 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 9** APIs for obtaining the distributed table name of a remote device +**Table 9** API for obtaining the distributed table name of a remote device | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): 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 API uses an asynchronous callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned.| -| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This method uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\; | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** -**Table 10** APIs for synchronizing data between devices +**Table 10** API 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. | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise>;| Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: 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**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Registering an RDB Store Observer** @@ -177,7 +140,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback>): void;| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback>): void;| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** @@ -185,7 +148,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE\_TYPE\_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| +| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| ## How to Develop @@ -193,7 +156,7 @@ You can obtain the distributed table name for a remote device based on the local 1. Create an RDB store. 1. Configure the RDB store attributes, including the RDB store name, storage mode, and whether read-only mode is used. 2. Initialize the table structure and related data in the RDB store. - 3. Create the RDB store. + 3. Create an RDB store. The sample code is as follows: @@ -201,7 +164,7 @@ You can obtain the distributed table name for a remote device based on the local import data_rdb from '@ohos.data.rdb' 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",} + const STORE_CONFIG = {name: "rdbstore.db"} data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { rdbStore.executeSql(CREATE_TABLE_TEST ) console.info('create table done.') @@ -216,7 +179,7 @@ You can obtain the distributed table name for a remote device based on the local ```js var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8} let insertPromise = rdbStore.insert("test", valueBucket) ``` @@ -253,12 +216,12 @@ 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("Failed to set distributed tables.") }) ``` 5. Synchronize data across devices. - 1. Constructs an **RdbPredicates** object to specify remote devices within the network to be synchronized. + 1. Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized. 2. Call the **sync()** method to synchronize data. 3. Check whether the data synchronization is successful. @@ -293,7 +256,7 @@ You can obtain the distributed table name for a remote device based on the local try { rdbStore.on('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { - console.log('register observer failed') + console.log('Failed to register observer') } ``` @@ -307,8 +270,3 @@ You can obtain the distributed table name for a remote device based on the local let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` -## Samples -The following samples are provided for you to better understand the RDB development: -- [`Rdb`: eTS RDB (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) -- [`DistributedRdb`: eTS Distributed Relational Database (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) -- [Relational Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) diff --git a/en/application-dev/database/database-relational-overview.md b/en/application-dev/database/database-relational-overview.md index cd675b9701e9e22147833d1fb7b471f420af2f12..c78034c76f63fe1f6e8bd338f9595206f8c5eea0 100644 --- a/en/application-dev/database/database-relational-overview.md +++ b/en/application-dev/database/database-relational-overview.md @@ -1,42 +1,43 @@ -# RDB Overview +# RDB Overview -The relational database \(RDB\) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. +The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. -## Basic Concepts +You do not need to care about the implementation of the database locking mechanism. -- **RDB** +## Basic concepts - A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store. +- **RDB** -- **Predicate** + A type of database created on the basis of relational models. The RDB stores data in rows and columns. A RDB is also called RDB store. - A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. +- **Predicate** -- **Result set** + A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. - A set of query results used to access the data. You can access the required data in a result set in flexible modes. +- **Result set** -- **SQLite database** + A set of query results used to access data. You can access the required data in a result set in flexible modes. - A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability \(ACID\). +- **SQLite database** + A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability (ACID). -## Working Principles +## Working Principles -The RDB provides a common operation interface for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. +The RDB provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. -**Figure 1** How RDB works -![](figures/how-rdb-works.png "how-rdb-works") +**Figure 1** How RDB works -## Default Settings +![how-rdb-works](figures/how-rdb-works.png) -- The default database logging mode is write-ahead logging \(WAL\). -- The default database flush mode is Full mode. -- The default shared memory used by the OpenHarmony database is 2 MB. +## Default Settings -## Constraints +- The default RDB logging mode is Write Ahead Log (WAL). +- The default data flushing mode is **FULL** mode. +- The default size of the shared memory used by an OpenHarmony database is 2 MB. -- A maximum of four connection pools can be connected to an RDB to manage read and write operations. +## Constraints -- To ensure data accuracy, the RDB supports only one write operation at a time. +- A maximum of four connection pools can be connected to an RDB to manage read and write operations. +- To ensure data accuracy, the RDB supports only one write operation at a time. diff --git a/en/application-dev/database/database-storage-guidelines.md b/en/application-dev/database/database-storage-guidelines.md index 9375ed470629cba6112c1897db9f7b475d43cb3d..6d5ed225c67dc43d7024fd0e609e8f5eb18c38ea 100644 --- a/en/application-dev/database/database-storage-guidelines.md +++ b/en/application-dev/database/database-storage-guidelines.md @@ -76,19 +76,24 @@ Use the following APIs to delete a **Storage** instance or data file. 1. Import **@ohos.data.storage** and related modules to the development environment. ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' // Used to obtain the file storage path. + import dataStorage from '@ohos.data.storage'; + import featureAbility from '@ohos.ability.featureAbility'; // Used to obtain the file storage path. ``` 2. Create a **Storage** instance. Read the specified file and load its data to the **Storage** instance for data operations. - ```js - var context = featureAbility.getContext() - var path = await context.getFilesDir() - let promise = dataStorage.getStorage(path + '/mystore') - ``` + ```js + var path; + var context = featureAbility.getContext(); + context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); + }); + + let promise = dataStorage.getStorage(path + '/mystore'); + ``` 3. Write data. @@ -97,14 +102,14 @@ Use the following APIs to delete a **Storage** instance or data file. ```js promise.then((storage) => { - let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance. + let getPromise = storage.put('startup', 'auto'); // Save data to the Storage instance. getPromise.then(() => { - console.info("Put the value of startup successfully.") + console.info("Succeeded in putting the value of startup."); }).catch((err) => { - console.info("Put the value of startup failed with err: " + err) + console.info("Failed to put the value of startup with err: " + err); }) }).catch((err) => { - console.info("Get the storage failed") + console.info("Failed to get the storage."); }) ``` @@ -115,14 +120,14 @@ Use the following APIs to delete a **Storage** instance or data file. ```js promise.then((storage) => { - let getPromise = storage.get('startup', 'default') + let getPromise = storage.get('startup', 'default'); getPromise.then((value) => { - console.info("The value of startup is " + value) + console.info("The value of startup is " + value); }).catch((err) => { - console.info("Get the value of startup failed with err: " + err) + console.info("Failed to get the value of startup with err: " + err); }) }).catch((err) => { - console.info("Get the storage failed") + console.info("Failed to get the storage."); }) ``` @@ -142,15 +147,15 @@ Use the following APIs to delete a **Storage** instance or data file. ```js promise.then((storage) => { var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key of " + key + " changed."); } - storage.on('change', observer) - storage.putSync('startup', 'auto') // Modify data in the Storage instance. - storage.flushSync() // Trigger the StorageObserver callback. + storage.on('change', observer); + storage.putSync('startup', 'auto'); // Modify data in the Storage instance. + storage.flushSync(); // Trigger the StorageObserver callback. - storage.off(...change..., observer) // Unsubscribe from the data changes. + storage.off('change', observer); // Unsubscribe from the data changes. }).catch((err) => { - console.info("Get the storage failed") + console.info("Failed to get the storage."); }) ``` @@ -160,11 +165,11 @@ Use the following APIs to delete a **Storage** instance or data file. Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. ```js - let promise = dataStorage.deleteStorage(path + '/mystore') + let promise = dataStorage.deleteStorage(path + '/mystore'); promise.then(() => { - console.info("Deleted successfully.") + console.info("Succeeded in deleting the storage."); }).catch((err) => { - console.info("Deleted failed with err: " + err) + console.info("Failed to deleted the storage with err: " + err); }) ``` diff --git a/en/application-dev/database/database-storage-overview.md b/en/application-dev/database/database-storage-overview.md index 45639c75e8ad5d1b3f68c79da90fbc598af7e840..6bf3acda7d8eb9efac54b38474eeea5b2c35c4fd 100644 --- a/en/application-dev/database/database-storage-overview.md +++ b/en/application-dev/database/database-storage-overview.md @@ -1,31 +1,32 @@ -# Lightweight Data Store Overview +# Lightweight Data Store Overview -Lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight **Storage** instance, data in the **Storage** instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. +The lightweight data store is applicable to access and persistence of data in the key-value structure. -## Basic Concepts +After an application obtains a lightweight store instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. -- **Key-Value data structure** +You do not need to care about the implementation of the database lock mechanism. - A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. +## Basic Concepts -- **Non-relational database** +- **Key-value structure** - A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. The data in a non-relational database is independent. + A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. +- **Non-relational database** -## Working Principles + A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. -1. When an application loads data from a specified **Storage** file to a **Storage** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file. -2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method. +## Working Principles -**Figure 1** How lightweight data store works +1. An application can load data from a specified **Storage** file to a **Storage** instance. The system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file. +2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method. +**Figure 1** Working mechanism ![](figures/en-us_image_0000001199139454.png) -## Constraints - -- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. -- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters. -- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters. +## Constraints +- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. +- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. +- The value of the string type can be empty, but cannot exceed 8192 bytes if not empty. diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index ed6d64d2f532114c44220f493fcdce9180d0aa1f..006157006ef345b172be25256dc0ddc04958152b 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -1,4 +1,4 @@ -## Device Usage Statistics Development +# Device Usage Statistics Development ## When to Use @@ -56,7 +56,9 @@ import stats from '@ohos.bundleState'; // Use an asynchronous callback to return the result. stats.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)); @@ -74,21 +76,23 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Use a promise to return the result. - stats.queryBundleStateInfos(0, 20000000000000).then( res => { + stats.queryBundleStateInfos(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); let i = 1; - for(let key in res){ + for (let key in res) { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); i++; } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); }); // Use an asynchronous callback to return the result. stats.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){ @@ -108,26 +112,26 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Use a promise to return the result. - stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { + stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); }); // Use an asynchronous callback to return the result. stats.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); } }); ``` @@ -138,26 +142,26 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Use a promise to return the result. - stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { + stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); }); // Use an asynchronous callback to return the result. stats.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); } }); ``` @@ -168,18 +172,18 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Use a promise to return the result. - stats.queryAppUsagePriorityGroup().then( res => { + stats.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); // Use an asynchronous callback to return the result. stats.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)); } }); ``` @@ -190,18 +194,18 @@ import stats from '@ohos.bundleState'; import stats from '@ohos.bundleState' // Use a promise to return the result. - stats.isIdleState("com.ohos.camera").then( res => { + stats.isIdleState("com.ohos.camera").then(res => { console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); }); // Use an asynchronous callback to return the result. stats.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)); } }); ``` diff --git a/en/application-dev/device/device-location-geocoding.md b/en/application-dev/device/device-location-geocoding.md index cfb2504ff30266bdba5699b44f5f0577cc953ea9..e0080e3e87ddfc28779c7023c75d464e23af78da 100644 --- a/en/application-dev/device/device-location-geocoding.md +++ b/en/application-dev/device/device-location-geocoding.md @@ -3,9 +3,9 @@ ## When to Use -Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. +Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. -With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc. +The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address. ## Available APIs @@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord | API | Description | | -------- | -------- | -| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. | -| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. | -| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. | -| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. | +| isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. | +| isGeoServiceAvailable() : Promise<boolean> | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. | +| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. | +| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. | +| getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. | ## How to Develop -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> > The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. 1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. @@ -45,7 +46,7 @@ The following table describes APIs available for mutual conversion between coord }); ``` - Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see the _API Reference_. + Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). - Call **getAddressesFromLocationName** to convert geographic description into coordinates. ``` @@ -55,6 +56,6 @@ The following table describes APIs available for mutual conversion between coord }); ``` - Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the _API Reference_. + Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md). To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index e3d2e4155798eb69904ec7c819ef3702604dd1bf..1a23762efeea7e059ab2a1b6a34050f6ef662efd 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -14,47 +14,49 @@ The following table describes APIs available for obtaining device location infor **Table 1** APIs for obtaining device location information -| API| Description| -| -------- | -------- | -| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated.| -| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted.| -| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events.| -| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events.| -| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports.| -| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports.| -| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events.| -| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events.| -| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events.| -| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events.| -| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence.| -| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence.| -| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. | -| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. | -| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result.| -| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. | -| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.| -| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result.| -| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result.| -| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result.| -| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result.| -| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result.| -| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This function uses an asynchronous callback to return the result.| -| disableLocation() : Promise<boolean> | Disables the location service. This function uses a promise to return the result.| -| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This function uses an asynchronous callback to return the result.| -| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This function uses a promise to return the result.| -| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses an asynchronous callback to return the result.| -| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This function uses a promise to return the result.| -| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This function uses an asynchronous callback to return the result.| -| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This function uses a promise to return the result.| -| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This function uses an asynchronous callback to return the result.| -| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This function uses a promise to return the result.| -| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This function uses an asynchronous callback to return the result.| -| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This function uses a promise to return the result.| +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated. | +| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. | +| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. | +| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. | +| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. | +| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. | +| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. | +| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. | +| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events. | +| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events. | +| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence. | +| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence. | +| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. | +| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. | +| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result. | +| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. | +| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. | +| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result. | +| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result. | +| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result. | +| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result. | +| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result. | +| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This API uses an asynchronous callback to return the result. | +| disableLocation() : Promise<boolean> | Disables the location service. This API uses a promise to return the result. | +| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result. | +| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This API uses a promise to return the result. | +| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.| +| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.| +| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.| +| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This API uses a promise to return the result. | +| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.| +| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.| +| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.| +| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.| ## How to Develop -1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user. For details, see . +To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md). + +1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. The system provides the following location permissions: - ohos.permission.LOCATION @@ -62,11 +64,11 @@ The following table describes APIs available for obtaining device location infor The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information. - If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background. + If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: - + ``` { "module": { @@ -82,20 +84,21 @@ The following table describes APIs available for obtaining device location infor } ``` - For details about the configuration fields, see the description of the **module.json** file. + For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. - + ``` import geolocation from '@ohos.geolocation'; ``` -3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information.
+3. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information. + **Method 1:** To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported. - + ``` export enum LocationRequestScenario { UNSET = 0x300, @@ -107,28 +110,28 @@ The following table describes APIs available for obtaining device location infor } ``` - + **Table 2** Common use cases of the location function - | Use Case| Constant| Description| - | -------- | -------- | -------- | - | Navigation| NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency| NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. 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.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - - The following example instantiates the **RequestParam** object for navigation: - + | Use Case | Constant | Description | + | ------------ | ------------------- | ------------------------------------------------------------ | + | Navigation | NAVIGATION | Applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Trajectory tracking| TRAJECTORY_TRACKING | Applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Life service| DAILY_LIFE_SERVICE | Applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Power efficiency | NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. 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.
By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + + Sample code for initializing **requestInfo** for navigation: + ``` - var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` **Method 2:** If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system. - + ``` export enum LocationRequestPriority { UNSET = 0x200, @@ -138,19 +141,19 @@ The following table describes APIs available for obtaining device location infor } ``` - + **Table 3** Location priority policies - | Policy| Constant| Description| - | -------- | -------- | -------- | - | Location accuracy priority| ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Fast location priority| FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| - | Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Policy | Constant | Description | + | ------------------ | -------------- | ------------------------------------------------------------ | + | Location accuracy priority | ACCURACY | This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Fast location priority | FAST_FIRST_FIX | This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. This policy can lead to significant hardware resource consumption and power consumption.
To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| + | Power efficiency priority| LOW_POWER | This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| - The following example instantiates the **RequestParam** object for the location accuracy priority policy: - + Sample code for initializing **requestInfo** for the location accuracy priority policy: + ``` - var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; ``` 4. Instantiate the **Callback** object for the system to report location results. @@ -163,22 +166,26 @@ The following table describes APIs available for obtaining device location infor ``` 5. Start device location. - + ``` geolocation.on('locationChange', requestInfo, locationChange); ``` 6. (Optional) Stop device location. - + ``` geolocation.off('locationChange', locationChange); ``` - If your application does not need the real-time device location, it can use the last known device location cached in the system instead. +If your application does not need the real-time device location, it can use the last known device location cached in the system instead. ``` - geolocation.getLastLocation((data) => { - console.log('getLastLocation: data: ' + JSON.stringify(data)); + geolocation.getLastLocation((err, data) => { + if (err) { + console.log('getLastLocation: err: ' + JSON.stringify(err)); + } else { + console.log('getLastLocation: data: ' + JSON.stringify(data)); + } }); ``` diff --git a/en/application-dev/device/sensor-guidelines.md b/en/application-dev/device/sensor-guidelines.md index ca434c9639e064dda463873dee8fdf701271181b..dcfffc55a6400f21c9180ee3306af16ae8713119 100644 --- a/en/application-dev/device/sensor-guidelines.md +++ b/en/application-dev/device/sensor-guidelines.md @@ -37,7 +37,7 @@ "reqPermissions":[ { "name":"ohos.permission.ACCELEROMETER", - "reason"":"", + "reason":"", "usedScene":{ "ability": ["sensor.index.MainAbility",".MainAbility"], "when":"inuse" @@ -45,7 +45,7 @@ }, { "name":"ohos.permission.GYROSCOPE", - "reason"":"", + "reason":"", "usedScene":{ "ability": ["sensor.index.MainAbility",".MainAbility"], "when":"inuse" @@ -53,7 +53,7 @@ }, { "name":"ohos.permission.ACTIVITY_MOTION", - "reason"":"ACTIVITY_MOTION_TEST", + "reason":"ACTIVITY_MOTION_TEST", "usedScene":{ "ability": ["sensor.index.MainAbility",".MainAbility"], "when":"inuse" @@ -61,7 +61,7 @@ }, { "name":"ohos.permission.READ_HEALTH_DATA", - "reason"":"HEALTH_DATA_TEST", + "reason":"HEALTH_DATA_TEST", "usedScene":{ "ability": ["sensor.index.MainAbility",".MainAbility"], "when":"inuse" @@ -123,8 +123,3 @@ console.error(error); } ``` -## Samples - -The following sample is provided to help you better understand how to develop sensors: - -- [`Sensor`: sensor (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor) diff --git a/en/application-dev/device/sensor-overview.md b/en/application-dev/device/sensor-overview.md index 3f891e75ceea0d9c426b3739d3b085d5fde806a9..671cc29ade0a832dc835ab4c03529ef9c9771280 100644 --- a/en/application-dev/device/sensor-overview.md +++ b/en/application-dev/device/sensor-overview.md @@ -1,7 +1,7 @@ # Sensor Overview -Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. +Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: @@ -37,7 +37,7 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso **Figure 1** How the sensor works -![en-us_image_0000001226521897.png](figures/en-us_image_0000001226521897.png) +![fad1a124-a90e-460f-84fc-e87d6caebb21](figures/fad1a124-a90e-460f-84fc-e87d6caebb21.png) - Sensor API: provides APIs for performing basic operations on sensors, including querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. This module makes application development simpler. diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 5e3e6ba1c139a6bf5717865a040884d8ce6e40a4..e026109ca3d34b44f69d2ae4752425febbd2116c 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -16,7 +16,7 @@ The following table lists the USB APIs currently available. For details, see the | ------------------------------------------------------------ | ------------------------------------------------------------ | | hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | | requestRight(deviceName: string): Promise\ | Requests the temporary permission for a given application to access the USB device. | -| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device information returned by **getDevices()**. | +| connectDevice(device: USBDevice): Readonly\ | Connects to the USB device based on the device information returned by `getDevices()`. | | getDevices(): Array> | Obtains the USB device list. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | @@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The Claim the corresponding interface from deviceList. interface1 must be one present in the device configuration. */ - usb.claimInterface(pipe , interface1, 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 0915792d90590cac0719e4f4933e0b1fc4b5ab12..9731fa6cec8da388719b61cf7cf7b0e542f87ca4 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -5,53 +5,55 @@ You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls. +For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md). + ## Available APIs | 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":[ + "reqPermissions": [ { - "name":"ohos.permission.ACCELEROMETER", - "reason"":"", - "usedScene":{ - "ability""[ - ".MainAbility" + "name": "ohos.permission.ACCELEROMETER", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" ], - "when":"inuse" + "when": "inuse" } }, { - "name":"ohos.permission.VIBRATE", - "reason"":"", - "usedScene":{ - "ability""[ - ".MainAbility" + "name": "ohos.permission.VIBRATE", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" ], - "when":"inuse" + "when": "inuse" } }, { - "name":"ohos.permission.ACTIVITY_MOTION", - "reason"":"", - "usedScene":{ - "ability""[ - ".MainAbility" + "name": "ohos.permission.ACTIVITY_MOTION", + "reason": "", + "usedScene": { + "ability": [ + ".MainAbility" ], - "when":"inuse" + "when": "inuse" } }, ] @@ -63,9 +65,9 @@ You can set different vibration effects as needed, for example, customizing the import vibrator from "@ohos.vibrator" 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); + 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.") + Console.log("Promise returned to indicate a successful vibration.") }; }) ``` @@ -76,15 +78,9 @@ You can set different vibration effects as needed, for example, customizing the import vibrator from "@ohos.vibrator" 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); + Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); }else{ // The call is successful, and the device stops vibrating. Console.log("Promise returned to indicate a successful stop."); }; }) ``` - -## Samples - -The following sample is provided to help you better understand how to develop vibrators: - -- [`Vibrator`: vibrator (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator) diff --git a/en/application-dev/device/vibrator-overview.md b/en/application-dev/device/vibrator-overview.md index 191d74b591e6fe296cf80c7874cc0a60b50dad7f..05e9b06d5c906c7e0ad46a6dc7e7f65400b6bc20 100644 --- a/en/application-dev/device/vibrator-overview.md +++ b/en/application-dev/device/vibrator-overview.md @@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ## Constraints -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**. +When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index ee553b735fb510d78ee6531e0a8a71fa99fc53bb..e1d4cddeb2ff96c8a07a6df84382ad0b8d22464c 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -88,9 +88,3 @@ 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. - -## Samples - -The following sample is provided to help you better understand how to develop the application event logging feature: - -- [`JsDotTest`: Event Logging Test (JavaScript) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 1be7b7dff8fe59b423fa2766b81dc6c164aeec31..adfcf2ffb719e60b44e25d5747a28404c5784413 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,15 +1,17 @@ -# Internationalization Development (i18n) +# Internationalization Development (I18N) -This development guide describes how to use i18n APIs that are not defined in ECMA 402. +This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md). + +The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. ## Obtaining System Language and Region Information -APIs are provided to access the system language and region information. +You can use APIs provided in the following table to obtain the system language and region information. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.i18n | getSystemLanguage(): string | Obtains the system language. | | ohos.i18n | getSystemRegion(): string | Obtains the system region. | @@ -17,52 +19,57 @@ APIs are provided to access the system language and region information. | ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | | ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | | ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country. | +| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | ### How to Develop 1. Obtain the system language. - Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). + + Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). - ``` + ```js var language = i18n.getSystemLanguage(); ``` -2. Obtains the system region. - Call the **getSystemRegion** method to obtain the system region. +2. Obtain the system region. + + Call the **getSystemRegion** method to obtain the system region. - ``` + ```js var region = i18n.getSystemRegion(); ``` 3. Obtain the system locale. - Call the **getSystemLocale** method to obtain the system locale. + + Call the **getSystemLocale** method to obtain the system locale. - ``` + ```js var locale = i18n.getSystemLocale(); ``` 4. Check whether the locale's language is RTL. - Call the **isRTL** method to check whether the locale's language is RTL. + Call the **isRTL** method to check whether the locale's language is RTL. - ``` + ```js var rtl = i18n.isRTL("zh-CN"); ``` 5. Check whether the system uses a 24-hour clock. - Call the **is24HourClock** method to check whether the system uses a 24-hour clock. + + Call the **is24HourClock** method to check whether the system uses a 24-hour clock. - ``` + ```js var hourClock = i18n.is24HourClock(); ``` 6. Obtain the localized display of a language. - Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. + + Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - ``` + ```js var language = "en"; var locale = "zh-CN"; var sentenceCase = false; @@ -70,9 +77,10 @@ APIs are provided to access the system language and region information. ``` 7. Obtain the localized display of a country. - Call the **getDisplayCountry** method to obtain the localized display of a country. **country** indicates the country to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. + + Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - ``` + ```js var country = "US"; var locale = "zh-CN"; var sentenceCase = false; @@ -82,7 +90,7 @@ APIs are provided to access the system language and region information. ## Obtaining Calendar Information -[Calendar](../reference/apis/js-apis-intl.md) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. +[Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. ### Available APIs @@ -106,17 +114,19 @@ APIs are provided to access the system language and region information. ### How to Develop 1. Instantiate a **Calendar** object. - Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. + + Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - ``` - var calendar = i18n.getCalendar("zh-CN", "gregory); + ```js + var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` 2. Set the time for the **Calendar** object. - Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. + + Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - ``` + ```js var date1 = new Date(); calendar.setTime(date1); var date2 = 1000; @@ -124,51 +134,57 @@ APIs are provided to access the system language and region information. ``` 3. Set the year, month, day, hour, minute, and second for the **Calendar** object. - Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. + + Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - ``` + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` 4. Set and obtain the time zone for the **Calendar** object. - Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. + + Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. - ``` + ```js calendar.setTimeZone("Asia/Shanghai"); var timezone = calendar.getTimeZone(); ``` 5. Set and obtain the first day of a week for the **Calendar** object. - Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. + + Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. - ``` + ```js calendar.setFirstDayOfWeek(1); var firstDayOfWeek = calendar.getFirstDayOfWeek(); ``` 6. Set and obtain the minimum count of days in the first week for the **Calendar** object. - Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. + + Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - ``` + ```js calendar.setMinimalDaysInFirstWeek(3); var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); ``` 7. Obtain the localized display of the **Calendar** object. - Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. + + Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. - ``` + ```js var localizedName = calendar.getDisplayName("zh-CN"); ``` 8. Check whether a date is a weekend. - Call the **isWeekend** method to determine whether the input date is a weekend. + + Call the **isWeekend** method to determine whether the input date is a weekend. - ``` + ```js var date = new Date(); var weekend = calendar.isWeekend(date); ``` @@ -176,12 +192,12 @@ APIs are provided to access the system language and region information. ## Formatting a Phone Number -[PhoneNumberFormat](../reference/apis/js-apis-intl.md) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. +[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | | ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | @@ -191,47 +207,49 @@ APIs are provided to access the system language and region information. ### How to Develop 1. Instantiate a **PhoneNumberFormat** object. - Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. + + Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. - ``` - var phoneNumberFormat = new i18n.PhoneNubmerFormat("CN", {type: "E164"}); + ```js + var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); ``` 2. Check whether the phone number format is correct. - Call the **isValidNumber** method to check whether the format of the input phone number is correct. + + Call the **isValidNumber** method to check whether the format of the input phone number is correct. - ``` + ```js var validNumber = phoneNumberFormat.isValidNumber("15812341234"); ``` 3. Format a phone number. - Call the **format** method of **PhoneNumberFormat** to format the input phone number. + + Call the **format** method of **PhoneNumberFormat** to format the input phone number. - ``` + ```js var formattedNumber = phoneNumberFormat.format("15812341234"); ``` ## Measurement Conversion -An API can be called to implement measurement conversion. +The **unitConvert** API is provided to help you implement measurement conversion. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | ### How to Develop -1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result. +Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. - ``` + ```js var fromUnit = {unit: "cup", measureSystem: "US"}; var toUnit = {unit: "liter", measureSystem: "SI"}; var number = 1000; @@ -243,7 +261,7 @@ An API can be called to implement measurement conversion. ## Alphabet Index -[IndexUtil](../reference/apis/js-apis-intl.md) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. +[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. ### Available APIs @@ -259,31 +277,35 @@ An API can be called to implement measurement conversion. ### How to Develop 1. Instantiate an **IndexUtil** object. - Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. + + Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - ``` - var indexUtil = getInstance("zh-CN"); + ```js + var indexUtil = i18n.getInstance("zh-CN"); ``` 2. Obtain the index list. - Call the **getIndexList** method to obtain the alphabet index list of the current locale. + + Call the **getIndexList** method to obtain the alphabet index list of the current locale. - ``` + ```js var indexList = indexUtil.getIndexList(); ``` 3. Add an index. - Call the **addLocale** method to add the alphabet index of a new locale to the current index list. + + Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - ``` + ```js indexUtil.addLocale("ar") ``` 4. Obtain the index of a string. - Call the **getIndex** method to obtain the alphabet index of a string. + + Call the **getIndex** method to obtain the alphabet index of a string. - ``` + ```js var text = "access index"; indexUtil.getIndex(text); ``` @@ -291,7 +313,7 @@ An API can be called to implement measurement conversion. ## Obtaining Line Breaks of Text -When a text is displayed in more than one line, [BreakIterator](../reference/apis/js-apis-intl.md) APIs are used to obtain the line break positions of the text. +When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text. ### Available APIs @@ -313,52 +335,57 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api ### How to Develop 1. Instantiate a **BreakIterator** object. - Call the **getLineInstance** method to instantiate a **BreakIterator** object. + + Call the **getLineInstance** method to instantiate a **BreakIterator** object. - ``` + ```js var locale = "en-US" var breakIterator = i18n.getLineInstance(locale); ``` 2. Set and access the text that requires line breaking. - Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. + + Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. - ``` + ```js var text = "Apple is my favorite fruit"; breakIterator.setLineBreakText(text); var breakText = breakIterator.getLineBreakText(); ``` 3. Obtain the current position of the **BreakIterator** object. - Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. + + Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. - ``` + ```js var pos = breakIterator.current(); ``` 4. Set the position of a **BreakIterator** object. - The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. + + The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. - ``` - var firstPos = breakIterator.first(); // Sets a BreakIterator object to the first break point, that is, the start position of the text. - var lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end. - // Moves a BreakIterator object forward or backward by a certain number of break points. + ```js + var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. + var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end. + // Move a BreakIterator object forward or backward by a certain number of break points. // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. // When the object is moved out of the text length range, -1 is returned. var nextPos = breakIterator.next(-2); - var previousPos = breakIterator.previous(); // Moves a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. - // Moves a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. + var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. + // Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. var followingPos = breakIterator.following(10); ``` 5. Determine whether a position is a break point. - Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. + + Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. - ``` + ```js var isboundary = breakIterator.isBoundary(5); ``` diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 76c00eb557816681efb54e9e7ec5d0a3754471b6..363b4a37b2dfccbda8602c5f24987d14261a9036 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,15 +1,21 @@ -# Internationalization Development (intl) +# Internationalization Development (Intl) -This development guide describes how to use i18n APIs that are defined in ECMA 402. +This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md). + +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. + +> **NOTE** +> +> In the code snippets in this document, **intl** refers to the name of the imported module. ## Setting Locale Information -[Locale](../reference/apis/js-apis-intl.md) APIs are used to maximize or minimize locale information. +Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Instantiates a **Locale** object. | | ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | @@ -21,45 +27,63 @@ This development guide describes how to use i18n APIs that are defined in ECMA 4 ### How to Develop 1. Instantiate a **Locale** object. - Create a **Locale** object using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list (**intl** is the name of the imported module). + + Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list. + + A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). + - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. + - Script: optional. It is represented by a four-letter code as defined in ISO-15924. The first letter is in uppercase, and the remaining three letters are in lowercase. For example, **Hant** represents the traditional Chinese, and **Hans** represents the simplified Chinese. + - Country or region: optional. It is represented by two-letter code as defined in ISO-3166. Both letters are in uppercase. For example, **CN** represents China, and **US** represents the United States. + - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the Latin numbering system and Chinese calendar system are used. Extensions can also be passed via the second parameter. + | Extended Parameter ID| Description| + | -------- | -------- | + | ca | Calendar algorithm.| + | co | Collation type.| + | hc | Hour cycle.| + | nu | Numbering system.| + | kn | Whether numeric collation is used when sorting or comparing strings.| + | kf | Whether upper case or lower case is considered when sorting or comparing strings.| - ``` + ```js var locale = "zh-CN"; - var options = {caseFirst: false, calendar: "chinese", collation: pinyin}; + var options = {caseFirst: false, calendar: "chinese", collation: "pinyin"}; var localeObj = new intl.Locale(locale, options); ``` 2. Obtain the string representing a **Locale** object. - Call the **toString** method to obtain the string representing a **Locale** object, including the language, region, and other options. - - ``` + + Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. + + ```js var localeStr = localeObj.toString(); ``` 3. Maximize locale information. - Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. - - ``` + + Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. + + ```js var maximizedLocale = localeObj.maximize(); ``` 4. Minimize locale information. - Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. - - ``` + + Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. + + ```js var minimizedLocale = localeObj.minimize(); ``` ## Formatting the Date and Time -[DateTimeFormat](../reference/apis/js-apis-intl.md) APIs are used to format the date and time for a specific locale. +Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | | ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | @@ -71,149 +95,160 @@ This development guide describes how to use i18n APIs that are defined in ECMA 4 ### How to Develop 1. Instantiate a **DateTimeFormat** object. - Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object (**intl** is the name of the imported module). + + Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. - ``` + ```js var dateTimeFormat = new intl.DateTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). - ``` + ```js var options = {dateStyle: "full", timeStyle: "full"}; var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); ``` 2. Format the date and time. - Use the **format** method of **DateTimeFormat** to format a **Date** object. A string is returned as the formatting result. - - ``` - Date date = new Date(); + + Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. + + ```js + var date = new Date(); var formatResult = dateTimeFormat.format(date); ``` 3. Format a period. - Use the **formatRange** method of **DateTimeFormat** to format a period. This method requires the input of two **Date** objects, which respectively indicate the start date and end date of a period. A string is returned as the formatting result. - - ``` - Date startDate = new Date(); - Date endDate = new Date(); - var formatResult = dateTimeFormat.formatRange(startDate, endDate); - ``` -4. Access the attributes of the **DateTimeFormat** object. - The **resolvedOptions** method of **DateTimeFormat** returns an object that contains all related attributes and values of the **DateTimeFormat** object. - + Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. + + ```js + var startDate = new Date(2021, 11, 17, 3, 24, 0); + var endDate = new Date(2021, 11, 18, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.formatRange(startDate, endDate); ``` + +4. Obtain attributes of the **DateTimeFormat** object. + + Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. + + ```js var options = dateTimeFormat.resolvedOptions(); ``` -## Number Formatting +## Formatting Numbers -[NumberFormat](../reference/apis/js-apis-intl.md) APIs are used to format a number for a specific locale. +Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | | ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | | ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains the attributes of the **NumberFormat** object. | +| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | ### How to Develop 1. Instantiate a **NumberFormat** object. - Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **NumberFormat** object (**intl** is the name of the imported module). + + Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object. - ``` + ```js var numberFormat = new intl.NumberFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). - ``` + ```js var options = {compactDisplay: "short", notation: "compact"}; var numberFormat = new intl.NumberFormat("zh-CN", options); ``` 2. Format a number. - Use the **format** method of **NumberFormat** to format a number. A string is returned as the formatting result. - - ``` + + Call the **format** method to format a number. A string is returned as the formatting result. + + ```js var number = 1234.5678 var formatResult = numberFormat.format(number); ``` -3. Access the attributes of the **NumberFormat** object. - The **resolvedOptions** method of NumberFormat returns an object that contains all related attributes and values of the **NumberFormat** object. - - ``` +3. Obtain attributes of the **NumberFormat** object. + + Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. + + ```js var options = numberFormat.resolvedOptions(); ``` -## String Sorting +## Sorting Strings -Users in different regions have different requirements for string sorting. [Collator](../reference/apis/js-apis-intl.md) APIs are used to sort strings based on a specific locale. +Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Creates a **Collator** object. | | ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | | ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains the attributes of the **Collator** object. | +| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | ### How to Develop 1. Instantiate a **Collator** object. - Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **Collator** object (**intl** is the name of the imported module). + + Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object. - ``` + ```js var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). - ``` - var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}; + ```js + var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); ``` 2. Compare two strings. - Use the **compare** method of **Collator** to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. - - ``` + + Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + + ```js var str1 = "first string"; var str2 = "second string"; var compareResult = collator.compare(str1, str2); ``` -3. Access the attributes of the **Collator** object. - The **resolvedOptions** method of **Collator** returns an object that contains all related attributes and values of the **Collator** object. - - ``` +3. Obtain attributes of the **Collator** object. + + Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. + + ```js var options = collator.resolvedOptions(); ``` ## Determining the Singular-Plural Type -According to grammars in certain languages, the singular or plural form of a noun depends on the number prior to the noun. [PluralRules](../reference/apis/js-apis-intl.md) APIs are used to determine the singular-plural type for a specific locale. +Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Creates a **PluralRules** object. | | ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | @@ -223,82 +258,88 @@ According to grammars in certain languages, the singular or plural form of a nou ### How to Develop 1. Instantiate a **PluralRules** object. - Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **PluralRules** object (**intl** is the name of the imported module). + + Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object. - ``` + ```js var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). - ``` - var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}; + ```js + var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); ``` -2. Determine the singular or plural category. - Use the **select** method of **PluralRules** to determine the singular-plural type for an input number. This method returns a string as the category of the input number, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. - - ``` +2. Determine the singular-plural type. + + Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + + ```js var number = 1234.5678 var categoryResult = plurals.select(number); ``` -## Formatting Relative Time +## Formatting the Relative Time -[RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs are used to format the relative time for a specific locale. +Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale. ### Available APIs - | Module | API | Description | +| Module | API | Description | | -------- | -------- | -------- | | ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | | ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | | ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | | ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains the attributes of the **RelativeTimeFormat** object. | +| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | ### How to Develop 1. Instantiate a **RelativeTimeFormat** object. - Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **RelativeTimeFormat** object (**intl** is the name of the imported module). + + Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object. - ``` + ```js var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). - ``` - var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}; + ```js + var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); ``` 2. Format the relative time. - Use the **format** method of **RelativeTimeFormat** to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. A string is returned as the formatting result. - - ``` + + Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. + + ```js var number = 2; var unit = "year" var formatResult = relativeTimeFormat.format(number, unit); ``` 3. Obtain each part of the relative time format. - On obtaining each part of the relative time format, customize the relative time formatting result. - - ``` + + Upon obtaining each part of the relative time format, customize the relative time formatting result. + + ```js var number = 2; var unit = "year" var formatResult = relativeTimeFormat.formatToParts(number, unit); ``` -4. Access the attributes of the **RelativeTimeFormat** object. - The **resolvedOptions** method of **RelativeTimeFormat** returns an object that contains all related attributes and values of the **RelativeTimeFormat** object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). - - ``` +4. Obtain attributes of the **RelativeTimeFormat** object. + + Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). + + ```js var options = numberFormat.resolvedOptions(); ``` @@ -306,4 +347,6 @@ According to grammars in certain languages, the singular or plural form of a nou The following sample is provided to help you better understand how to develop internationalization capabilities: --[`International`: Internationalization (JS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/UI/International) +-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) + +-[`International`: Internationalization (eTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index b425aa8618b7a9d40f23bcc6de622ab30f03d0b1..faf977c7b42644a03066947e45996a936529f8cc 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -39,38 +39,38 @@ function printfDescription(obj) { // Set the player callbacks. function setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. + audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. + audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. }); - audioPlayer.on('pause', () => { // Set the 'pause' event callback. + audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.info('audio pause success'); - audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. + audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. }); - audioPlayer.on('stop', () => { // Set the 'stop' event callback. + audioPlayer.on('stop', () => { // Set the 'stop' event callback. console.info('audio stop success'); - audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. + audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. }); - audioPlayer.on('reset', () => { // Set the 'reset' event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio reset success'); - audioPlayer.release(); // Release the AudioPlayer resources. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); - audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. + audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. if (typeof(seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; } console.info('audio seek success, and seek time is ' + seekDoneTime); - audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. + audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. }); - audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.info('audio volumeChange success'); - audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. + audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. if (typeof (arrlist) != 'undefined') { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); @@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { } else { console.log(`audio getTrackDescription fail, error:${error.message}`); } - audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. + audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback. }); }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); }); - audioPlayer.on('error', (error) => { // Set the 'error' 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, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); @@ -92,10 +92,10 @@ function setCallBack(audioPlayer) { } async function audioPlayerDemo() { - // 1. Create an audioPlayer instance. + // 1. Create an AudioPlayer instance. let audioPlayer = media.createAudioPlayer(); - setCallBack(audioPlayer); // Set the event callbacks. - // 2. Set the URI of the audio file selected by the user. + setCallBack(audioPlayer); // Set the event callbacks. + // 2. Set the URI of the audio file. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -119,23 +119,23 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); - audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. console.info('audio play finish'); - audioPlayer.release(); // Release the AudioPlayer resources. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -161,20 +161,20 @@ export class AudioDemo { // Set the player callbacks. private isNextMusic = false; setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the 'play' event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); - audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. + audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. }); - audioPlayer.on('reset', () => { // Set the 'reset' event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio play success'); - if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. - this.nextMusic(audioPlayer); // Changing songs is implemented. + if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. + this.nextMusic(audioPlayer); // Changing songs is implemented. } else { - audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; } }); @@ -197,8 +197,8 @@ export class AudioDemo { } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -223,19 +223,19 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); - audioPlayer.loop = true; // Set the loop playback attribute. - audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. + audioPlayer.loop = true; // Set the loop playback attribute. + audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Sets the 'play' event callback to start loop playback. + audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback. console.info('audio play success'); }); } async audioPlayerDemo() { - let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. - this.setCallBack(audioPlayer); // Set the event callbacks. + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. + this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; @@ -251,12 +251,3 @@ export class AudioDemo { } } ``` - -## Samples - -The following samples are provided to help you better understand how to develop audio playback: - -- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer) -- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer) -- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index ee93e267eb4a12fcdc7facf044e16248a938f266..b2686af80980cad565ab65fd1166217baba23154 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -185,11 +185,3 @@ export class AudioRecorderDemo { } } ``` - -## Samples - -The following samples are provided to help you better understand how to develop audio recording: - -- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder) -- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) diff --git a/en/application-dev/media/public_sys-resources/icon-caution.gif b/en/application-dev/media/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/media/public_sys-resources/icon-danger.gif b/en/application-dev/media/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/media/public_sys-resources/icon-note.gif b/en/application-dev/media/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/media/public_sys-resources/icon-notice.gif b/en/application-dev/media/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/media/public_sys-resources/icon-tip.gif b/en/application-dev/media/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/media/public_sys-resources/icon-warning.gif b/en/application-dev/media/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/media/public_sys-resources/icon-warning.gif differ diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index 3aab853a699f7ac9b2d9fe2a6f7da9bf03d994cd..5b98b99e44b336ae54edfa4ba0edb4a70087c368 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -445,8 +445,3 @@ export class VideoPlayerDemo { } } ``` - -## Samples -The following samples are provided to help you better understand how to develop video playback: - -- [`VideoPlayer`: Video Playback (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer) diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index b34a02ddc209ad3c0c4feec76bce3247fbdb5b27..280efd8afa5fa845dab0d607ed94b33e2a75e6d3 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -2,6 +2,7 @@ - [Using Native APIs in Application Projects](napi-guidelines.md) - [Drawing Development](drawing-guidelines.md) -- [Native Window Development](native_window-guidelines.md) - [Raw File Development](rawfile-guidelines.md) +- [Native Window Development](native-window-guidelines.md) + diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md index e813f84d92d4155e78c9ca651af6a3e3cd010232..7cbf0e3d9e10bb6d8d346e8f6a9910771c523434 100644 --- a/en/application-dev/napi/drawing-guidelines.md +++ b/en/application-dev/napi/drawing-guidelines.md @@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of double position[2] = {10.0, 15.0}; OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); ``` - -## Samples - -The following samples are provided to help you better understand how to use the Native Drawing module: -* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp) -* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp) diff --git a/en/application-dev/napi/native_window-guidelines.md b/en/application-dev/napi/native-window-guidelines.md similarity index 100% rename from en/application-dev/napi/native_window-guidelines.md rename to en/application-dev/napi/native-window-guidelines.md diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index f46e565f2a9d203a056e6f9ceed055b81e8dcf08..3884cf1c364b7d2e92e11a4560ad46e6997eade7 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -169,9 +169,3 @@ if (this.subscriber != null) { }) } ``` - -## Samples - -The following sample is provided to help you better understand how to use the common event functionality: - -- [`CommonEvent`: eTS Common Event (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent) diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md index 107346659df11ffa808dc8701c9c971721a13282..9d4ce8d3b78bc59c3b92ac43b85c6415d67b03d6 100644 --- a/en/application-dev/notification/notification-guidelines.md +++ b/en/application-dev/notification/notification-guidelines.md @@ -256,10 +256,3 @@ function cancelCallback(err) { Notification.cancel(1, "label", cancelCallback) ``` - - -## Samples - -The following sample is provided to help you better understand how to develop notification functions: - -[`Notification`: Notification (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification) \ No newline at end of file diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 5236153ea7f845936ee364213f1cf2aef4326770..709c419fc08b3035c6b2060fd9445fc351b869ea 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -6,10 +6,7 @@ - [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 - [Application Package Structure Configuration File (FA Model)](package-structure.md) - [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - - [Resource File Categories](basic-resource-file-categories.md) - [SysCap](syscap.md) - diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png new file mode 100644 index 0000000000000000000000000000000000000000..048b8e07817272b759781df104c1dd4526685d61 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png new file mode 100644 index 0000000000000000000000000000000000000000..606ce3a0eab0a39f166029182bcc2f70291740d6 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128939.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png new file mode 100644 index 0000000000000000000000000000000000000000..d044d5d829ab1ad805f4ffcda19837f867b976fc Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png new file mode 100644 index 0000000000000000000000000000000000000000..2dd664a2b25751cc32bd81927b30036d5cc4f351 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png new file mode 100644 index 0000000000000000000000000000000000000000..7d3222667d7bffe89a148dc3b08861a86c43713e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png new file mode 100644 index 0000000000000000000000000000000000000000..c188c864c051f68984ecc0c4c64be83f0dd6e1e9 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129264.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png new file mode 100644 index 0000000000000000000000000000000000000000..b42f2e3896d334d86e89b867cf3428782f88d600 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png new file mode 100644 index 0000000000000000000000000000000000000000..8541c80810d3f3dfb7180fede34a51221dc56106 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129372.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png new file mode 100644 index 0000000000000000000000000000000000000000..2dda1a5cfca8d75d70e40b8bc0d555faade04583 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png differ diff --git a/en/application-dev/quick-start/full-sdk-switch-guide.md b/en/application-dev/quick-start/full-sdk-switch-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..4c20e429bdef97ab0503614d01f1807e56eedb13 --- /dev/null +++ b/en/application-dev/quick-start/full-sdk-switch-guide.md @@ -0,0 +1,98 @@ +# Guide to Switching to Full SDK + +Both the public SDK and full SDK are toolkits for application development. + +The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications. + +The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs. + +The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. + +## Downloading the Full SDK (of 3.1.1 Release in this example) + +Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md). + +![image-20220613161049897](figures/en-us_image_0000001655128646.png) + + + + +## Checking the Local SDK Location
In this example, an eTS project is used. For a JS project, replace **ets** with **js**. + +In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK. + +![](figures/en-us_image_0000001655128939.png) + +![image-20220613160524053](figures/en-us_image_0000001655128998.png) + + +## Replacing the SDK + +1. Make sure the downloaded SDK is a full SDK. + + a. Verify that the name of the downloaded file contains **sdk-full**. + + ![image-20220613220702504](figures/en-us_image_0000001655129232.png) + + b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**). + + Note: The criteria for identifying system APIs are subject to the released API documentation. + + + +2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example. + + + + a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip` + + ![image-20220613165018184](figures/en-us_image_0000001655129264.png) + + b. Replace the SDK files. + + Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.) + + Go to the obtained location of the local installed SDK and back up the files therein. + + ![image-20220613161352157](figures/en-us_image_0000001655129041.png) + + Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**. + + ![image-20220613165018184](figures/en-us_image_0000001655129398.png) + + The configuration in the **oh-uni-package.json** file is as follows: + + ``` + { + "apiVersion": "8", + "displayName": "Ets", + "meta": { + "metaVersion": "3.0.0" + }, + "path": "ets", + "releaseType": "Release", + "version": "3.1.6.6" + } + ``` + + **Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten. + + + + Copy the full SDK to the location of the local SDK. + + Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK. + + Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number. + + + + In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package. + + ![image-20220613171111405](figures/en-us_image_0000001655129333.png) + + + + c. Check for system APIs. + + ![image-20220613213038104](figures/en-us_image_0000001655129372.png) diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index 7fe24ab3c28b8b1d94aa1cd7c258a32be9f126e9..2733f0f0a7bfbeebf646813ff1395cf36babe49d 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -99,50 +99,6 @@ Example of the **module.json** file: "resource": "$profile:config_file2" } ], - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file1" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file2" - } - ], - "abilities": [ - { - "name": "MainAbility", - "srcEntrance" : "./login/MyMainAbility.ts", - "description": "$string:description_main_ability", - "icon": "$media:icon", - "label": "HiMusic", - "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ ] - } - ], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], - } - ], "abilities": [ { "name": "MainAbility", 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 index 5b27196b94fba68c504243122f899f6a016049ae..444064abb6deb2c23e16cbc6d9e1dd296ca7774a 100644 --- a/en/application-dev/quick-start/start-with-ets-low-code.md +++ b/en/application-dev/quick-start/start-with-ets-low-code.md @@ -1,6 +1,8 @@ # Getting Started with eTS in the Low-Code Approach -> **NOTE**
This feature is supported in DevEco Studio V3.0 Beta3 and later versions. +> **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. > @@ -15,7 +17,7 @@ You can develop applications or services in the low-code approach using either o - 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. +- In an existing project, create a .visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page). ## Creating a Project That Supports Low-Code Development 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 2a3add0689722179d384b50a4afa27abd5a8077f..93b46ac4515350f84f884a4f9bcbd524d0a5ebdc 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 @@ -1,6 +1,8 @@ # Getting Started with JavaScript in the Low-Code Approach -> **NOTE**
This feature will be available in DevEco Studio V2.2 Beta1 and later versions. +> **NOTE** +> +> This feature will be available in DevEco Studio V2.2 Beta1 and later 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. @@ -13,7 +15,7 @@ You can develop applications or services in the low-code approach using either o - 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. +- In an existing project, create a Visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page). ## Creating a Project That Supports Low-Code Development diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 7a0b40e55111901d58660e503ad022b8b41d494c..bed5c71f81b43a5ba8012b2c8eb2d9e8d41ce2b3 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -18,8 +18,8 @@ - [@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.application.missionManager](js-apis-missionManager.md) - [@ohos.ability.particleAbility](js-apis-particleAbility.md) - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) @@ -31,22 +31,23 @@ - application/[AbilityContext](js-apis-ability-context.md) - application/[abilityDelegator](js-apis-application-abilityDelegator.md) - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) + - application/[AbilityManager](js-apis-abilityManager.md) - application/[abilityMonitor](js-apis-application-abilityMonitor.md) - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) - application/[AbilityStageContext](js-apis-abilityStageContext.md) - application/[Context](js-apis-application-context.md) + - application/[ExtensionAbilityContext](js-apis-extension-ability-context.md) + - application/[ExtensionAbilityInfo](js-apis-extensionAbilityInfo.md) - application/[ExtensionContext](js-apis-extension-context.md) - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - application/[FormExtensionContext](js-apis-formextensioncontext.md) + - application/[MissionInfo](js-apis-application-missionInfo.md) - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) + - application/[ServiceExtAbilityContext](js-apis-serviceExtAbilityContext.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - - application/[AbilityManager (AbilityManager)](js-apis-abilityManager.md) - - application/[ExtensionAbilityContext (ExtensionAbilityContext)](js-apis-extension-ability-context.md) - - application/[ExtensionAbilityInfo (ExtensionAbilityInfo)](js-apis-extensionAbilityInfo.md) - - application/[ServiceExtAbilityContext (ServiceExtAbilityContext)](js-apis-serviceExtAbilityContext.md) - Common Event and Notification - [@ohos.commonEvent](js-apis-commonEvent.md) @@ -87,6 +88,7 @@ - [@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) @@ -110,7 +112,6 @@ - [@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) - [@ohos.data.storage](js-apis-data-storage.md) - data/rdb/[resultSet](js-apis-data-resultset.md) - File Management @@ -119,6 +120,7 @@ - [@ohos.environment](js-apis-environment.md) - [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileManager](js-apis-filemanager.md) + - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.volumeManager](js-apis-volumemanager.md) @@ -132,11 +134,12 @@ - [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.data](js-apis-telephony-data.md) - Network Management + - [@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) + - [@ohos.request](js-apis-request.md) - Connectivity - [@ohos.bluetooth](js-apis-bluetooth.md) @@ -163,6 +166,7 @@ - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.wallpaper](js-apis-wallpaper.md) + - [console (Log)](js-apis-logs.md) - [Timer](js-apis-timer.md) - Device Management @@ -178,6 +182,7 @@ - [@ohos.power](js-apis-power.md) - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) + - [@ohos.settings](js-apis-settings.md) - [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -236,4 +241,3 @@ - [@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/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 4e37d4be279a2acc092617c9bc69723d2c924d9f..1dcdd4b837f3f5236871445eaa88140ad8732968 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,6 +1,7 @@ -# Bundle Module (JavaScript SDK APIs) +# Bundle -> **NOTE**
+> **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. > API version 9 is a canary version for trial use. The APIs of this version may be unstable. ## Modules to Import @@ -15,11 +16,11 @@ 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 @@ -39,7 +40,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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. | @@ -69,7 +70,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 API uses an asynchronous callback to return the result. +Obtains the application information of the specified user based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -83,7 +84,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | @@ -122,7 +123,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | @@ -143,9 +144,9 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\> +getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result. +Obtains the information of all available bundles of the specified user in the system. This API uses a promise to return the result. **Required permissions** @@ -166,7 +167,7 @@ SystemCapability.BundleManager.BundleFramework | Type | Description | | --------------------------- | -------------------------- | -| Promise\> | Promise used to return the information of all available bundles.| +| Promise> | Promise used to return the information of all available bundles.| **Example** @@ -185,7 +186,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\>): void +getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. @@ -220,9 +221,9 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { ## bundle.getAllBundleInfo -getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\>): void +getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all available bundles of the specified user in the system. This API uses an asynchronous callback to return the result. **Required permissions** @@ -238,7 +239,7 @@ SystemCapability.BundleManager.BundleFramework | ---------- | --------------------------------- | ---- | --------------------------------------- | | 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. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -274,7 +275,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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.| | options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | @@ -320,7 +321,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | @@ -343,7 +344,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 API uses an asynchronous callback to return the result. +Obtains the bundle information based on a given bundle name and bundle options. This API uses an asynchronous callback to return the result. **Required permissions** @@ -357,7 +358,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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.| | options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | @@ -578,7 +579,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -618,7 +619,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| @@ -654,7 +655,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -694,7 +695,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | abilityName | string | Yes | Ability name.| | callback | AsyncCallback\ | Yes | Callback used to return the application name. | @@ -718,10 +719,6 @@ isAbilityEnabled(info: AbilityInfo): Promise\ Checks whether the ability that matches a given **AbilityInfo** object is enabled. This API uses a promise to return the result. -**Required permissions** - -None - **System capability** SystemCapability.BundleManager.BundleFramework @@ -759,10 +756,6 @@ isAbilityEnabled(info : AbilityInfo, callback : AsyncCallback\): void Checks whether the ability that matches a given **AbilityInfo** object is enabled. This API uses an asynchronous callback to return the result. -**Required permissions** - -None - **System capability** SystemCapability.BundleManager.BundleFramework @@ -796,10 +789,6 @@ isApplicationEnabled(bundleName: string): Promise\ Checks whether an application is enabled based on a given bundle name. This API uses a promise to return the result. -**Required permissions** - -None - **System capability** SystemCapability.BundleManager.BundleFramework @@ -808,7 +797,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of an application.| **Return value** @@ -834,10 +823,6 @@ isApplicationEnabled(bundleName: string, callback : AsyncCallback\): vo Checks whether an application is enabled based on a given bundle name. This API uses an asynchronous callback to return the result. -**Required permissions** - -None - **System capability** SystemCapability.BundleManager.BundleFramework @@ -846,7 +831,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ----------------------- | ---- | --------------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an 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** @@ -911,9 +896,13 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) ## bundle.queryAbilityByWant -queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\>): void +queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. +Obtains the ability information of the specified user based on a given want. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -923,7 +912,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ---------------------------------- | ---- | ------------------------------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | +| want | [Want](js-apis-application-Want.md) | 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. | @@ -952,6 +941,10 @@ queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback> | Yes | Callback used to return the ability information. | @@ -1001,7 +994,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| bundleName | string | Yes | Bundle name of the application.| +| bundleName | string | Yes | Bundle name of an application.| **Return value** | Type | Description | @@ -1038,7 +1031,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | -------------------- | ---- | ------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of an application. | | callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the **Want** object.| **Example** @@ -1123,11 +1116,11 @@ bundle.getNameForUid(uid, (err, data) => { getAbilityIcon(bundleName: string, abilityName: string): Promise\; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -1143,13 +1136,13 @@ SystemCapability.BundleManager.BundleFramework **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the [PixelMap](js-apis-image.md).| +| Promise\ | Promise used to return the [pixel map](js-apis-image.md).| **Example** ```js -let bundleName = com.example.myapplication; -let abilityName = com.example.myapplication.MainAbility; +let bundleName = "com.example.myapplication"; +let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityIcon(bundleName, abilityName) .then((data) => { console.info('Operation successful. Data: ' + JSON.stringify(data)); @@ -1162,11 +1155,11 @@ bundle.getAbilityIcon(bundleName, abilityName) getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the [PixelMap](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. +Obtains the [pixel map](js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO **System capability** @@ -1178,13 +1171,13 @@ SystemCapability.BundleManager.BundleFramework | ----------- | ---------------------------------------- | ---- | ---------------------------------------- | | 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](js-apis-image.md).| +| callback | AsyncCallback\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** ```js -let bundleName = com.example.myapplication; -let abilityName = com.example.myapplication.MainAbility; +let bundleName = "com.example.myapplication"; +let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -1194,134 +1187,6 @@ 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 API 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](js-apis-application-Want.md) | 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 API 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](js-apis-application-Want.md) | 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 API 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](js-apis-application-Want.md) | 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)); -}) -``` - ## InstallErrorCode **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1403,10 +1268,10 @@ Enumerates display orientations. | Name | Type | Description | | ------------- | ---- | ------------- | -| UNSPECIFIED | None | The system automatically determines the display orientation. | +| UNSPECIFIED | None | Unspecified 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.| +| FOLLOW_RECENT | None | Orientation same as that of the nearest ability in the stack.| ## LaunchMode @@ -1438,7 +1303,7 @@ Enumerates Extension ability types. | Name | Type | Description | | ------------------------------ | ---- | ------------------------- | -| FORM9+ | 0 | Form included. | +| FORM9+ | 0 | Form (widget) included. | | WORK_SCHEDULER9+ | 1 | Work scheduler included.| | INPUT_METHOD9+ | 2 | Input method included. | | SERVICE9+ | 3 | Service included. | @@ -1447,7 +1312,7 @@ Enumerates Extension ability types. | FILE_SHARE9+ | 6 | File sharing included.| | STATIC_SUBSCRIBER9+ | 7 | Subscribers included. | | WALLPAPER9+ | 8 | Wallpaper included. | -| UNSPECIFIED9+ | 9 | Unspecified type. | +| UNSPECIFIED9+ | 9 | Unspecified type. | ## ExtensionFlag9+ @@ -1484,3 +1349,4 @@ Enumerates permission grant states. | ------------------ | ---- | ---- | | 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 213f302466c5dfd0cabb76f4899665139dfe2e3d..9ceaca4f6f4c784172d6f6905d702b7970a67000 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -7,7 +7,7 @@ import featureAbility from '@ohos.ability.featureAbility' import bundle from '@ohos.bundle' ``` -The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the Context module. An example is as follows: +The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: ```js import featureAbility from '@ohos.ability.featureAbility' @@ -27,9 +27,9 @@ If this API is called for the first time, a root directory will be created. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| **Example** @@ -55,8 +55,8 @@ If this API is called for the first time, a root directory will be created. **Return value** -| Type | Description | -| ---------------- | ---------------------- | +| Type | Description | +| ---------------- | ----------- | | Promise\ | Promise used to return the local root directory.| **Example** @@ -81,11 +81,11 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -110,10 +110,10 @@ Verifies whether the current PID and UID have the given permission. This API use **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -133,16 +133,16 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------- | -| permission | string | Yes | Name of the permission to verify.| -| options | [PermissionOptions](#permissionoptions) | No | Permission options. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------- | +| permission | string | Yes | Name of the permission to verify.| +| options | [PermissionOptions](#permissionoptions) | No | Permission options. | **Return value** -| Type | Description | -| ---------------- | ----------------------------------------------------------- | -| Promise\ | Promise used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| +| Type | Description | +| ---------------- | ---------------------------------- | +| Promise\ | Promise used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -168,11 +168,11 @@ Requests certain permissions from the system. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | -| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| -| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Permission request result. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ----------------------------------- | +| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | +| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| +| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Callback used to return the permission request result. | **Example** @@ -193,6 +193,44 @@ context.requestPermissionsFromUser( ``` +## Context.requestPermissionsFromUser7+ + +requestPermissionsFromUser(permissions: Array\, requestCode: number): Promise\<[PermissionRequestResult](#permissionrequestresult7)> + +Requests certain permissions from the system. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ----- | -------------------------------------------- | +| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | +| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------- | ---------------- | +| Promise\<[PermissionRequestResult](#permissionrequestresult7)> | Promise used to return the permission request result.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.requestPermissionsFromUser( + ["com.example.permission1", + "com.example.permission2", + "com.example.permission3", + "com.example.permission4", + "com.example.permission5"], + 1).then((data)=>{ + console.info("====>requestdata====>" + JSON.stringify(data)); + }); +``` + + ## Context.getApplicationInfo @@ -204,9 +242,9 @@ Obtains information about the current application. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the application information.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the application information.| **Example** @@ -228,8 +266,8 @@ Obtains information about the current application. This API uses a promise to re **Return value** -| Type | Description | -| ------------------------- | ------------------ | +| Type | Description | +| ------------------------- | --------- | | Promise\ | Promise used to return the application information.| **Example** @@ -249,15 +287,15 @@ context.getApplicationInfo().then((data) => { getBundleName(callback: AsyncCallback\): void -Obtains the bundle name of the current ability. This API uses an asynchronous callback to return the result. +Obtains the bundle name of this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -273,14 +311,14 @@ context.getBundleName() getBundleName(): Promise\ -Obtains the bundle name of the current ability. This API uses a promise to return the result. +Obtains the bundle name of this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| ---------------- | ------------------------- | +| Type | Description | +| ---------------- | ---------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -306,9 +344,9 @@ Obtains information about the current process, including the PID and process nam **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process information.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process information.| **Example** @@ -330,8 +368,8 @@ Obtains information about the current process, including the PID and process nam **Return value** -| Type | Description | -| --------------------- | -------------- | +| Type | Description | +| --------------------- | ------- | | Promise\ | Promise used to return the process information.| **Example** @@ -351,7 +389,7 @@ context.getProcessInfo().then((data) => { getElementName(callback: AsyncCallback\): void -Obtains the **ohos.bundle.ElementName** object of the current ability. This API uses an asynchronous callback to return the result. +Obtains the **ohos.bundle.ElementName** object of this ability. This API uses an asynchronous callback to return the result. This API is available only to Page abilities. @@ -359,9 +397,9 @@ This API is available only to Page abilities. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** @@ -377,7 +415,7 @@ context.getElementName() getElementName(): Promise\ -Obtains the **ohos.bundle.ElementName** object of the current ability. This API uses a promise to return the result. +Obtains the **ohos.bundle.ElementName** object of this ability. This API uses a promise to return the result. This API is available only to Page abilities. @@ -385,8 +423,8 @@ This API is available only to Page abilities. **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | +| Type | Description | +| --------------------- | ------------------------------------ | | Promise\ | Promise used to return the **ohos.bundle.ElementName** object.| **Example** @@ -410,9 +448,9 @@ Obtains the name of the current process. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process name.| **Example** @@ -434,8 +472,8 @@ Obtains the name of the current process. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------- | -------------------- | +| Type | Description | +| ---------------- | ---------- | | Promise\ | Promise used to return the process name.| **Example** @@ -461,9 +499,9 @@ Obtains the bundle name of the calling ability. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -485,8 +523,8 @@ Obtains the bundle name of the calling ability. This API uses a promise to retur **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | -------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -504,15 +542,15 @@ context.getCallingBundle().then((data) => { getCacheDir(callback: AsyncCallback\): void -Obtains the cache directory of the application on the internal storage. This API uses an asynchronous callback to return the result. +Obtains the cache directory of the application in the internal storage. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | --------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| **Example** @@ -532,14 +570,14 @@ context.getCacheDir((err, data) => { getCacheDir(): Promise\ -Obtains the cache directory of the application on the internal storage. This API uses a promise to return the result. +Obtains the cache directory of the application in the internal storage. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | --------------- | | Promise\ | Promise used to return the cache directory.| **Example** @@ -557,15 +595,15 @@ context.getCacheDir().then((data) => { getFilesDir(callback: AsyncCallback\): void -Obtains the file directory of the application on the internal storage. This API uses an asynchronous callback to return the result. +Obtains the file directory of the application in the internal storage. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| **Example** @@ -585,14 +623,14 @@ context.getFilesDir((err, data) => { getFilesDir(): Promise\ -Obtains the file directory of the application on the internal storage. This API uses a promise to return the result. +Obtains the file directory of the application in the internal storage. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------- | | Promise\ | Promise used to return the file directory.| **Example** @@ -618,9 +656,9 @@ If the distributed file path does not exist, the system will create one and retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| **Example** @@ -648,8 +686,8 @@ If the distributed file path does not exist, the system will create one and retu **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ----------------------------------- | | Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| **Example** @@ -672,9 +710,9 @@ Obtains the application type. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the application type.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the application type.| **Example** @@ -700,8 +738,8 @@ Obtains the application type. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------ | | Promise\ | Promise used to return the application type.| **Example** @@ -724,9 +762,9 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](#hapmoduleinfo)> | Yes | Callback used to return the **ModuleInfo** object.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[HapModuleInfo](#hapmoduleinfo)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -752,8 +790,8 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[HapModuleInfo](#hapmoduleinfo)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -776,9 +814,9 @@ Obtains the version information of the application. This API uses an asynchronou **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| **Example** @@ -804,8 +842,8 @@ Obtains the version information of the application. This API uses a promise to r **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | --------- | | Promise\<[AppVersionInfo](#appversioninfo)> | Promise used to return the version information.| **Example** @@ -822,15 +860,15 @@ context.getAppVersionInfo().then((data) => { getAbilityInfo(callback: AsyncCallback\): void -Obtains information of the current ability. This API uses an asynchronous callback to return the result. +Obtains information about this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes |Callback used to return the ability information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[AbilityInfo](#abilityInfo)> | Yes | Callback used to return the ability information.| **Example** @@ -850,14 +888,14 @@ context.getAbilityInfo((err, data) => { getAbilityInfo(): Promise\ -Obtains information of the current ability. This API uses a promise to return the result. +Obtains information about this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[AbilityInfo](#abilityInfo)> | Promise used to return the ability information.| **Example** @@ -880,9 +918,9 @@ Obtains the context of the application. **Return value** -| Type | Description | -| --------- |------ | -| Context |Application context.| +| Type | Description | +| ------- | ---------- | +| Context | Application context.| **Example** @@ -895,48 +933,49 @@ var context = featureAbility.getContext().getApplicationContext(); **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Readable/Writable| Type | Mandatory| Description | -| ---- | -------- | ------ | ---- | ------ | -| pid | Read-only | number | No | Process ID.| -| uid | Read-only | number | No | User ID.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ---- | ---- | ------ | ---- | ----- | +| pid | Read-only | number | No | Process ID.| +| uid | Read-only | number | No | User ID.| ## PermissionRequestResult **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------- | ---- | ------------------ | -| requestCode | Read-only | number | Yes | Request code passed.| -| permissions | Read-only | Array\ | Yes | Permissions requested. | -| authResults | Read-only | Array\ | Yes | Permission request result. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | -------------- | ---- | ---------- | +| requestCode | Read-only | number | Yes | Request code passed.| +| permissions | Read-only | Array\ | Yes | Permissions requested. | +| authResults | Read-only | Array\ | Yes | Permission request result. | ## HapModuleInfo Describes the HAP module information. -| 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 | Running modes supported by the module. | -| reqCapabilities | Array\ | Yes | No | Capabilities required for module running.| -| deviceTypes | Array\ | Yes | No | Device types supported by the module.| -| abilityInfo | Array\ | Yes | No | Ability information. | -| moduleName | string | Yes | No | Module name. | -| mainAbilityName | string | Yes | No | Name of the main ability. | -| installationFree | boolean | Yes | No | Whether installation-free is supported. | -| mainElementName | string | Yes| No| Information about the main 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 | Running modes supported by the module. | +| reqCapabilities | Array\ | Yes | No | Capabilities required for module running. | +| deviceTypes | Array\ | Yes | No | Device types supported by the module. | +| abilityInfo | Array\ | Yes | No | Ability information. | +| moduleName | string | Yes | No | Module name. | +| mainAbilityName | string | Yes | No | Name of the main ability. | +| installationFree | boolean | Yes | No | Whether installation-free is supported. | +| mainElementName | string | Yes | No | Information about the main ability. | ## AppVersionInfo -| Name | Type| Readable | Writable | Description| -| ------ | ------ | ------| ------ | ------ | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description. | -| versionName | string | Yes | No | Module description ID. | + +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| appName | string | Yes | No | Module name. | +| versionCode | number | Yes | No | Module description.| +| versionName | string | Yes | No | Module description ID.| diff --git a/en/application-dev/reference/apis/js-apis-DataUriUtils.md b/en/application-dev/reference/apis/js-apis-DataUriUtils.md index 267ba0d27b3fbf9e3b35a8dbb884da04286f5729..6860b188b4caeff2cd36c061868617dc8bddc1ea 100644 --- a/en/application-dev/reference/apis/js-apis-DataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-DataUriUtils.md @@ -32,11 +32,9 @@ Obtains the ID attached to the end of a given URI. **Example** ```js -dataUriUtils.getIdSync("com.example.dataUriUtils/1221") +dataUriUtils.getId("com.example.dataUriUtils/1221") ``` - - ## dataUriUtils.attachId attachId(uri: string, id: number): string @@ -68,8 +66,6 @@ dataUriUtils.attachId( ) ``` - - ## dataUriUtils.deleteId deleteId(uri: string): string @@ -96,8 +92,6 @@ Deletes the ID from the end of a given URI. dataUriUtils.deleteId("com.example.dataUriUtils/1221") ``` - - ## dataUriUtils.updateId updateId(uri: string, id: number): string diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index 3d1f09e0e427c20f01a450f9b2a093d12df1ac6a..ad9cd9a4d257370d94566ef43cd81af3bb6e163e 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -126,7 +126,7 @@ var options = { windowMode: 0, }; this.context.startAbility(want, options) -.then((data) => { +.then(() => { console.log('Operation successful.') }).catch((error) => { console.log('Operation failed.'); @@ -273,7 +273,7 @@ var options = { }; var accountId = 11; this.context.startAbility(want, accountId, options) -.then((data) => { +.then(() => { console.log('Operation successful.') }).catch((error) => { console.log('Operation failed.'); @@ -352,7 +352,7 @@ Starts an ability with **options** specified. This API uses a promise to return | 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.| +| options | StartOptions | No | Parameters used for starting the ability.| **Return value** @@ -511,8 +511,8 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js -this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringify(data)); +this.context.terminateSelf(want).then(() => { + console.log('success:'); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); @@ -571,7 +571,7 @@ this.context.terminateSelfWithResult( { want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, resultCode: 100 -}).then((result) => { +}).then(() => { console.log("terminateSelfWithResult") }) ``` @@ -595,7 +595,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | Type| Description| | -------- | -------- | -| number | ID of the connection between the two abilities.| +| number | Result code of the ability connection.| **Example** ```js @@ -606,7 +606,7 @@ var want = { } var options = { onConnect: (elementName, remote) => { - console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) + console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote) }, onDisconnect: (elementName) => { console.log('connectAbility onDisconnect, elementName: ' + elementName) @@ -615,8 +615,8 @@ var options = { console.log('connectAbility onFailed, code: ' + code) } } -this.context.connectAbility(want, options) { - console.log('code: ' + code) +let result = this.context.connectAbility(want, options) { + console.log('code: ' + result) } ``` @@ -652,7 +652,7 @@ var want = { var accountId = 111; var options = { onConnect: (elementName, remote) => { - console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) + console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' + remote) }, onDisconnect: (elementName) => { console.log('connectAbility onDisconnect, elementName: ' + elementName) @@ -768,8 +768,8 @@ Sets the label of the ability in the mission. This API uses a promise to return **Example** ```js -this.context.setMissionLabel("test").then((data) => { - console.log('success:' + JSON.stringify(data)); +this.context.setMissionLabel("test").then(() => { + console.log('success:'); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 9f81d3aab860d8f6123d09d7f4aae8893ca19aa4..3432e02b385a8c3f265437a9f8afcc9ffd42bad3 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,11 +1,12 @@ # Ability Access Control -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import abilityAccessCtrl from '@ohos.abilityAccessCtrl' ``` @@ -72,6 +73,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses a promise to return the result. +This is a system API. + **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **System capability**: SystemCapability.Security.AccessToken @@ -109,6 +112,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. +This is a system API. + **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **System capability**: SystemCapability.Security.AccessToken @@ -139,6 +144,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses a promise to return the result. +This is a system API. + **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **System capability**: SystemCapability.Security.AccessToken @@ -175,6 +182,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. +This is a system API. + **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **System capability**: SystemCapability.Security.AccessToken @@ -204,6 +213,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. +This is a system API. + **Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS **System capability**: SystemCapability.Security.AccessToken diff --git a/en/application-dev/reference/apis/js-apis-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index c39e6e8f9437e64b3f05f59986ec08d35170eb71..dc2c79e0058293ddd2e1a9459b1962037e591aff 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -1,6 +1,9 @@ # Accessibility -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration. + +> **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 @@ -13,7 +16,7 @@ import accessibility from '@ohos.accessibility'; Enumerates the states of an accessibility application. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -25,7 +28,7 @@ Enumerates the states of an accessibility application. Enumerates the types of accessibility applications. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -34,12 +37,13 @@ Enumerates the types of accessibility applications. | haptic | The accessibility application provides haptic feedback.| | spoken | The accessibility application provides spoken feedback.| | visual | The accessibility application provides visual feedback.| +| all9+ | All the preceding types.| ## AccessibilityAbilityInfo Provides information about an accessibility application. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core ### Attributes @@ -48,6 +52,7 @@ Provides information about an accessibility application. | id | number | Yes| No| Ability ID.| | name | string | Yes| No| Ability name.| | bundleName | string | Yes| No| Bundle name.| +| targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.| | abilityTypes | Array<[AbilityType](#abilitytype)> | Yes| No| Accessibility application type.| | capabilities | Array<[Capability](#capability)> | Yes| No| Capabilities list of the accessibility application.| | description | string | Yes| No| Description of the accessibility application.| @@ -57,7 +62,7 @@ Provides information about an accessibility application. Describes the target action supported by an accessibility application. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -82,7 +87,7 @@ Describes the target action supported by an accessibility application. Enumerates the capabilities of an auxiliary application. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -94,9 +99,9 @@ Enumerates the capabilities of an auxiliary application. ## CaptionsFontEdgeType8+ -Enumerates the caption font edge type. +Enumerates the font edge types of captions. -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing | Name| Description| | -------- | -------- | @@ -108,9 +113,9 @@ Enumerates the caption font edge type. ## CaptionsFontFamily8+ -Enumerates the caption font families. +Enumerates the font families of captions. -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing | Name| Description| | -------- | -------- | @@ -125,50 +130,49 @@ Enumerates the caption font families. ## CaptionsStyle8+ -Describes the caption style. +Describes the style of captions. -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes| No| Font family of the captions.| -| fontScale | number | Yes| No| Font scale of the captions.| -| fontColor | number \| string | Yes| No| Font color of the captions.| -| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes| No| Font edge type of the captions.| -| backgroundColor | number \| string | Yes| No| Background color of the captions.| -| windowColor | number \| string | Yes| No| Window color of the captions.| +| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes| No| Font family of captions.| +| fontScale | number | Yes| No| Font scale of captions.| +| fontColor | number \| string | Yes| No| Font color of captions.| +| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes| No| Font edge type of captions.| +| backgroundColor | number \| string | Yes| No| Background color of captions.| +| windowColor | number \| string | Yes| No| Window color of captions.| ## CaptionsManager8+ -Implements caption configuration management. +Implements configuration management for captions. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing ### Attributes | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| enabled | boolean | Yes| No| Whether to enable caption configuration.| -| style | [CaptionsStyle](#captionsstyle8) | Yes| No| Caption style.| +| enabled | boolean | Yes| No| Whether to enable captions configuration.| +| style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.| ### Methods -In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) method to obtain a **captionsManager** instance, and then call the methods using the obtained instance. - +In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance. #### on('enableChange') on(type: 'enableChange', callback: Callback<boolean>): void; -Enables listening for enable status changes of caption configuration. - -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +Enables listening for enabled status changes of captions configuration. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | Yes| Callback invoked when the enable status of caption configuration changes.| + | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| -- Example +- **Example** ```typescript captionsManager.on('enableChange',(data) => { @@ -180,18 +184,16 @@ Enables listening for enable status changes of caption configuration. on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -Enables listening for caption style changes. - -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +Enables listening for captions style changes. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the caption style changes.| + | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| -- Example +- **Example** ```typescript captionsManager.on('styleChange',(data) => { @@ -203,18 +205,16 @@ Enables listening for caption style changes. off(type: 'enableChange', callback?: Callback<boolean>): void; -Disables listening for enable status changes of caption configuration. - -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +Disables listening for enabled status changes of captions configuration. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | No| Callback invoked when the enable status of caption configuration changes.| + | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| -- Example +- **Example** ```typescript captionsManager.off('enableChange') @@ -224,18 +224,16 @@ Disables listening for enable status changes of caption configuration. off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -Disables listening for caption style changes.s is removed. - -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +Disables listening for captions style changes. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the caption style changes.| + | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| -- Example +- **Example** ```typescript captionsManager.off('styleChange') @@ -245,7 +243,7 @@ Disables listening for caption style changes.s is removed. Describes a GUI change event. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core ### Attributes @@ -270,7 +268,7 @@ Describes a GUI change event. Enumerates accessibility event types. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -290,7 +288,7 @@ Enumerates accessibility event types. Enumerates the movement units for traversing the node text. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -304,7 +302,7 @@ Enumerates the movement units for traversing the node text. Enumerates window update types. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core | Name| Description| | -------- | -------- | @@ -326,7 +324,7 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A Obtains the accessibility application list. This API uses a promise to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core - **Parameters** @@ -335,13 +333,13 @@ Obtains the accessibility application list. This API uses a promise to return th | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| -- Example +- **Example** ```typescript accessibility.getAbilityLists("spoken", "enable") @@ -369,7 +367,7 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn Obtains the accessibility application list. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core - **Parameters** @@ -379,7 +377,7 @@ Obtains the accessibility application list. This API uses an asynchronous callba | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| -- Example +- **Example** ```typescript accessibility.getAbilityLists("visual", "enable", (err, data) => { @@ -406,17 +404,17 @@ Obtains the accessibility application list. This API uses an asynchronous callba getCaptionsManager(): CaptionsManager -Obtains the accessibility caption configuration. +Obtains the captions configuration. -**System capability**: SystemCapability.Barrierfree.Accessibility.Hearing +**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -- Return value +- **Return value** | Type| Description| | -------- | -------- | - | [CaptionsManager](#captionsmanager8) | Accessibility caption configuration.| + | [CaptionsManager](#captionsmanager8) | Captions configuration.| -- Example +- **Example** ```typescript captionsManager = accessibility.getCaptionsManager() @@ -432,10 +430,10 @@ Enables listening for the accessibility application or touch guide mode status c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision| - | callback | Callback<boolean> | Yes| Callback invoked when the enable status changes.| + | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| + | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| -- Example +- **Example** ```typescript accessibility.on('accessibilityStateChange',(data) => { @@ -447,18 +445,16 @@ Enables listening for the accessibility application or touch guide mode status c off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void -Disables listening for the accessibility application or touch guide mode status changes. - - +Disables listening for the accessibility application or touch guide mode status changes. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | No| Type of the event to listen for.
- **accessibilityStateChange** means to listen for enable status changes of the accessibility application.
**System capability**: SystemCapability.Barrierfree.Accessibility.Core
- **touchGuideStateChange** means to listen for enable status changes of the touch guide mode.
**System capability**: SystemCapability.Barrierfree.Accessibility.Vision| - | callback | Callback<boolean> | No| Callback invoked when the enable status changes.| + | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| + | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.| -- Example +- **Example** ```typescript accessibility.off('accessibilityStateChange',(data) => { @@ -472,15 +468,15 @@ isOpenAccessibility(): Promise<boolean> Checks whether accessibility is enabled. This API uses a promise to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.| -- Example +- **Example** ```typescript accessibility.isOpenAccessibility() @@ -497,15 +493,15 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void Checks whether accessibility is enabled. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- Example +- **Example** ```typescript accessibility.isOpenAccessibility((err, data) => { @@ -523,15 +519,15 @@ isOpenTouchGuide(): Promise<boolean> Checks whether touch guide mode is enabled. This API uses a promise to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- Example +- **Example** ```typescript accessibility.isOpenTouchGuide() @@ -548,15 +544,15 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void Checks whether touch guide mode is enabled. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- Example +- **Example** ```typescript accessibility.isOpenTouchGuide((err, data) => { @@ -574,7 +570,7 @@ sendEvent(event: EventInfo): Promise<void> Sends an accessibility event. This API uses a promise to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core - **Parameters** @@ -582,13 +578,13 @@ Sends an accessibility event. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| -- Example +- **Example** ```typescript accessibility.sendEvent(this.eventInfo) @@ -605,7 +601,7 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void Sends an accessibility event. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Barrierfree.Accessibility.Core +**System capability**: SystemCapability.BarrierFree.Accessibility.Core - **Parameters** @@ -614,7 +610,7 @@ Sends an accessibility event. This API uses an asynchronous callback to return t | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| -- Example +- **Example** ```typescript accessibility.sendEvent(this.eventInfo,(err, data) => { diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index dfa57f762424de8035a8febcd2262b4c2431d004..de23e2a4fa2b688798f7ed7856340a0ab7270070 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,6 +1,6 @@ -# App Account Management +# App Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **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. @@ -19,7 +19,7 @@ Creates an **AppAccountManager** instance. **System capability**: SystemCapability.Account.AppAccount -**Return Value** +**Return value** | Type | Description | | ----------------- | ------------ | | AppAccountManager | **AppAccountManager** instance created.| @@ -37,7 +37,7 @@ Provides methods to manage app accounts. addAccount(name: string, callback: AsyncCallback<void>): void -Adds an app account to the account management service. This method uses an asynchronous callback to return the result. +Adds an app account to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -61,7 +61,7 @@ Adds an app account to the account management service. This method uses an async addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void -Adds an app account and its additional information to the account management service. This method uses an asynchronous callback to return the result. +Adds an app account and its additional information to the **AppAccountManager** service. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -88,7 +88,7 @@ Adds an app account and its additional information to the account management ser addAccount(name: string, extraInfo?: string): Promise<void> -Adds an app account and its additional information to the account management service. This method uses a promise to return the result. +Adds an app account and its additional information to the **AppAccountManager** service. This method uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -99,7 +99,7 @@ Adds an app account and its additional information to the account management ser | 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** +**Return value** | Type | Description | | ------------------- | --------------------- | @@ -151,7 +151,7 @@ Implicitly adds an app account based on the specified account owner, authenticat } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("LiSi", "readAge", {}, { + appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -161,7 +161,7 @@ Implicitly adds an app account based on the specified account owner, authenticat deleteAccount(name: string, callback: AsyncCallback<void>): void -Deletes an app account from the account management service. This method uses an asynchronous callback to return the result. +Deletes an app account from the **AppAccountManager** service. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -185,7 +185,7 @@ Deletes an app account from the account management service. This method uses an deleteAccount(name: string): Promise<void> -Deletes an app account from the account management service. This method uses a promise to return the result. +Deletes an app account from the **AppAccountManager** service. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -195,7 +195,7 @@ Deletes an app account from the account management service. This method uses a p | ---- | ------ | ---- | ------------ | | name | string | Yes | Name of the app account to delete.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -224,8 +224,8 @@ Disables an app account from accessing an application with the given bundle name | Name | Type | Mandatory | Description | | ---------- | ------------------------- | ---- | ------------------------------- | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | | callback | AsyncCallback<void> | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name.| **Example** @@ -249,10 +249,10 @@ Disables an app account from accessing an application with the given bundle name | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ----------------- | -| name | string | Yes | App account name.| -| bundleName | string | Yes | Bundle name of an app. | +| name | string | Yes | Name of the target app account.| +| bundleName | string | Yes | Bundle name of the app. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -281,8 +281,8 @@ Enables an app account to access an application with the given bundle name. This | Name | Type | Mandatory | Description | | ---------- | ------------------------- | ---- | ------------------------------- | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | | callback | AsyncCallback<void> | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name.| **Example** @@ -306,10 +306,10 @@ Enables an app account to access an application with the given bundle name. This | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | --------- | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app.| +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -318,7 +318,8 @@ Enables an app account to access an application with the given bundle name. This **Example** ```js - app_account_instance.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { console.log('enableAppAccess Success'); }).catch((err) => { console.log("enableAppAccess err: " + JSON.stringify(err)); @@ -329,9 +330,9 @@ Enables an app account to access an application with the given bundle name. This checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void -Checks whether an app account allows application data synchronization. This method uses an asynchronous callback to return the result. +Checks whether an app account allows app data synchronization. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -339,7 +340,7 @@ Checks whether an app account allows application data synchronization. This meth | Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | callback | AsyncCallback<boolean> | Yes | Callback used to return whether the app account allows application data synchronization.| **Example** @@ -356,9 +357,9 @@ Checks whether an app account allows application data synchronization. This meth checkAppAccountSyncEnable(name: string): Promise<boolean> -Checks whether an app account allows application data synchronization. This method uses a promise to return the result. +Checks whether an app account allows app data synchronization. This API uses a promise to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -366,9 +367,9 @@ Checks whether an app account allows application data synchronization. This meth | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------- | -| name | string | Yes | App account name.| +| name | string | Yes | Name of the target app account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :-------------------- | @@ -389,7 +390,7 @@ Checks whether an app account allows application data synchronization. This meth 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. +Sets a credential for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -397,7 +398,7 @@ Sets a credential for an app account. This method uses an asynchronous callback | Name | Type | Mandatory | Description | | -------------- | ------------------------- | ---- | -------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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.| @@ -415,7 +416,7 @@ Sets a credential for an app account. This method uses an asynchronous callback setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> -Sets a credential for an app account. This method uses a promise to return the result asynchronously. +Sets a credential for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -423,11 +424,11 @@ Sets a credential for an app account. This method uses a promise to return the r | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to set.| | credential | string | Yes | Credential to set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -448,7 +449,7 @@ Sets a credential for an app account. This method uses a promise to return the r setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void -Sets additional information for an app account. This method uses an asynchronous callback to return the result. +Sets additional information for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -456,7 +457,7 @@ Sets additional information for an app account. This method uses an asynchronous | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | extraInfo | string | Yes | Additional information to set. | | callback | AsyncCallback<void> | Yes | Callback invoked when additional information is set for the specified app account.| @@ -473,7 +474,7 @@ Sets additional information for an app account. This method uses an asynchronous setAccountExtraInfo(name: string, extraInfo: string): Promise<void> -Sets additional information for an app account. This method uses a promise to return the result asynchronously. +Sets additional information for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -481,10 +482,10 @@ Sets additional information for an app account. This method uses a promise to re | Name | Type | Mandatory | Description | | --------- | ------ | ---- | --------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | extraInfo | string | Yes | Additional information to set.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -505,9 +506,9 @@ Sets additional information for an app account. This method uses a promise to re setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void -Sets whether to enable application data synchronization for an app account. This method uses an asynchronous callback to return the result. +Sets whether to enable app data synchronization for an app account. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -515,9 +516,9 @@ Sets whether to enable application data synchronization for an app account. This | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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.| +| callback | AsyncCallback<void> | Yes | Callback invoked when app data synchronization is enabled or disabled for the app account.| **Example** @@ -532,9 +533,9 @@ Sets whether to enable application data synchronization for an app account. This setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> -Sets whether to enable application data synchronization for an app account. This method uses a promise to return the result asynchronously. +Sets whether to enable app data synchronization for an app account. This API uses a promise to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -542,10 +543,10 @@ Sets whether to enable application data synchronization for an app account. This | Name | Type | Mandatory | Description | | -------- | ------- | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | isEnable | boolean | Yes | Whether to enable app data synchronization.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -566,7 +567,7 @@ Sets whether to enable application data synchronization for an app account. This setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void -Sets data to be associated with an app account. This method uses an asynchronous callback to return the result. +Sets data to be associated with an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -574,7 +575,7 @@ Sets data to be associated with an app account. This method uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ----------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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.| @@ -582,7 +583,8 @@ Sets data to be associated with an app account. This method uses an asynchronous **Example** ```js - app_account_instance.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { console.log("setAssociatedData err: " + JSON.stringify(err)); }); ``` @@ -591,7 +593,7 @@ Sets data to be associated with an app account. This method uses an asynchronous setAssociatedData(name: string, key: string, value: string): Promise<void> -Sets data to be associated with an app account. This method uses a promise to return the result asynchronously. +Sets data to be associated with an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -599,11 +601,11 @@ Sets data to be associated with an app account. This method uses a promise to re | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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** +**Return value** | Type | Description | | :------------------ | :-------------------- | @@ -632,9 +634,9 @@ Obtains the credential of an app account. This method uses an asynchronous callb | Name | Type | Mandatory | Description | | -------------- | --------------------------- | ---- | -------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential of the specified app account.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential obtained.| **Example** @@ -650,7 +652,7 @@ Obtains the credential of an app account. This method uses an asynchronous callb getAccountCredential(name: string, credentialType: string): Promise<string> -Obtains the credential of an app account. This method uses a promise to return the result asynchronously. +Obtains the credential of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -658,10 +660,10 @@ Obtains the credential of an app account. This method uses a promise to return t | Name | Type | Mandatory | Description | | -------------- | ------ | ---- | ---------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to obtain.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | @@ -690,7 +692,7 @@ Obtains additional information of an app account. This method uses an asynchrono | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ---------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| **Example** @@ -707,7 +709,7 @@ Obtains additional information of an app account. This method uses an asynchrono getAccountExtraInfo(name: string): Promise<string> -Obtains additional information of an app account. This method uses a promise to return the result asynchronously. +Obtains additional information of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -715,9 +717,9 @@ Obtains additional information of an app account. This method uses a promise to | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------- | -| name | string | Yes | App account name.| +| name | string | Yes | Name of the target app account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | @@ -738,7 +740,7 @@ Obtains additional information of an app account. This method uses a promise to getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void -Obtains data associated with an app account. This method uses an asynchronous callback to return the result. +Obtains data associated with an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -746,7 +748,7 @@ Obtains data associated with an app account. This method uses an asynchronous ca | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ----------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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.| @@ -764,7 +766,7 @@ Obtains data associated with an app account. This method uses an asynchronous ca getAssociatedData(name: string, key: string): Promise<string> -Obtains data associated with an app account. This method uses a promise to return the result asynchronously. +Obtains data associated with an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -772,10 +774,10 @@ Obtains data associated with an app account. This method uses a promise to retur | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | key | string | Yes | Key of the data to obtain.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :-------------------- | @@ -796,7 +798,7 @@ Obtains data associated with an app account. This method uses a promise to retur getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. +Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) @@ -822,7 +824,7 @@ Obtains information about all accessible app accounts. This method uses an async getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> -Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. +Obtains information about all accessible app accounts. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) @@ -849,7 +851,7 @@ Obtains information about all accessible app accounts. This method uses an async getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void -Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. +Obtains information about all app accounts of the specified app. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) @@ -877,7 +879,7 @@ Obtains information about all app accounts of the specified app. This method use 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. +Obtains information about all app accounts of the specified app. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) @@ -911,7 +913,7 @@ Obtains information about all app accounts of the specified app. This method use on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -Subscribes to the account change event of the specified account owners. This method uses an asynchronous callback to return the result. +Subscribes to account changes of the specified account owners. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -942,7 +944,7 @@ Subscribes to the account change event of the specified account owners. This met off(type: 'change', callback?: Callback>): void -Unsubscribes from the account change event. This method uses an asynchronous callback to return the result. +Unsubscribes from account changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1007,7 +1009,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "readAge", {}, { + appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -1017,7 +1019,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -Obtains the OAuth access token of an app account based on the specified authentication type. This method uses an asynchronous callback to return the result. +Obtains the OAuth token of an app account based on the specified authentication type. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1025,7 +1027,7 @@ Obtains the OAuth access token of an app account based on the specified authenti | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| | authType | string | Yes | Authentication type. | | callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | @@ -1034,7 +1036,7 @@ Obtains the OAuth access token of an app account based on the specified authenti ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); }); @@ -1044,7 +1046,7 @@ Obtains the OAuth access token of an app account based on the specified authenti getOAuthToken(name: string, owner: string, authType: string): Promise<string> -Obtains the OAuth access token of an app account based on the specified authentication type. This method uses a promise to return the result. +Obtains the OAuth token of an app account based on the specified authentication type. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1052,7 +1054,7 @@ Obtains the OAuth access token of an app account based on the specified authenti | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| | authType | string | Yes | Authentication type. | @@ -1066,7 +1068,7 @@ Obtains the OAuth access token of an app account based on the specified authenti ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { console.log("getOAuthToken err: " + JSON.stringify(err)); @@ -1077,7 +1079,7 @@ Obtains the OAuth access token of an app account based on the specified authenti setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -Sets an OAuth access token for an app account. This method uses an asynchronous callback to return the result. +Sets an OAuth token for an app account. This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1085,16 +1087,16 @@ Sets an OAuth access token for an app account. This method uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | -------- | -| name | string | Yes | App account name.| +| name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set.| +| token | string | Yes | OAuth token to set.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx", (err) => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1103,7 +1105,7 @@ Sets an OAuth access token for an app account. This method uses an asynchronous setOAuthToken(name: string, authType: string, token: string): Promise<void> -Sets an OAuth access token for an app account. This method uses a promise to return the result. +Sets an OAuth token for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1111,9 +1113,9 @@ Sets an OAuth access token for an app account. This method uses a promise to ret | Name | Type | Mandatory | Description | | -------- | ------ | ---- | -------- | -| name | string | Yes | App account name.| +| name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set.| +| token | string | Yes | OAuth token to set.| **Parameters** @@ -1125,7 +1127,7 @@ Sets an OAuth access token for an app account. This method uses a promise to ret ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx").then(() => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); @@ -1136,7 +1138,7 @@ Sets an OAuth access token for an app account. This method uses a promise to ret deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -Deletes the specified OAuth access token for an app account. This method uses an asynchronous callback to return the result. +Deletes the specified OAuth token for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1144,17 +1146,17 @@ Deletes the specified OAuth access token for an app account. This method uses an | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------ | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete.| +| token | string | Yes | OAuth token to delete.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx", (err) => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1163,7 +1165,7 @@ Deletes the specified OAuth access token for an app account. This method uses an deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -Deletes the specified OAuth access token for an app account. This method uses a promise to return the result. +Deletes the specified OAuth token for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1171,10 +1173,10 @@ Deletes the specified OAuth access token for an app account. This method uses a | Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------ | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete.| +| token | string | Yes | OAuth token to delete.| **Parameters** @@ -1186,7 +1188,7 @@ Deletes the specified OAuth access token for an app account. This method uses a ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx").then(() => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { console.log("deleteOAuthToken err: " + JSON.stringify(err)); @@ -1197,7 +1199,7 @@ Deletes the specified OAuth access token for an app account. This method uses a setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -Sets the visibility of an OAuth access token to the specified app. This method uses an asynchronous callback to return the result. +Sets the visibility of an OAuth token to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1205,17 +1207,17 @@ Sets the visibility of an OAuth access token to the specified app. This method u | Name | Type | Mandatory | Description | | ---------- | ------------------------- | ---- | ------------ | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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. | +| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err) => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -1224,7 +1226,7 @@ Sets the visibility of an OAuth access token to the specified app. This method u setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -Sets the visibility of an OAuth access token to the specified app. This method uses a promise to return the result. +Sets the visibility of an OAuth token to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1232,10 +1234,10 @@ Sets the visibility of an OAuth access token to the specified app. This method u | Name | Type | Mandatory | Description | | ---------- | ------- | ---- | ------------ | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | 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. | +| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. | **Parameters** @@ -1247,7 +1249,7 @@ Sets the visibility of an OAuth access token to the specified app. This method u ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1258,7 +1260,7 @@ Sets the visibility of an OAuth access token to the specified app. This method u checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -Checks whether an OAuth token is visible to the specified app. This method uses an asynchronous callback to return the result. +Checks whether an OAuth token is visible to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1266,7 +1268,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ---- | ------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | @@ -1275,7 +1277,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err, data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); }); @@ -1285,7 +1287,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -Checks whether an OAuth token is visible to the specified app. This method uses a promise to return the result. +Checks whether an OAuth token is visible to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1293,7 +1295,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| @@ -1307,7 +1309,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then((data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1318,7 +1320,7 @@ Checks whether an OAuth token is visible to the specified app. This method uses getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void -Obtains information about all OAuth access tokens of an app account visible to the specified app. This method uses an asynchronous callback to return the result. +Obtains all OAuth tokens visible to the caller for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1326,7 +1328,7 @@ Obtains information about all OAuth access tokens of an app account visible to t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| | callback | AsyncCallback<Array<OAuthTokenInfo>> | Yes | Callback invoked to return the result. | @@ -1344,7 +1346,7 @@ Obtains information about all OAuth access tokens of an app account visible to t getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> -Obtains information about all OAuth access tokens of an app account visible to the specified app. This method uses a promise to return the result. +Obtains all OAuth tokens visible to the caller for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1352,7 +1354,7 @@ Obtains information about all OAuth access tokens of an app account visible to t | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| **Parameters** @@ -1376,7 +1378,7 @@ Obtains information about all OAuth access tokens of an app account visible to t getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -Obtains the authorization list of OAuth access tokens of an app account. This method uses an asynchronous callback to return the result. +Obtains a list of authorized OAuth tokens of an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1384,7 +1386,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| | callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | @@ -1392,7 +1394,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); }); @@ -1402,7 +1404,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me getOAuthList(name: string, authType: string): Promise<Array<string>> -Obtains the authorization list of OAuth access tokens of an app account. This method uses a promise to return the result. +Obtains a list of authorized OAuth tokens of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1410,7 +1412,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | owner | string | Yes | Bundle name of the app.| **Parameters** @@ -1423,7 +1425,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getOAuthList err: " + JSON.stringify(err)); @@ -1434,7 +1436,7 @@ Obtains the authorization list of OAuth access tokens of an app account. This me getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void -Obtains the authenticator callback for a session. This method uses an asynchronous callback to return the result. +Obtains the authenticator callback for a session. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1458,7 +1460,7 @@ Obtains the authenticator callback for a session. This method uses an asynchrono } var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }); @@ -1469,7 +1471,7 @@ Obtains the authenticator callback for a session. This method uses an asynchrono getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> -Obtains the authenticator callback for a session. This method uses a promise to return the result. +Obtains the authenticator callback for a session. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1494,7 +1496,7 @@ Obtains the authenticator callback for a session. This method uses a promise to appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { @@ -1534,7 +1536,7 @@ Obtains authenticator information of an app account. This method uses an asynchr getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -Obtains authenticator information of an app account. This method uses a promise to return the result. +Obtains authenticator information of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1570,18 +1572,18 @@ Defines app account information. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | | owner | string | Yes | Bundle name of the app.| -| name | string | Yes | App account name. | +| name | string | Yes | Name of the app account. | ## OAuthTokenInfo8+ -Defines OAuth access token information. +Defines OAuth token information. **System capability**: SystemCapability.Account.AppAccount | Name | Type | Mandatory | Description | | -------- | ------ | ---- | -------- | | authType | string | Yes | Authentication type.| -| token | string | Yes | Value of the access token. | +| token | string | Yes | Value of the token. | ## AuthenticatorInfo8+ @@ -1591,9 +1593,9 @@ Defines OAuth authenticator information. | 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. | +| owner | string | Yes | Owner of the authenticator. The value is the bundle name of the app.| +| iconId | number | Yes | ID of the authenticator icon. | +| labelId | number | Yes | ID of the authenticator label. | ## Constants8+ @@ -1607,7 +1609,7 @@ Enumerates the constants. | ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | | KEY_NAME | "name" | App account name. | | KEY_OWNER | "owner" | App account owner.| -| KEY_TOKEN | "token" | OAuth access token. | +| KEY_TOKEN | "token" | OAuth token. | | KEY_ACTION | "action" | Action. | | KEY_AUTH_TYPE | "authType" | Authentication type. | | KEY_SESSION_ID | "sessionId" | Session ID. | @@ -1637,15 +1639,15 @@ Enumerates the result codes. | 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_TOKEN_NOT_EXIST | 10014 | The OAuth token does not exist.| +| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth 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+ -Provides methods for managing the OAuth authenticator callback. +Provides OAuth authenticator callbacks. ### onResult8+ @@ -1669,7 +1671,7 @@ Called back to send the authentication result. appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { @@ -1712,13 +1714,13 @@ Called back to redirect an authentication request. ## Authenticator8+ -Defines the OAuth authenticator base class. +OAuth authenticator base class. ### addAccountImplicitly8+ addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Implicitly adds an app account based on the specified authentication type and options. This method uses an asynchronous callback to return the result. +Implicitly adds an app account based on the specified authentication type and options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1734,14 +1736,14 @@ Implicitly adds an app account based on the specified authentication type and op authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Authenticates an app account to obtain the OAuth access token. This method uses an asynchronous callback to return the result. +Authenticates an app account to obtain the OAuth token. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | -| name | string | Yes | App account name. | +| name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | callerBundleName | string | Yes | Bundle name of the authentication requester. | | options | {[key: string]: any} | Yes | Options for the authentication. | diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index 3731cf8c99930e4bdf470946c5ad00067c142c21..b52bbbfb03c03b27b63bc137d0056af4f134327a 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -1,14 +1,13 @@ # 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. +The **Want** module provides the basic communication component of the system. +> **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 Want from '@ohos.application.Want'; ``` @@ -20,11 +19,55 @@ import Want from '@ohos.application.Want'; | 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.| +| 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 match a specific 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 match a specific 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).| +| 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. 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. | | +| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read only | Array\ | No | List of entities. | +| extensionAbilityType9+ | Read only | bundle.ExtensionAbilityType | No | Type of the Extension ability. | +| extensionAbilityName9+ | Read only | string | No | Description of the Extension ability name in the **Want** object. | + +**Example** + +- Basic usage + + ```js + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "uri": "pages/second" // uri is optional and can be used to pass the destination URI. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing a file descriptor (FD) + + ```js + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 75f75008aa73d07c618ddd1db2a0deac373f84d3..5a2236019b7fc888af15b2da38602df92d892f25 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -21,8 +21,8 @@ import Ability from '@ohos.application.Ability'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters used when the ability was started last time.| +| launchWant | [Want](js-apis-application-want.md)| Yes| No| Parameters for starting the ability.| +| lastRequestWant | [Want](js-apis-application-want.md)| Yes| No| Parameters used when the ability was started last time.| ## Ability.onCreate @@ -37,7 +37,7 @@ Called to initialize the service logic when an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this ability, including the ability name and bundle name.| + | want | [Want](js-apis-application-want.md)| Yes| Information related to this ability, including the ability name and bundle name.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| **Example** @@ -222,7 +222,7 @@ Called when the ability startup mode is set to singleton. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Want parameters, such as the ability name and bundle name.| + | want | [Want](js-apis-application-want.md)| Yes| Want parameters, such as the ability name and bundle name.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 635df95894dc0b2148aefc98ea7c4eb8a163b517..b8262e80289f9288bbd2665775c2844cbdd8cc42 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,13 +1,11 @@ # Context -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> +> **NOTE** > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. Provides the context for running code, including **applicationInfo** and **resourceManager**. - ## Usage @@ -36,7 +34,7 @@ You must extend **AbilityContext** to implement this module. createBundleContext(bundleName: string): Context; -Creates an application context. +Creates a context for a given application. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -50,10 +48,10 @@ Creates an application context. | Type| Description| | -------- | -------- | -| Context | Context of the application created.| +| Context | Context created.| **Example** - + ```js let test = "com.example.test"; let context = this.context.createBundleContext(test); @@ -74,9 +72,47 @@ Obtains the context of this application. | -------- | -------- | | Context | Context obtained.| -**Example** - +**Example** + ```js // This part is mandatory. let context = this.context.getApplicationContext(); ``` + + + +> **NOTE** +> +> Currently, API version 9 is a Canary version. + +## Context.switchArea + +switchArea(mode: AreaMode): void + +Switches the file area mode. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------- | ---- | -------------- | +| mode | [AreaMode](#AreaMode) | Yes | File area mode.| + +**Example** + +```js +var areaMode = 0 +this.context.switchArea(areaMode); +``` + +## AreaMode + +Describes the file area mode. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Value | +| ---- | -------- | ---- | +| EL1 | number | 0 | +| EL2 | number | 1 | diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 0b31d38d305281fec2aa327959de91e1833e409f..4c7c030e7c93c92ac03ac1e892c470893b78993a 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,10 +1,6 @@ # Audio Management -> **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. -> -> API version 9 is a canary release for trial use. The APIs of this version may be unstable. +The **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering. This module provides the following common audio-related functions: @@ -12,6 +8,12 @@ This module provides the following common audio-related functions: - [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. +> **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. +> +> API version 9 is a canary release for trial use. The APIs of this version may be unstable. + ## Modules to Import ``` @@ -570,8 +572,8 @@ Describes the device connection status and device information. | Name | Type | Mandatory| Description | | :---------------- | :------------------------------------------------ | :--- | :----------------- | -| type | [DeviceChangeType](#DeviceChangeType) | Yes | Device connection status.| -| deviceDescriptors | [AudioDeviceDescriptors](#AudioDeviceDescriptors) | Yes | Device information. | +| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| +| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | ## DeviceChangeType @@ -641,6 +643,8 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l Sets the volume for a stream. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -669,6 +673,8 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -863,6 +869,8 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -891,6 +899,8 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> Mutes or unmutes a stream. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1033,6 +1043,8 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer.) + **System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1060,6 +1072,8 @@ setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer.) + **System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1140,6 +1154,8 @@ Sets an audio parameter. This API uses an asynchronous callback to return the re This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + **System capability**: SystemCapability.Multimedia.Audio.Core **Parameters** @@ -1170,6 +1186,8 @@ Sets an audio parameter. This API uses a promise to return the result. This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + **System capability**: SystemCapability.Multimedia.Audio.Core **Parameters** @@ -1426,6 +1444,8 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1453,6 +1473,8 @@ setMicrophoneMute(mute: boolean): Promise<void> Mutes or unmutes the microphone. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1481,6 +1503,8 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** @@ -1507,6 +1531,8 @@ isMicrophoneMute(): Promise<boolean> Checks whether the microphone is muted. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MICROPHONE + **System capability**: SystemCapability.Multimedia.Audio.Device **Return value** @@ -1538,7 +1564,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected.| | callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Example** @@ -1565,8 +1591,8 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | **Example** @@ -1588,7 +1614,7 @@ Subscribes to device change events. When a device is connected or disconnected, | Name | Type | Mandatory| Description | | :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | Yes | Callback used to return the device update details. | **Example** @@ -1614,7 +1640,7 @@ Unsubscribes from device change events. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | No | Callback used to return the device update details. | **Example** @@ -1637,7 +1663,7 @@ Subscribes to audio interruption events. When the application's audio is interru | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | interrupt | AudioInterrupt | Yes | Audio interruption event type. | | callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | @@ -1673,7 +1699,7 @@ Unsubscribes from audio interruption events. | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | interrupt | AudioInterrupt | Yes | Audio interruption event type. | | callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | @@ -2235,14 +2261,50 @@ Writes the buffer. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Returns the number of bytes written if the operation is successful; returns an error code otherwise.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| **Example** ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data)=> { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data)=> { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('Buffer size:'+bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); +var filePath = path+"/StarWars10s-2C-48000-4SW.wav" let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); @@ -2267,14 +2329,49 @@ Writes the buffer. This API uses a promise to return the result. | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Returns the number of bytes written if the operation is successful; returns an error code otherwise.| +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| **Example** ``` import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; +import featureAbility from '@ohos.ability.featureAbility' +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); +var bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); + }); +console.info('BufferSize: ' + bufferSize); +var context = featureAbility.getContext(); +var path = await context.getCacheDir(); var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); @@ -2377,12 +2474,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels:audio.AudioChannel.CHANNEL_2, + sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType.audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.streamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 +} + +var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo +} +var audioRenderer; +audio.createAudioRenderer(audioRendererOptions).then((data) => { + audioRenderer = data; + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message); + }); var bufferSize; -await audioRenderer.getBufferSize().then(async function (data) => { - console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); +audioRenderer.getBufferSize().then((data) => { + console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data); bufferSize=data; }).catch((err) => { - console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); + console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message); }); ``` @@ -2501,7 +2625,7 @@ Subscribes to audio interruption events. This API uses a callback to get interru | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when audio playback is interrupted.| | callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | **Example** @@ -2567,7 +2691,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **'markReach'** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | @@ -2575,7 +2699,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ``` audioRenderer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2594,7 +2718,7 @@ Unsubscribes from mark reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :------------------------------------------------ | -| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **markReach**.| +| type | string | Yes | Event type. The value is fixed at **'markReach'**.| **Example** @@ -2614,15 +2738,15 @@ Subscribes to period reached events. When the period of frame rendering reaches | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | +| type | string | Yes | Event type. The value **'periodReach'** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| +| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | **Example** ``` audioRenderer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -2640,7 +2764,7 @@ Unsubscribes from period reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :-------------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **periodReach**.| +| type | string | Yes | Event type. The value is fixed at **'periodReach'**.| **Example** @@ -2660,7 +2784,7 @@ Subscribes to state change events. | Name | Type | Mandatory| Description | | :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| type | string | Yes | Event type. The value **'stateChange'** means the state change event.| | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -2856,13 +2980,35 @@ Starts capturing. This API uses a promise to return the result. **Example** ``` +import audio from '@ohos.multimedia.audio'; +import fileio from '@ohos.fileio'; + +var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_2, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW +} + +var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags = 1 +} + +var audioCapturer; +audio.createAudioCapturer(audioCapturerOptions).then((data) => { + audioCapturer = data; + console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); + }).catch((err) => { + console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message); + }); audioCapturer.start().then(() => { console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); - console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS '); if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - stateFlag = true; + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); } }).catch((err) => { console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); @@ -2915,15 +3061,13 @@ Stops capturing. This API uses a promise to return the result. ``` audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); - if ((audioCapturer.state == audioCapturer.AudioState.STATE_STOPPED)){ - stateFlag=true; - console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag); + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped': '); } }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false; + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -2975,13 +3119,9 @@ audioCapturer.release().then(() => { console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); - stateFlag=true; console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); - expect(stateFlag).assertTrue(); - done(); }).catch((err) => { - console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); - stateFlag=false + console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message); }); ``` @@ -3005,6 +3145,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message); + }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { console.log("Success in reading the buffer data"); @@ -3032,11 +3179,19 @@ Reads the buffer. This API uses a promise to return the result. | Type | Description | | :-------------------- | :----------------------------------------------------- | -| Promise | Returns the buffer data read if the operation is successful; returns an error code otherwise.| +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned.| **Example** ``` +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data); + bufferSize = data; + }).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message); + }); +console.info('Buffer size: ' + bufferSize); audioCapturer.read(bufferSize, true).then((buffer) => { console.info('buffer read successfully'); }).catch((err) => { @@ -3057,7 +3212,7 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). | Name | Type | Mandatory| Description | | :------- | :--------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the timestamp.| +| callback | AsyncCallback | Yes | Callback used to return the timestamp. | **Example** @@ -3140,15 +3295,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Example** ``` -audioCapturer.getBufferSize().then((bufferSize) => { - if (!err) { - console.log('BufferSize : ' + bufferSize); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('Buffer read is ' + buffer ); - }).catch((err) => { - console.info('ERROR : '+err.message); - }); - } +var bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data); + bufferSize = data; +}).catch((err) => { + console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message); }); ``` @@ -3165,7 +3317,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th | Name | Type | Mandatory| Description | | :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| type | string | Yes | Event type. The value **'markReach'** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | callback | position: number) => {} | Yes | Callback invoked when the event is triggered.| @@ -3173,7 +3325,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ``` audioCapturer.on('markReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -3191,7 +3343,7 @@ Unsubscribes from mark reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **'markReach'** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| **Example** @@ -3211,15 +3363,15 @@ Subscribes to mark reached events. When the period of frame capturing reaches th | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| -| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | +| type | string | Yes | Event type. The value **'periodReach'** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter. | +| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | **Example** ``` audioCapturer.on('periodReach', 1000, (position) => { - if (position == "1000") { + if (position == 1000) { console.log('ON Triggered successfully'); } }); @@ -3237,7 +3389,7 @@ Unsubscribes from period reached events. | Name| Type | Mandatory| Description | | :----- | :----- | :--- | :---------------------------------------------- | -| type | string | Yes | Type of event to unsubscribe from. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| type | string | Yes | Event type. The value **'periodReach'** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| **Example** @@ -3257,7 +3409,7 @@ Subscribes to state change events. | Name | Type | Mandatory| Description | | :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| +| type | string | Yes | Event type. The value **'stateChange'** means the state change event.| | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index a0d93b14fc86287eeb8b9dedcff4bfd7f0d210f3..b65d3e3f9d45c1819ce94926322069c220857669 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 @@ > **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. -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 @@ -12,18 +12,6 @@ Provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and import bluetooth from '@ohos.bluetooth'; ``` - -## Required Permissions - -ohos.permission.USE_BLUETOOTH - -ohos.permission.MANAGE_BLUETOOTH - -ohos.permission.DISCOVER_BLUETOOTH - -ohos.permission.LOCATION - - ## bluetooth.enableBluetooth8+ enableBluetooth(): boolean @@ -202,7 +190,7 @@ let result = bluetooth.pairDevice("XX:XX:XX:XX:XX:XX"); getProfileConnState(profileId: ProfileId): ProfileConnectionState -Obtains the connection status of a profile. +Obtains the connection state of a profile. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -233,6 +221,8 @@ cancelPairedDevice(deviceId: string): boolean Cancels a paired remote device. +This is a system API. + **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -318,7 +308,7 @@ let remoteDeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); getPairedDevices(): Array<string> -Obtains the Bluetooth pairing list. +Obtains the paired devices. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -328,7 +318,7 @@ Obtains the Bluetooth pairing list. | Type | Description | | ------------------- | ------------- | -| Array<string> | List of the addresses of the paired Bluetooth devices.| +| Array<string> | Addresses of the paired Bluetooth devices.| **Example** @@ -352,7 +342,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de | Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | ---------------------------- | | mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode to set. | -| duration | number | Yes | Duration (in seconds) in which the device can be discovered. The value **0** indicates unlimited time.| +| duration | number | Yes | Duration (in ms) in which the device can be discovered. The value **0** indicates unlimited time.| **Return value** @@ -397,7 +387,7 @@ startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover remote devices. -**Required permissions**: ohos.permission.USE_BLUETOOTH and ohos.permission.LOCATION +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -607,7 +597,7 @@ bluetooth.off('pinRequired', onReceiveEvent); on(type: "bondStateChange", callback: Callback<BondStateParam>): void -Subscribes to the Bluetooth pairing state change events. +Subscribes to the Bluetooth bond state change events. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -617,8 +607,8 @@ Subscribes to the Bluetooth pairing state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------------ | -| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event.| -| callback | Callback<[BondStateParam](#bondstate)> | Yes | Callback invoked to return the pairing state. You need to implement this callback. | +| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth bond state change event.| +| callback | Callback<[BondStateParam](#bondstateparam8)> | Yes | Callback invoked to return the bond state. You need to implement this callback. | **Return value** @@ -627,7 +617,7 @@ No value is returned. **Example** ```js -function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the pairing state. +function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the bond state. console.info('pair state = '+ JSON.stringify(data)); } bluetooth.on('bondStateChange', onReceiveEvent); @@ -638,7 +628,7 @@ bluetooth.on('bondStateChange', onReceiveEvent); off(type: "bondStateChange", callback?: Callback<BondStateParam>): void -Unsubscribes from the Bluetooth pairing state change events. +Unsubscribes from the Bluetooth bond state change events. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -648,8 +638,8 @@ Unsubscribes from the Bluetooth pairing state change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event. | -| callback | Callback<[BondStateParam](#bondstate)> | No | Callback used to report the change of the Bluetooth pairing state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| +| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth bond state change event. | +| callback | Callback<[BondStateParam](#bondstateparam8)> | No | Callback used to report the change of the Bluetooth bond state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| **Return value** @@ -1277,7 +1267,7 @@ No value is returned. getDeviceState(device: string): ProfileConnectionState -Obtains the connection status of the profile. +Obtains the connection state of the profile. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -1293,7 +1283,7 @@ Obtains the connection status of the profile. | | | | ------------------------------------------------- | ----------------------- | | Type | Description | -| [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained. | ## A2dpSourceProfile @@ -1315,7 +1305,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device to connect.| +| device | string | Yes | Address of the target device.| | **Return value** @@ -1347,7 +1337,7 @@ Disconnects an A2DP connection. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device to disconnect.| +| device | string | Yes | Address of the target device.| | **Return value** @@ -1369,7 +1359,7 @@ let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the A2DP connection status change events. +Subscribes to the A2DP connection state change events. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1396,9 +1386,9 @@ A2dpSourceProfile.on('connectionStateChange', onReceiveEvent); ### A2dpSourceProfile.off('connectionStateChange')8+ -off(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the A2DP connection status change events. +Unsubscribes from the A2DP connection state change events. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1423,11 +1413,13 @@ A2dpSourceProfile.off('connectionStateChange', onReceiveEvent); ``` -### getPlayingState +### getPlayingState9+ getPlayingState(device: string): PlayingState -Obtains the playing status of a device. +Obtains the playing state of a device. + +**Required permissions**: ohos.permission.USE_BLUETOOTH **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1442,7 +1434,7 @@ Obtains the playing status of a device. | | | | ----------------------------- | ---------- | | Type | Description | -| [PlayingState](#PlayingState) | Playing status obtained. | +| [PlayingState](#PlayingState) | Playing state obtained. | **Example** @@ -1524,7 +1516,7 @@ let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); on(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void -Subscribes to the HFP connection status change events. +Subscribes to the HFP connection state change events. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1533,7 +1525,7 @@ Subscribes to the HFP connection status change events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type. The value **connectionStateChange** indicates an HFP connection state change event.| -| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback invoked to return the HFP connection state change event. | +| callback | Callback<[StateChangeParam](#StateChangeParam)> | Yes | Callback used to return the HFP connection state change event. | **Return value** @@ -1551,9 +1543,9 @@ HandsFreeAudioGatewayProfile.on('connectionStateChange', onReceiveEvent); ### HandsFreeAudioGatewayProfile.off('connectionStateChange')8+ -off(type: "connectionStateChange", callback: Callback<[StateChangeParam](#StateChangeParam)>): void +off(type: "connectionStateChange", callback?: Callback<[StateChangeParam](#StateChangeParam)>): void -Unsubscribes from the HFP connection status change events. +Unsubscribes from the HFP connection state change events. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1704,7 +1696,7 @@ let descV = new Uint8Array(arrayBuffer); descV[0] = 11; let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', - descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; descriptors[0] = descriptor; // Create characteristics. @@ -1807,6 +1799,16 @@ Notifies the connected client device when a characteristic value changes. **Example** ```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; + let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; @@ -1880,7 +1882,7 @@ Subscribes to the characteristic read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------------- | | type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event.| -| callback | Callback<[CharacteristicReadReq](#characteristicreadreq)> | Yes | Callback invoked to return a characteristic read request from the GATT client. | +| callback | Callback<[CharacteristicReadReq](#characteristicreadreq)> | Yes | Callback invoked to return a characteristic read request event from the GATT client. | **Return value** @@ -1957,7 +1959,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<[CharacteristicWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | +| callback | Callback<[CharacteristicWriteReq](#characteristicwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | **Return value** @@ -2325,7 +2327,7 @@ let ret = device.close(); getServices(callback: AsyncCallback<Array<GattService>>): void -Obtains all services of the remote BLE device. This method uses an asynchronous callback to return the result. +Obtains all services of the remote BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2367,7 +2369,7 @@ device.getServices(getServices); getServices(): Promise<Array<GattService>> -Obtains all services of the remote BLE device. This method uses a promise to return the result. +Obtains all services of the remote BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2387,12 +2389,9 @@ Obtains all services of the remote BLE device. This method uses a promise to ret // Promise let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); device.connect(); -var services = device.getServices(); -console.log("bluetooth services size is ", services.length); - -for (let i = 0; i < services.length; i++) { - console.log('bluetooth serviceUuid is ' + services[i].serviceUuid); -} +device.getServices().then(result => { + console.info("getServices successfully:" + JSON.stringify(result)); +}); ``` @@ -2400,7 +2399,7 @@ for (let i = 0; i < services.length; i++) { readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback<BLECharacteristic>): void -Reads the characteristic value of the specific service of the remote BLE device. This method uses an asynchronous callback to return the result. +Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2454,7 +2453,7 @@ device.readCharacteristicValue(characteristic, readCcc); readCharacteristicValue(characteristic: BLECharacteristic): Promise<BLECharacteristic> -Reads the characteristic value of the specific service of the remote BLE device. This method uses a promise to return the result. +Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2501,7 +2500,7 @@ device.readCharacteristicValue(characteristic); readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback<BLEDescriptor>): void -Reads the descriptor contained in the specific characteristic of the remote BLE device. This method uses an asynchronous callback to return the result. +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2545,7 +2544,7 @@ device.readDescriptorValue(descriptor, readDesc); readDescriptorValue(descriptor: BLEDescriptor): Promise<BLEDescriptor> -Reads the descriptor contained in the specific characteristic of the remote BLE device. This method uses a promise to return the result. +Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2673,7 +2672,7 @@ if (retWriteDesc) { setBLEMtuSize(mtu: number): boolean -Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This method can be used only after a connection is set up by calling [connect](#connect). +Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2725,6 +2724,16 @@ Sets the function of notifying the GATT client when the characteristic value of **Example** ```js +// Create descriptors. +let descriptors = []; +let arrayBuffer = new ArrayBuffer(8); +let descV = new Uint8Array(arrayBuffer); +descV[0] = 11; +let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', + descriptorUuid: '00002902-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer}; +descriptors[0] = descriptor; + let arrayBufferC = new ArrayBuffer(8); let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; @@ -2862,7 +2871,7 @@ device.off('BLEConnectionStateChange'); getDeviceName(callback: AsyncCallback<string>): void -Obtains the name of the remote BLE device. This method uses an asynchronous callback to return the result. +Obtains the name of the remote BLE device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2894,7 +2903,7 @@ let deviceName = gattClient.getDeviceName((err, data)=> { getDeviceName(): Promise<string> -Obtains the name of the remote BLE device. This method uses a promise to return the result. +Obtains the name of the remote BLE device. This API uses a promise to return the result. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2922,7 +2931,7 @@ let deviceName = gattClient.getDeviceName().then((data) => { getRssiValue(callback: AsyncCallback<number>): void -Obtains the received signal strength indication (RSSI) of the remote BLE device. This method uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). +Obtains the received signal strength indication (RSSI) of the remote BLE device. This API uses an asynchronous callback to return the result. It can be used only after a connection is set up by calling [connect](#connect). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -2955,7 +2964,7 @@ let rssi = gattClient.getRssiValue((err, data)=> { getRssiValue(): Promise<number> -Obtains the RSSI of the remote BLE device. This method uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). +Obtains the RSSI of the remote BLE device. This API uses a promise to return the result. It can be used only after a connection is set up by calling [connect](#connect). **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -3202,7 +3211,7 @@ Defines the scan filter parameters. | ----------- | ------ | ---- | ---- | ---------------------------------------- | | deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. | | name | string | Yes | Yes | Name of the BLE device to filter. | -| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.| +| serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.| ## ScanOptions @@ -3281,7 +3290,7 @@ Defines the BLE advertising parameters. | Name | Type | Readable | Writable | Description | | ----------- | ------- | ---- | ---- | ---------------------------------------- | -| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16777215** slots. The default value is **1600** slots (1s).| +| interval | number | Yes | Yes | Interval for BLE advertising. The minimum value is **32** slots (20 ms). The maximum value is **16384** slots. The default value is **1600** slots (1s).| | txPower | number | Yes | Yes | Transmit power, in dBm. The value range is -127 to 1. The default value is **-7**. | | connectable | boolean | Yes | Yes | Whether the advertisement is connectable. The default value is **true**. | @@ -3335,6 +3344,18 @@ Defines the pairing request parameters. | pinCode | string | Yes | No | Key for the device pairing. | +## BondStateParam8+ + +Defines the bond state parameters. + +**System capability**: SystemCapability.Communication.Bluetooth.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ----------- | +| deviceId | string | Yes | No | ID of the device.| +| state | BondState | Yes | No | State of the device.| + + ## StateChangeParam8+ Defines the profile state change parameters. @@ -3492,7 +3513,7 @@ Enumerates the A2DP playing states. ## ProfileId8+ -Enumerates the Bluetooth profile IDs. +Enumerates the Bluetooth profiles. **System capability**: SystemCapability.Communication.Bluetooth.Core diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index 6bbea8b08a752972bcc9354b63841831ae837a88..e0b192951999cae7daba27a9f58d93e6c64af860 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,10 +1,10 @@ # Brightness -> ![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 Brightness module provides an API for setting the screen brightness. +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 75f36cbabd3f1cb7fd3fd16634a8b1193f55b314..cb7a8b6b093af914131be0dec737f8d130a4bc37 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,19 +1,16 @@ # AbilityInfo +Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. - -> **NOTE**
+> **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. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. -Provides the ability information. +## AbilityInfo - - - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | @@ -26,22 +23,23 @@ Provides the ability information. | 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 the ability runs. If this parameter is not set, the bundle name is used.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to. | -| backgroundModes | number | Yes | No | Background service mode of the ability. | +| 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. | +| 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.| +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | 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. | +| 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.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| 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\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability. | -| metaData9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | +| metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| +| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| | enabled8+ | boolean | Yes | No | Whether the ability is enabled. | + diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index db5f9d10136113d71f195e54b6a07ba22b81d186..fb72c282c8d9e3e1845e0f27168c1a1f85c55e0e 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,43 +1,38 @@ # ApplicationInfo +The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - -> **NOTE**
+> **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. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - - -Provides the application information. - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. +## ApplicationInfo **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.| -| 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\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | 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. | -| 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. | -| entityType8+ | 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. | +| 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.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| +| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | 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.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| +| metadata9+ | Map\> | Yes | No | Metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| +| 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. | +| entityType8+ | string | Yes | No | Entity type of the application. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index 4faaf2531a2a3e36733dcc190c8401f39374fd65..2f5348529a0b27e4c594550f9f57219e534b2013 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,46 +1,43 @@ # BundleInfo +The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - -> **NOTE**
+> **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. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - - -Provides the application bundle information. - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. +## BundleInfo **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\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information. | -| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application. | -| reqPermissionDetails | Array\<[ReqPermissionDetail](#ReqPermissionDetail)> | 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\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | 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 the application can be installed 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 module. | -| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | -| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information. | +| 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\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.
The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| +| reqPermissions | Array\ | Yes | No | Permissions to request from the system for running the application.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.
The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| +| 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\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether the application can be installed 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 module. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | +| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.
The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md index d45e4620d5af5f29334b9cb4bc264acea124095a..1514d377fc4c4e02df7e593b46d75fb0170c9607 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md +++ b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @@ -1,20 +1,15 @@ # CustomizeData - - -> **NOTE**
+> **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. - - Provides custom metadata. - +## CustomizeData **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | ------------------ | ------ | ---- | ---- | ---------------- | | name | string | Yes | Yes | Custom metadata name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md index 596753259d18ac2defea135cb8479719977f9ced..0ceee9af9b11189035dee2406e50d6b443581b8a 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @@ -1,17 +1,14 @@ # ExtensionAbilityInfo +The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - - -Provides the Extension ability information. - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. +## ExtensionAbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework @@ -27,7 +24,7 @@ Provides the Extension ability information. | extensionAbilityType | bundle.ExtensionAbilityType | Yes | No | Type of the Extension ability. | | permissions | Array\ | Yes | No | Permissions required for other applications to call the Extension ability.| | applicationInfo | ApplicationInfo | Yes | No | Application information of the Extension ability. | -| metaData | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | +| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | | enabled | boolean | Yes | No | Whether the Extension ability is enabled. | -| readPermission | string | Yes | No | Permission required for reading the Extension ability data. | +| readPermission | string | Yes | No | Permission required for reading data from the Extension ability. | | writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index dd69a7f722faa97d3e50db2ed82bb691b4bd8211..58a9e46ead747d0004ce9730d602d63db6af1c70 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,22 +1,17 @@ # HapModuleInfo +The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. - -> **NOTE**
+> **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. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - - -Provides the HAP module information. - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. +## HapModuleInfo **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | | name | string | Yes | No | Module name. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-Metadata.md b/en/application-dev/reference/apis/js-apis-bundle-Metadata.md index cf1060e9a4634c480da7b1bb21c25342eac019cd..b4adfc6882c6558e38339bee673cca9de12743c1 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-Metadata.md +++ b/en/application-dev/reference/apis/js-apis-bundle-Metadata.md @@ -1,24 +1,20 @@ # Metadata +The **Metadata** module provides the metadata information. - -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. - - - -Provides the metadata information. - +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. +## Metadata **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | -------- | ------ | ---- | ---- | ---------- | | name | string | Yes | Yes | Metadata name.| | value | string | Yes | Yes | Metadata value. | | resource | string | Yes | Yes | Metadata resource.| + diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 71fc24ff40eca2febce360b6be7b9eeb149d1b52..a971f509315963d3f9e3816d7471b880f23dfa3f 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -1,20 +1,15 @@ # ModuleInfo - - -> **NOTE**
+> **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. - - Provides the module information of the application. - +## ModuleInfo **System capability**: SystemCapability.BundleManager.BundleFramework - - | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 40a50ebc4aa5ea496d19df951ff04d03240a1b93..69bc43b637e75ee32acaf67fbf12a5658cc81055 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,13 +1,13 @@ # Performance Tracing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead. > - 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 -``` +```js import bytrace from '@ohos.bytrace'; ``` @@ -17,24 +17,26 @@ import bytrace from '@ohos.bytrace'; startTrace(name: string, taskId: number, expectedTime?: number): void -Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. +Marks the start of a timeslice trace task. + +> **NOTE** +> +> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. -**System capability**: SystemCapability.Developtools.Bytrace +**System capability**: SystemCapability.HiviewDFX.HiTrace **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the trace task to start.| -| taskId | number | Yes| Task ID.| +| name | string | Yes| Name of a timeslice trace task.| +| taskId | number | Yes| ID of a timeslice trace task.| | expectedTime | number | No| Expected duration of the trace, in ms.| -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. **Example** -``` +```js bytrace.startTrace("myTestFunc", 1); bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms. ``` @@ -44,23 +46,25 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is finishTrace(name: string, taskId: number): void -Stops a trace task. +Marks the end of a timeslice trace task. -**System capability**: SystemCapability.Developtools.Bytrace +> **NOTE** +> +> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. + +**System capability**: SystemCapability.HiviewDFX.HiTrace **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the trace task to start.| -| taskId | number | Yes| Task ID.| +| name | string | Yes| Name of a timeslice trace task.| +| taskId | number | Yes| ID of a timeslice trace task.| -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. **Example** -``` +```js bytrace.finishTrace("myTestFunc", 1); ``` @@ -91,9 +95,9 @@ bytrace.finishTrace("myTestFunc", 1); traceByValue(name: string, count: number): void -Traces the value changes of a variable. +Defines the variable that indicates the number of timeslice trace tasks. -**System capability**: SystemCapability.Developtools.Bytrace +**System capability**: HiviewDFX.HiTrace **Parameters** | Name| Type| Mandatory| Description| @@ -103,7 +107,7 @@ Traces the value changes of a variable. **Example** -``` +```js let traceCount = 3; bytrace.traceByValue("myTestCount", traceCount); traceCount = 4; diff --git a/en/application-dev/reference/apis/js-apis-config-policy.md b/en/application-dev/reference/apis/js-apis-config-policy.md index 8145056a3d6788baa31f7b80fdc3b7565c0ec77a..9a5abe4a6996933ef403fae468b3a54d99d45e38 100644 --- a/en/application-dev/reference/apis/js-apis-config-policy.md +++ b/en/application-dev/reference/apis/js-apis-config-policy.md @@ -1,13 +1,13 @@ # Configuration Policy +The configuration policy provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level. + > **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. -The configuration policy provides the capability of obtaining the custom configuration directory and file path based on the predefined custom configuration level. - ## Modules to Import ```js @@ -16,10 +16,10 @@ import configPolicy from '@ohos.configPolicy'; ## getOneCfgFile -getOneCfgFile(relPath: string, callback: AsyncCallback<string>): void +getOneCfgFile(relPath: string, callback: AsyncCallback<string>) Obtains the path of a configuration file with the specified name and highest priority. This API uses an asynchronous callback to return the result. -For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys-pod/etc/config.xml** (in ascending order of priority), then **/sys-pod/etc/config.xml** is returned. +For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml** (in ascending order of priority), then **/sys_pod/etc/config.xml** is returned. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -31,7 +31,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **Example** ```js - configPolicy.getOneCfgFile('config.xml', (error, value) => { + configPolicy.getOneCfgFile('etc/config.xml', (error, value) => { if (error == undefined) { console.log("value is " + value); } else { @@ -61,7 +61,7 @@ Obtains the path of a configuration file with the specified name and highest pri **Example** ```js - configPolicy.getOneCfgFile('config.xml').then(value => { + configPolicy.getOneCfgFile('etc/config.xml').then(value => { console.log("value is " + value); }).catch(error => { console.log("getOneCfgFile promise " + error); @@ -71,10 +71,9 @@ Obtains the path of a configuration file with the specified name and highest pri ## getCfgFiles -getCfgFiles(relPath: string, callback: AsyncCallback<Array<string>>): void +getCfgFiles(relPath: string, callback: AsyncCallback<Array<string>>) -Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml** -and **/sys-pod/etc/config.xml**, then **/system/etc/config.xml, /sys-pod/etc/config.xml** is returned. +Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml**, then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -86,7 +85,7 @@ and **/sys-pod/etc/config.xml**, then **/system/etc/config.xml, /sys-pod/etc/con **Example** ```js - configPolicy.getCfgFiles('config.xml', (error, value) => { + configPolicy.getCfgFiles('etc/config.xml', (error, value) => { if (error == undefined) { console.log("value is " + value); } else { @@ -116,7 +115,7 @@ Obtains all configuration files with the specified name and lists them in ascend **Example** ```js - configPolicy.getCfgFiles('config.xml').then(value => { + configPolicy.getCfgFiles('etc/config.xml').then(value => { console.log("value is " + value); }).catch(error => { console.log("getCfgFiles promise " + error); @@ -126,7 +125,7 @@ Obtains all configuration files with the specified name and lists them in ascend ## getCfgDirList -getCfgDirList(callback: AsyncCallback<Array<string>>): void +getCfgDirList(callback: AsyncCallback<Array<string>>) Obtains the configuration level directory list. This API uses an asynchronous callback to return the result. 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 b801f7038e84713dd3096a7c7c63f3a03314e2a5..e411ed212e606f1e14e68318c4abe3505ec80178 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,6 +1,8 @@ # DataAbilityPredicates -> **NOTE** +**DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. + +> **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. @@ -24,15 +26,15 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Table name in the RDB store.| -| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Name of a database table.| + | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** -| Type| Description| -| -------- | -------- | -| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| + | Type| Description| + | -------- | -------- | + | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** ```js @@ -58,15 +60,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -85,15 +87,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -112,9 +114,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** ```js @@ -138,9 +140,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** ```js @@ -164,9 +166,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** ```js @@ -187,9 +189,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** ```js @@ -210,15 +212,15 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **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**.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -237,15 +239,15 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **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**.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -264,15 +266,15 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **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**.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ``` @@ -291,14 +293,14 @@ 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.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -317,14 +319,14 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -343,15 +345,15 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **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**.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -370,15 +372,15 @@ 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**.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -392,21 +394,21 @@ Sets a **DataAbilityPredicates** object to match the specified string. 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. +Sets a **DataAbilityPredicates** object to match a 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](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| -| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -425,16 +427,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| -| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -453,15 +455,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -480,15 +482,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -507,15 +509,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -534,15 +536,15 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| -| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -561,14 +563,14 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -587,14 +589,14 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| field | string | Yes| Column name in the table.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -613,9 +615,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** ```js @@ -634,14 +636,14 @@ 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.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** ```js @@ -660,14 +662,14 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **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.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** ```js @@ -686,14 +688,14 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| fields | Array<string> | Yes| Names of columns to group.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** ```js @@ -705,20 +707,20 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i indexedBy(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to specify the index column. -**System capability**: SystemCapability.DistributedDataManager.DataShare.Core +Sets a **DataAbilityPredicates** object to specify the index column. +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| indexName | string | Yes| Name of the index column.| + | 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.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** ```js @@ -732,21 +734,21 @@ Sets a **DataAbilityPredicates** object to specify the index column. 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. +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](#valuetype)> | Yes| Array of **ValueType**s to match.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -760,21 +762,21 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< 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. +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](#valuetype)> | Yes| Array of **ValueType**s to match.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type| Description| -| -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** ```js @@ -787,7 +789,7 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core -| Name | Description | +| Type | Description | | ------- | -------------------- | | number | The value is a number. | | string | The value is a string. | 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 62d9896f3d2af4e47ea6f6ee152f565a932f0463..1b17be0e8011b117e821248ce9bd0c07d1165d47 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,6 +1,14 @@ # Relational Database +The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. + +This module provides the following RDB-related functions: + +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbStore](#rdbstore): provides APIs for managing an RDB store. + > **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 @@ -11,71 +19,9 @@ import data_rdb from '@ohos.data.rdb'; ## data_rdb.getRdbStore -getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void - -Obtains a relational database (RDB) store. This API 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. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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** - -```js -const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { - if (err) { - console.info("Failed to get RdbStore, err: " + err) - return - } - console.log("Got RdbStore successfully.") -}) -``` -## data_rdb.getRdbStore - -getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> - -Obtains an RDB store. This API 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. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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** - -```js -const STORE_CONFIG = { name: "RdbTest.db" } -let promise = data_rdb.getRdbStore(STORE_CONFIG, 1); -promise.then(async (rdbStore) => { - console.log("Got RdbStore successfully.") -}).catch((err) => { - console.log("Failed to get RdbStore, err: " + err) -}) -``` - - -## data_rdb.getRdbStore8+ - getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void -Obtains a relational database (RDB) store. This API 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. +Obtains an RDB store. This API 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. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -83,7 +29,7 @@ Obtains a relational database (RDB) store. This API uses an asynchronous callbac | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context8+ | Context | Yes| Context of the app or functionality.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| | 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.| @@ -101,11 +47,11 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { }) ``` -## data_rdb.getRdbStore8+ +## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> -Obtains an RDB store. This API 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. +Obtains an RDB store. This API 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. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -113,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context8+ | Context | Yes| Context of the app or functionality.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | version | number | Yes| RDB store version.| @@ -137,68 +83,16 @@ promise.then(async (rdbStore) => { ## data_rdb.deleteRdbStore -deleteRdbStore(name: string, callback: AsyncCallback<void>): void - -Deletes an RDB store. This API uses a callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the RDB store to delete.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** -```js -data_rdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { - if (err) { - console.info("Failed to delete RdbStore, err: " + err) - return - } - console.log("Deleted RdbStore successfully.") -}) -``` - ## data_rdb.deleteRdbStore - -deleteRdbStore(name: string): Promise<void> - -Deletes an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the RDB store to delete.| - -**Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** -```js -let promise = data_rdb.deleteRdbStore("RdbTest.db") -promise.then(()=>{ - console.log("Deleted RdbStore successfully.") -}).catch((err) => { - console.info("Failed to delete RdbStore, err: " + err) -}) -``` - -## data_rdb.deleteRdbStore8+ - deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void -Deletes an RDB store. This API uses a callback to return the result. +Deletes an RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context8+ | Context | Yes| Context of the app or functionality.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| | name | string | Yes| Name of the RDB store to delete.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| @@ -213,7 +107,7 @@ data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { }) ``` -## data_rdb.deleteRdbStore8+ +## data_rdb.deleteRdbStore deleteRdbStore(context: Context, name: string): Promise<void> @@ -224,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context8+ | Context | Yes| Context of the app or functionality.
For the definition of **Context** of API version 8, see [Context](js-apis-Context.md).
For the definition of **Context** of API version 9, see [Context](js-apis-ability-context.md).| +| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| | name | string | Yes| Name of the RDB store to delete.| **Return value** @@ -234,7 +128,7 @@ Deletes an RDB store. This API uses a promise to return the result. **Example** ```js -let promise = data_rdb.deleteRdbStore("RdbTest.db") +let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") promise.then(()=>{ console.log("Deleted RdbStore successfully.") }).catch((err) => { @@ -272,14 +166,14 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates -Specifies a remote device on the network during distributed database synchronization. +Connects to the specified remote devices on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| devices | Array<string> | Yes| ID of the remote device to specify.| +| devices | Array<string> | Yes| IDs of the remote devices in the same network.| **Return value** | Type| Description| @@ -317,7 +211,7 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -344,7 +238,7 @@ predicates.equalTo("NAME", "lisi") 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. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -468,7 +362,7 @@ predicates.equalTo("NAME", "Lisa") contains(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string containing the specified value. +Sets an **RdbPredicates** to match a string containing the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -495,7 +389,7 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that starts with the specified value. +Sets an **RdbPredicates** to match a string that starts with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -522,7 +416,7 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that ends with the specified value. +Sets an **RdbPredicates** to match a string that ends with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -549,7 +443,7 @@ predicates.endsWith("NAME", "se") isNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is null. +Sets an **RdbPredicates** to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -575,7 +469,7 @@ predicates.isNull("NAME") isNotNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is not null. +Sets an **RdbPredicates** to match the field whose value is not null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -601,7 +495,7 @@ predicates.isNotNull("NAME") like(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that is similar to the specified value. +Sets an **RdbPredicates** to match a string that is similar to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -628,7 +522,7 @@ predicates.like("NAME", "%os%") glob(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match the specified string. +Sets an **RdbPredicates** to match the specified string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -636,7 +530,7 @@ Sets the **RdbPredicates** to match the specified string. | 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.| +| 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| @@ -655,7 +549,7 @@ predicates.glob("NAME", "?h*g") 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. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -683,7 +577,7 @@ predicates.between("AGE", 10, 50) 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. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -710,7 +604,7 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -737,7 +631,7 @@ predicates.greaterThan("AGE", 18) lessThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -765,7 +659,7 @@ predicates.lessThan("AGE", 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. +Sets an **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 @@ -793,7 +687,7 @@ predicates.greaterThanOrEqualTo("AGE", 18) 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. +Sets an **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 @@ -821,7 +715,7 @@ predicates.lessThanOrEqualTo("AGE", 20) orderByAsc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in ascending order. +Sets an **RdbPredicates** to match the column with values sorted in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -848,7 +742,7 @@ predicates.orderByAsc("NAME") orderByDesc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in descending order. +Sets an **RdbPredicates** to match the column with values sorted in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -874,7 +768,7 @@ predicates.orderByDesc("AGE") distinct(): RdbPredicates -Sets the **RdbPredicates** to filter out duplicate records. +Sets an **RdbPredicates** to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -902,7 +796,7 @@ promise.then((resultSet) => { limitAs(value: number): RdbPredicates -Sets the **RdbPredicates** to specify the maximum number of records. +Sets an **RdbPredicates** to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -928,7 +822,7 @@ predicates.equalTo("NAME", "Rose").limitAs(3) offsetAs(rowOffset: number): RdbPredicates -Sets the **RdbPredicates** to specify the start position of the returned result. +Sets an **RdbPredicates** to specify the start position of the returned result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -954,7 +848,7 @@ predicates.equalTo("NAME", "Rose").offsetAs(3) groupBy(fields: Array<string>): RdbPredicates -Sets the **RdbPredicates** to group rows that have the same value into summary rows. +Sets an **RdbPredicates** to group rows that have the same value into summary rows. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -979,7 +873,7 @@ predicates.groupBy(["AGE", "NAME"]) indexedBy(field: string): RdbPredicates -Sets the **RdbPredicates** object to specify the index column. +Sets an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1006,7 +900,7 @@ predicates.indexedBy("SALARY_INDEX") 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. +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1034,7 +928,7 @@ predicates.in("AGE", [18, 20]) 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. +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1061,12 +955,14 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + ### insert insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void -Inserts a row of data into a table. This API uses a callback to return the result. +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1090,7 +986,7 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { console.info("Failed to insert data, err: " + err) return } - console.log("Insert first done: " + ret) + console.log("Inserted first row: " + ret) }) ``` @@ -1124,7 +1020,7 @@ const valueBucket = { } let promise = rdbStore.insert("EMPLOYEE", valueBucket) promise.then(async (ret) => { - console.log("Insert first done: " + ret) + console.log("Inserted first row: " + ret) }).catch((err) => { console.log("Failed to insert data, err: " + err) }) @@ -1135,7 +1031,7 @@ promise.then(async (ret) => { update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data in the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1143,8 +1039,8 @@ Updates data in the database based on the specified RdbPredicates object. This A | 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.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** ```js @@ -1170,7 +1066,7 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> -Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1178,7 +1074,7 @@ Updates data in the database based on the specified RdbPredicates object. This A | 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.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** | Type| Description| @@ -1209,14 +1105,14 @@ promise.then(async (ret) => { delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void -Deletes data from the database based on the specified RdbPredicates object. This API uses a callback to return the result. +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous 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.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** @@ -1228,7 +1124,7 @@ rdbStore.delete(predicates, function (err, rows) { console.info("Failed to delete data, err: " + err) return } - console.log("Delete rows: " + rows) + console.log("Deleted rows: " + rows) }) ``` @@ -1237,14 +1133,14 @@ rdbStore.delete(predicates, function (err, rows) { delete(rdbPredicates: RdbPredicates):Promise<number> -Deletes data from the database based on the specified RdbPredicates object. This API uses a promise to return the result. +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| **Return value** | Type| Description| @@ -1257,7 +1153,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.delete(predicates) promise.then((rows) => { - console.log("Delete rows: " + rows) + console.log("Deleted rows: " + rows) }).catch((err) => { console.info("Failed to delete data, err: " + err) }) @@ -1268,7 +1164,7 @@ promise.then((rows) => { query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the database based on specified conditions. This API uses a callback to return the result. +Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1285,7 +1181,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { if (err) { - console.info("Query failed, err: " + err) + console.info("Failed to query data, err: " + err) return } console.log("resultSet column names:" + resultSet.columnNames) @@ -1298,7 +1194,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in the database based on specified conditions. This API uses a promise to return the result. +Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1311,7 +1207,7 @@ Queries data in the database based on specified conditions. This API uses a prom **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.| +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** ```js @@ -1322,7 +1218,7 @@ Queries data in the database based on specified conditions. This API uses a prom console.log("resultSet column names:" + resultSet.columnNames) console.log("resultSet column count:" + resultSet.columnCount) }).catch((err) => { - console.info("Query failed, err: " + err) + console.info("Failed to query data, err: " + err) }) ``` @@ -1331,7 +1227,7 @@ Queries data in the database based on specified conditions. This API uses a prom querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result. +Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1339,14 +1235,14 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments 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** ```js rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { if (err) { - console.info("Query failed, err: " + err) + console.info("Failed to query data, err: " + err) return } console.log("resultSet column names:" + resultSet.columnNames) @@ -1367,12 +1263,12 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **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.| +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** ```js @@ -1381,7 +1277,7 @@ promise.then((resultSet) => { console.log("resultSet column names:" + resultSet.columnNames) console.log("resultSet column count:" + resultSet.columnCount) }).catch((err) => { - console.info("Query failed, err: " + err) + console.info("Failed to query data, err: " + err) }) ``` @@ -1390,7 +1286,7 @@ promise.then((resultSet) => { executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses a callback to return the result. +Runs the SQL statement that contains the specified parameters but does not return a value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1398,7 +1294,7 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** @@ -1406,10 +1302,10 @@ Runs the SQL statement that contains the specified parameters but does not retur 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)" rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { if (err) { - console.info("executeSql failed, err: " + err) + console.info("Failed to execute SQL, err: " + err) return } - console.info('create table done.') + console.info('Created table successfully.') }) ``` @@ -1426,7 +1322,7 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** | Type| Description| @@ -1438,9 +1334,9 @@ Runs the SQL statement that contains the specified parameters but does not retur 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 = rdbStore.executeSql(SQL_CREATE_TABLE) promise.then(() => { - console.info('create table done.') + console.info('Created table successfully.') }).catch((err) => { - console.info("ExecuteSql failed, err: " + err) + console.info("Failed to execute SQL, err: " + err) }) ``` @@ -1538,7 +1434,7 @@ try { setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void -Sets a list of distributed tables. This API uses a callback to return the result. +Sets a list of distributed tables. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1552,10 +1448,10 @@ Sets a list of distributed tables. This API uses a callback to return the result ```js rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { - console.info('setDistributedTables failed, err: ' + err) + console.info('Failed to set distributed tables, err: ' + err) return } - console.info('setDistributedTables successfully.') + console.info('Set distributed tables successfully.') }) ``` @@ -1582,9 +1478,9 @@ Sets a list of distributed tables. This API uses a promise to return the result. ```js let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) promise.then(() => { - console.info("setDistributedTables successfully.") + console.info("Set distributed tables successfully.") }).catch((err) => { - console.info("setDistributedTables failed, err: " + err) + console.info('Failed to set distributed tables, err: ' + err) }) ``` @@ -1592,7 +1488,7 @@ promise.then(() => { 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 API uses a callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the database of a remote device is queried. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1605,12 +1501,12 @@ Obtains the distributed table name for a remote device based on the local table **Example** ```js -rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { +rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { if (err) { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain DistributedTableName, err: ' + err) return } - console.info('obtainDistributedTableName successfully, tableName=.' + tableName) + console.info('Obtained DistributedTableName successfully, tableName=.' + tableName) }) ``` @@ -1619,7 +1515,7 @@ rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableNa 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 API uses a promise to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is used to query the RDB store of the remote device. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1636,11 +1532,11 @@ Obtains the distributed table name for a remote device based on the local table **Example** ```js -let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") +let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") promise.then((tableName) => { - console.info('obtainDistributedTableName successfully, tableName=' + tableName) + console.info('Obtained DistributedTableName successfully, tableName=' + tableName) }).catch((err) => { - console.info('obtainDistributedTableName failed, err: ' + err) + console.info('Failed to obtain DistributedTableName, err: ' + err) }) ``` @@ -1648,7 +1544,7 @@ promise.then((tableName) => { sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void -Synchronizes data between devices. This API uses a callback to return the result. +Synchronizes data between devices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1657,13 +1553,13 @@ Synchronizes data between devices. This API uses a callback to return the result | -------- | -------- | -------- | -------- | | 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. | +| 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 that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** ```js -let predicates = new rdb.RdbPredicates('EMPLOYEE') +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) -rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { +rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { if (err) { console.log('sync failed, err: ' + err) return @@ -1694,7 +1590,7 @@ Synchronizes data between devices. This API uses a promise to return the result. | 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. | +| 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 that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** ```js @@ -1745,7 +1641,7 @@ try { off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void -Deletes the specified observer of the RDB store. This API uses a callback to return the result. +Unregisters the specified observer of the RDB store. This API uses a callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1788,7 +1684,7 @@ Defines the data types allowed. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -| Name| Description| +| Type| Description| | -------- | -------- | | number | Number.| | string | String.| @@ -1797,13 +1693,13 @@ Defines the data types allowed. ## ValuesBucket -Defines a bucket to store key-value pairs. +Defines the types of the key and value in a KV pair. **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.| +| Key Type| Value Type| +| -------- | -------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | ## SyncMode8+ 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 613e793255ded14a1ae050bdf4504e402b52b941..3098499d48ca52b0251cfb9648cc032fc26e2652 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,12 +1,15 @@ # Result Set +A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data. + > **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. ## Usage -You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain the **resultSet** object. +You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain a **resultSet** object. ```js import dataRdb from '@ohos.data.rdb'; @@ -20,7 +23,7 @@ promise.then((resultSet) => { ## ResultSet -Provides methods to access the result set, which is obtained by querying the relational database (RDB) store. +Provides methods to access the result set, which is obtained by querying the RDB store. ### Attributes 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 6d2e4596a6a87b585dbb83e886a32eb5868a8125..01d064e9a3e12e2bda811a7de953cf15fea6efe7 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -3,9 +3,10 @@ Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. -> **NOTE**
+> **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import @@ -18,10 +19,10 @@ import data_storage from '@ohos.data.storage'; **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| +| Name | Type | Readable | Writable | Description | +| ---------------- | ------ | -------- | -------- | ----------------------------------------------------------- | +| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. It must be less than 80 bytes. | +| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. It must be less than 8192 bytes. | ## data_storage.getStorageSync @@ -33,25 +34,33 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | [Storage](#storage) | **Storage** instance used for data storage operations.| + +| Type | Description | +| ------------------- | ------------------------------------------------------ | +| [Storage](#storage) | **Storage** instance used for data storage operations. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - var path = '/data/storage/el2/database/test_storage' - let storage = data_storage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() - - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +let storage = data_storage.getStorageSync(path + '/mystore'); +storage.putSync('startup', 'auto'); +storage.flushSync(); +``` ## data_storage.getStorage @@ -63,25 +72,33 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<[Storage](#storage)> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | --------------------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - var path = '/data/storage/el2/database/test_storage' - data_storage.getStorage(path + '/mystore', function (err, storage) { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - storage.putSync('startup', 'auto') - storage.flushSync() - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +data_storage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Failed to get the storage. path: " + path + '/mystore'); + return; + } + storage.putSync('startup', 'auto'); + storage.flushSync(); +}) +``` ## data_storage.getStorage @@ -93,29 +110,37 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Storage](#storage)> | Promise used to return the result.| + +| Type | Description | +| ---------------------------------- | ---------------------------------- | +| Promise<[Storage](#storage)> | Promise used to return the result. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - var path = '/data/storage/el2/database/test_storage' - - let getPromise = data_storage.getStorage(path + '/mystore') - getPromise.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +let getPromise = data_storage.getStorage(path + '/mystore'); +getPromise.then((storage) => { + storage.putSync('startup', 'auto'); + storage.flushSync(); +}).catch((err) => { + console.info("Failed to get the storage. path: " + path + '/mystore'); +}) +``` ## data_storage.deleteStorageSync @@ -127,14 +152,25 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Example** - ```js - data_storage.deleteStorageSync(path + '/mystore') - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +data_storage.deleteStorageSync(path + '/mystore'); +``` ## data_storage.deleteStorage @@ -146,21 +182,32 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - data_storage.deleteStorage(path + '/mystore', function (err) { - if (err) { - console.info("Deleted failed with err: " + err) - return - } - console.info("Deleted successfully.") - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +data_storage.deleteStorage(path + '/mystore', function (err) { + if (err) { + console.info("Failed to delete the storage with err: " + err); + return; + } + console.info("Succeeded in deleting the storage."); +}) +``` ## data_storage.deleteStorage @@ -172,24 +219,35 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promisedelSt = data_storage.deleteStorage(path + '/mystore') - promisedelSt.then(() => { - console.info("Deleted successfully.") - }).catch((err) => { - console.info("Deleted failed with err: " + err) - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +let promisedelSt = data_storage.deleteStorage(path + '/mystore'); +promisedelSt.then(() => { + console.info("Succeeded in deleting the storage."); +}).catch((err) => { + console.info("Failed to delete the storage with err: " + err); +}) +``` ## data_storage.removeStorageFromCacheSync @@ -201,14 +259,25 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Example** - ```js - data_storage.removeStorageFromCacheSync(path + '/mystore') - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +data_storage.removeStorageFromCacheSync(path + '/mystore'); +``` ## data_storage.removeStorageFromCache @@ -220,21 +289,32 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - data_storage.removeStorageFromCache(path + '/mystore', function (err) { - if (err) { - console.info("Removed storage from cache failed with err: " + err) - return - } - console.info("Removed storage from cache successfully.") - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +data_storage.removeStorageFromCache(path + '/mystore', function (err) { + if (err) { + console.info("Failed to remove storage from cache with err: " + err); + return; + } + console.info("Succeeded in removing storage from cache."); +}) +``` ## data_storage.removeStorageFromCache @@ -246,24 +326,36 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') - promiserevSt.then(() => { - console.info("Removed storage from cache successfully.") - }).catch((err) => { - console.info("Removed storage from cache failed with err: " + err) - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromise====================>"); +}); + +let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') +promiserevSt.then(() => { + console.info("Succeeded in removing storage from cache."); +}).catch((err) => { + console.info("Failed to remove storage from cache with err: " + err); +}) +``` ## Storage @@ -280,21 +372,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.| + +| Type | Description | +| --------- | ------------------------------------------------------------ | +| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned. | **Example** - ```js - let value = storage.getSync('startup', 'default') - console.info("The value of startup is " + value) - ``` + +```js +let value = storage.getSync('startup', 'default'); +console.info("The value of startup is " + value); +``` ### get @@ -306,22 +401,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<ValueType> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------ | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | +| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. | **Example** - ```js - storage.get('startup', 'default', function(err, value) { - if (err) { - console.info("Get the value of startup failed with err: " + err) - return + +```js +storage.get('startup', 'default', function(err, value) { + if (err) { + console.info("Failed to get the value of startup with err: " + err); + return; } - console.info("The value of startup is " + value) - }) - ``` + console.info("The value of startup is " + value); +}) +``` ### get @@ -334,25 +431,26 @@ Obtains the value corresponding to a key. If the value is null or not in the def **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| + +| Type | Description | +| ------------------------ | ---------------------------------- | +| Promise<ValueType> | Promise used to return the result. | **Example** - ```js - let promiseget = storage.get('startup', 'default') - promiseget.then((value) => { - console.info("The value of startup is " + value) - }).catch((err) => { - console.info("Get the value of startup failed with err: " + err) - }) - ``` +```js +let promiseget = storage.get('startup', 'default'); +promiseget.then((value) => { + console.info("The value of startup is " + value) +}).catch((err) => { + console.info("Failed to get the value of startup with err: " + err); +}) +``` ### putSync @@ -364,15 +462,17 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | **Example** - ```js - storage.putSync('startup', 'auto') - ``` + +```js +storage.putSync('startup', 'auto') +``` ### put @@ -384,22 +484,24 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.put('startup', 'auto', function (err) { - if (err) { - console.info("Put the value of startup failed with err: " + err) - return - } - console.info("Put the value of startup successfully.") - }) - ``` + +```js +storage.put('startup', 'auto', function (err) { + if (err) { + console.info("Failed to put the value of startup with err: " + err); + return; + } + console.info("Succeeded in putting the value of startup."); +}) +``` ### put @@ -411,25 +513,27 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseput = storage.put('startup', 'auto') - promiseput.then(() => { - console.info("Put the value of startup successfully.") - }).catch((err) => { - console.info("Put the value of startup failed with err: " + err) - }) - ``` +```js +let promiseput = storage.put('startup', 'auto'); +promiseput.then(() => { + console.info("Succeeded in putting the value of startup."); +}).catch((err) => { + console.info("Failed to put the value of startup with err: " + err); +}) +``` ### hasSync @@ -441,22 +545,25 @@ Checks whether the storage object contains data with a given key. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | **Example** - ```js - let isExist = storage.hasSync('startup') - if (isExist) { - console.info("The key of startup is contained.") - } - ``` + +```js +let isExist = storage.hasSync('startup'); +if (isExist) { + console.info("The key of startup is contained."); +} +``` ### has @@ -468,28 +575,31 @@ Checks whether the storage object contains data with a given key. This API uses **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | --------------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | **Example** - ```js - storage.has('startup', function (err, isExist) { - if (err) { - console.info("Check the key of startup failed with err: " + err) - return - } - if (isExist) { - console.info("The key of startup is contained.") - } - }) - ``` + +```js +storage.has('startup', function (err, isExist) { + if (err) { + console.info("Failed to check the key of startup with err: " + err); + return; + } + if (isExist) { + console.info("The key of startup is contained."); + } +}) +``` ### has @@ -501,26 +611,29 @@ Checks whether the storage object contains data with a given key. This API uses **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result.| + +| Type | Description | +| ---------------------- | ---------------------------------- | +| Promise<boolean> | Promise used to return the result. | **Example** - ```js - let promisehas = storage.has('startup') - promisehas.then((isExist) => { - if (isExist) { - console.info("The key of startup is contained.") - } - }).catch((err) => { - console.info("Check the key of startup failed with err: " + err) - }) - ``` + +```js +let promisehas = storage.has('startup') +promisehas.then((isExist) => { + if (isExist) { + console.info("The key of startup is contained."); + } +}).catch((err) => { + console.info("Failed to check the key of startup with err: " + err); +}) +``` ### deleteSync @@ -532,14 +645,16 @@ Deletes data with the specified key from this storage object. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Example** - ```js - storage.deleteSync('startup') - ``` + +```js +storage.deleteSync('startup') +``` ### delete @@ -551,21 +666,23 @@ Deletes data with the specified key from this storage object. This API uses an a **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.delete('startup', function (err) { - if (err) { - console.info("Delete startup key failed with err: " + err) - return - } - console.info("Deleted startup key successfully.") - }) - ``` + +```js +storage.delete('startup', function (err) { + if (err) { + console.info("Failed to delete startup key failed err: " + err); + return; + } + console.info("Succeeded in deleting startup key."); +}) +``` ### delete @@ -577,24 +694,27 @@ Deletes data with the specified key from this storage object. This API uses a pr **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ---------------- | +| key | string | Yes | Key of the data. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promisedel = storage.delete('startup') - promisedel.then(() => { - console.info("Deleted startup key successfully.") - }).catch((err) => { - console.info("Delete startup key failed with err: " + err) - }) - ``` + +```js +let promisedel = storage.delete('startup') +promisedel.then(() => { + console.info("Succeeded in deleting startup key."); +}).catch((err) => { + console.info("Failed to delete startup key failed err: " + err); +}) +``` ### flushSync @@ -606,9 +726,10 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Example** - ```js - storage.flushSync() - ``` + +```js +storage.flushSync() +``` ### flush @@ -620,20 +741,22 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.flush(function (err) { - if (err) { - console.info("Flush to file failed with err: " + err) - return - } - console.info("Flushed to file successfully.") - }) - ``` + +```js +storage.flush(function (err) { + if (err) { + console.info("Failed to flush to file with err: " + err); + return; + } + console.info("Succeeded in flushing to file."); +}) +``` ### flush @@ -645,19 +768,21 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseflush = storage.flush() - promiseflush.then(() => { - console.info("Flushed to file successfully.") - }).catch((err) => { - console.info("Flush to file failed with err: " + err) - }) - ``` + +```js +let promiseflush = storage.flush(); +promiseflush.then(() => { + console.info("Succeeded in flushing to file."); +}).catch((err) => { + console.info("Failed to flush to file with err: " + err); +}) +``` ### clearSync @@ -669,9 +794,10 @@ Clears this **Storage** object. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Example** - ```js - storage.clearSync() - ``` + +```js +storage.clearSync() +``` ### clear @@ -683,20 +809,22 @@ Clears this **Storage** object. This API uses an asynchronous callback to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.clear(function (err) { - if (err) { - console.info("Clear to file failed with err: " + err) - return - } - console.info("Cleared to file successfully.") - }) - ``` + +```js +storage.clear(function (err) { + if (err) { + console.info("Failed to clear the storage with err: " + err); + return; + } + console.info("Succeeded in clearing the storage."); +}) +``` ### clear @@ -708,19 +836,21 @@ Clears this **Storage** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseclear = storage.clear() - promiseclear.then(() => { - console.info("Cleared to file successfully.") - }).catch((err) => { - console.info("Clear to file failed with err: " + err) - }) - ``` + +```js +let promiseclear = storage.clear(); +promiseclear.then(() => { + console.info("Succeeded in clearing the storage."); +}).catch((err) => { + console.info("Failed to clear the storage with err: " + err); +}) +``` ### on('change') @@ -732,20 +862,22 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes.| + +| Name | Type | Description | +| -------- | --------------------------------------------------- | ------------------------------------------------------------ | +| type | string | Event type. The value **change** indicates data change events. | +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** - ```js - var observer = function (key) { - console.info("The key of " + key + " changed.") - } - storage.on('change', observer) - storage.putSync('startup', 'auto') - storage.flushSync() // observer will be called. - ``` + +```js +var observer = function (key) { + console.info("The key of " + key + " changed."); +} +storage.on('change', observer); +storage.putSync('startup', 'auto'); +storage.flushSync(); // observer will be called. +``` ### off('change') @@ -757,27 +889,29 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes.| + +| Name | Type | Description | +| -------- | --------------------------------------------------- | ------------------------------------------------------------ | +| type | string | Event type. The value **change** indicates data change events. | +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** - ```js - var observer = function (key) { - console.info("The key of " + key + " changed.") - } - storage.off('change', observer) - ``` + +```js +var observer = function (key) { + console.info("The key of " + key + " changed."); +} +storage.off('change', observer); +``` ## StorageObserver **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | No| Data changed.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------- | +| key | string | No | Data changed. | ## ValueType @@ -785,8 +919,8 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name | Description | -| ------- | -------------------- | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type.| +| Type | Description | +| ------- | ----------------------------- | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | \ No newline at end of file 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 93ab553ef10e531fea0b2d0871b65183d22bf6fa..8c27495f208ad620ed6e104fb19c958350805c1e 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,11 +1,22 @@ # Device Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **DeviceManager** module provides APIs for distributed device management. + +System applications can call the APIs to do the following: + +- Subscribe to or unsubscribe from device state changes. +- Discover peripheral untrusted devices. +- Authenticate or deauthenticate a device. +- Query the trusted device list. +- Query local device information, including the device name, type, and ID. + +> **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'; @@ -21,10 +32,10 @@ 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.| + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------------------------------------ | + | bundleName | string | Yes | Bundle name of an application. | + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| - Example ``` @@ -34,10 +45,40 @@ Creates a **DeviceManager** instance. return; } console.info("createDeviceManager success"); - this.dmInstance = data; + let dmInstance = data; }); ``` +## DeviceInfo + +Defines device information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ---------------------- | ------------------------- | ---- | -------- | +| deviceId | string | Yes | Unique identifier of a device.| +| deviceName | string | Yes | Device name. | +| deviceType | [DeviceType](#devicetype) | Yes | Device type. | +| networkId8+ | string | Yes | Network ID of the device. | + + +## 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.| + ## DeviceStateChangeAction @@ -45,42 +86,103 @@ Enumerates the device states. **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.| +| 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. | +## SubscribeInfo -## DeviceType +Defines subscription information. -Enumerates the device types. +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| ------------- | --------------------------------- | ---- | ----------------- | +| subscribeId | number | Yes | Subscription ID, used to identify a device discovery period.| +| mode | [DiscoverMode ](#discovermode) | No | Device discovery mode. | +| medium | [ExchangeMedium](#exchangemedium) | No | Medium used for device discovery. | +| freq | [ExchangeFreq](#exchangefreq) | No | Frequency of device discovery. | +| isSameAccount | boolean | No | Whether the same account is used on the discovered device. | +| isWakeRemote | boolean | No | Whether to wake up the discovered device. | +| capability | [SubscribeCap](#subscribecap) | No | Discovery capability. | + + +## DiscoverMode + +Enumerates the device discovery modes. **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.| +| Name | Default Value | Description | +| --------------------- | ---- | ----- | +| DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.| +| DISCOVER_MODE_ACTIVE | 0xAA | Active discovery.| -## DeviceInfo +## ExchangeMedium -Defines device information. +Enumerates the media used for device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| deviceId | number | Yes| Unique device identifier.| -| deviceName | string | Yes| Device name.| -| deviceType | number | Yes| Device type.| +| Name | Default Value | Description | +| ---- | ---- | --------- | +| AUTO | 0 | Automatic. | +| BLE | 1 | Bluetooth. | +| COAP | 2 | Wi-Fi.| +| USB | 3 | USB. | + +## ExchangeFreq + +Enumerates the device discovery frequencies. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ---------- | ---- | ----- | +| LOW | 0 | Low frequency. | +| MID | 1 | Medium frequency. | +| HIGH | 2 | High frequency. | +| SUPER_HIGH | 3 | Ultra-high frequency.| + + +## SubscribeCap + +Enumerates the discovery capabilities. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Default Value | Description | +| ------------------------- | ---- | -------------- | +| SUBSCRIBE_CAPABILITY_DDMP | 0 | DDMP capability. This will be deprecated later.| +| SUBSCRIBE_CAPABILITY_OSD | 1 | OSD capability. | + + +## AuthParam + +Defines the authentication parameters. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| extraInfo | {[key:string] : any} | No | Extended field.| + +## AuthInfo + +Defines authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name | Type | Mandatory | Description | +| --------- | -------------------- | ---- | ---------- | +| authType | number | Yes | Authentication type. | +| token | number | Yes | Authentication token. | +| extraInfo | {[key:string] : any} | No | Extended field.| ## DeviceManager @@ -92,12 +194,12 @@ Provides APIs to obtain information about trusted devices and local devices. Bef release(): void -Releases the **DeviceManager** instance that is no longer used. +Releases this **DeviceManager** instance when it is no longer used. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Example - ``` + ```js dmInstance.release(); ``` @@ -111,16 +213,258 @@ Obtains all trusted devices synchronously. **System capability**: SystemCapability.DistributedHardware.DeviceManager - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | -------------------------------------- | --------- | | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| - Example - ``` + ```js var deviceInfoList = dmInstance.getTrustedDeviceListSync(); ``` +### getTrustedDeviceList8+ + +getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): void + +Obtains all trusted devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------- | + | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList((err, data) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + console.log('get trusted device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getTrustedDeviceList8+ + +getTrustedDeviceList(): Promise<Array<DeviceInfo>> + +Obtains all trusted devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + +- Example + ```js + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + }); + ``` + +### getLocalDeviceInfoSync8+ + +getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) + +Obtains local device information synchronously. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Name | Description | + | -------------------------------------- | --------- | + | Array<[DeviceInfo](#deviceinfo)> | List of local devices obtained.| + +- Example + ```js + var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + ``` + + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void + +Obtains local device information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------- | + | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo((err, data) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + console.log('get local device info: ' + JSON.stringify(data)); + } + ); + ``` + +### getLocalDeviceInfo8+ + +getLocalDeviceInfo(): Promise<DeviceInfo> + +Obtains local device information. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + +- Example + ```js + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + }); + ``` + +### startDeviceDiscovery + +startDeviceDiscovery(subscribeInfo: SubscribeInfo): void + +Starts to discover peripheral devices. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + +- Example + ```js + // Automatically generate a unique subscription ID. + var subscribeId = Math.floor(Math.random() * 10000 + 1000); + var subscribeInfo = { + "subscribeId": subscribeId, + "mode": 0xAA, // Active discovery + "medium": 0, // Automatic. Multiple media can be used for device discovery. + "freq": 2, // High frequency + "isSameAccount": false, + "isWakeRemote": false, + "capability": 1 + }; + dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + ``` + +### stopDeviceDiscovery + +stopDeviceDiscovery(subscribeId: number): void + +Stops device discovery. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ----------- | ------ | ---- | ----- | + | subscribeId | number | Yes | Subscription ID.| + +- Example + ```js + // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. + dmInstance.stopDeviceDiscovery(subscribeId); + ``` + +### authenticateDevice + +authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void + +Authenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | + | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | + | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + +- Example + ```js + // Information about the device to authenticate. The information can be obtained from the device discovery result. + var deviceInfo ={ + "deviceId": "XXXXXXXX", + "deviceName": "", + deviceType: 0x0E + }; + let authParam = { + "authType": 1, // Authentication type. The value 1 means no account PIN authentication. + "extraInfo": {} + } + dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { + if (err) { + console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); + token = data.pinToken; + }); + ``` + +### unAuthenticateDevice8+ + +unAuthenticateDevice(deviceInfo: DeviceInfo): void + +Deauthenticates a device. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | ---------- | ------------------------- | ---- | ----- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + +- Example + ```js + dmInstance.unAuthenticateDevice(deviceInfo); + ``` + + +### verifyAuthInfo + +verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void + +Verifies authentication information. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------- | + | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | + | authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + +- Example + ```js + let authInfo = { + "authType": 1, + "token": xxxxxx, + "extraInfo": {} + } + dmInstance.verifyAuthInfo(authInfo, (err, data) => { + if (err) { + console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); + return; + } + console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + }); + ``` + + ### on('deviceStateChange') on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -130,13 +474,13 @@ Subscribes to changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager - **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.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state. | - Example - ``` + ```js dmInstance.on('deviceStateChange', (data) => { console.info("deviceStateChange on:" + JSON.stringify(data)); } @@ -146,20 +490,20 @@ Subscribes to changes in the device state. ### off('deviceStateChange') -off(type: 'deviceStateChange', callback?: Call back<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void +off(type: 'deviceStateChange', callback?: Callback<{ 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.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| - Example - ``` + ```js dmInstance.off('deviceStateChange', (data) => { console.info('deviceStateChange' + JSON.stringify(data)); } @@ -167,6 +511,95 @@ Unsubscribes from changes in the device state. ``` +### on('deviceFound') + +on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Subscribes to device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| + | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | + +- Example + ```js + dmInstance.on('deviceFound', (data) => { + console.info("deviceFound:" + JSON.stringify(data)); + } + ); + ``` + +### off('deviceFound') + +off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: DeviceInfo }>): void + +Unsubscribes from device discovery events. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used for device discovery, which is invoked to return the device information and state.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + +### on('discoverFail') + +on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: number }>): void + +Subscribes to device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | + +- Example + ```js + dmInstance.on('discoverFail', (data) => { + this.log("discoverFail on:" + JSON.stringify(data)); + } + ); + ``` + +### off('discoverFail') + +off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: number }>): void + +Unsubscribes from device discovery failures. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + +- Example + ```js + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + } + ); + ``` + + ### on('serviceDie') on(type: 'serviceDie', callback: () => void): void @@ -176,13 +609,13 @@ 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.| + | 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 - ``` + ```js dmInstance.on("serviceDie", () => { console.info("serviceDie on"); } @@ -199,13 +632,13 @@ 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.| + | 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 - ``` + ```js 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 934bcc66d070f4f2a484944d7427d38039332f33..2b292bc1771bf37f1dcc738cafec5ef837d04d7c 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,6 +1,24 @@ # Device Usage Statistics -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +This module provides APIs for collecting statistics on device usage. + +System applications can call these APIs to implement the following features: + +- Query the usage duration in different time segments, events (foreground, background, start and end of continuous tasks), and the number of notifications, on a per application basis. +- Query statistics about system events (sleep, wakeup, unlock, and screen lock). +- Query the bundle group information of applications, including the invoking application itself. +- Query the idle status of applications, including the invoking application itself. +- Set the bundle group for other applications. +- Register and deregister the callback for application group changes. + +Third-party applications can call these APIs to implement the following features: + +- Query the idle status of the invoking application itself. +- Query the bundle group information of the invoking application itself. +- Query the events of the invoking application itself. + +> **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. @@ -14,16 +32,16 @@ import bundleState from '@ohos.bundleState' isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void -Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. +Checks whether the application specified by **bundleName** is in the idle state. This API uses an asynchronous callback to return the result. A third-party application can only check the idle status of itself. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns whether the application specified by **bundleName** is in the idle state if the value of **bundleName** is valid; returns **null** otherwise.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the value of bundleName is valid, null will be returned.| **Example** @@ -41,28 +59,28 @@ Checks whether the application specified by **bundleName** is in the idle state. isIdleState(bundleName: string): Promise<boolean> -Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. +Checks whether the application specified by **bundleName** is in the idle state. This API uses a promise to return the result. A third-party application can only check the idle status of itself. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | Yes | Bundle name of an application.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. Returns whether the application specified by **bundleName** is in the idle state if the value of **bundleName** is valid; returns **null** otherwise.| +| Type | Description | +| ---------------------- | ---------------------------------------- | +| Promise<boolean> | Promise used to return the result. If the value of **bundleName** is valid, **null** will be returned.| **Example** ``` - bundleState.isIdleState("com.ohos.camera").then( res => { + bundleState.isIdleState("com.ohos.camera").then(res => { console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); }); ``` @@ -71,15 +89,16 @@ Checks whether the application specified by **bundleName** is in the idle state. queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void -Queries the priority group of the current invoker application. This API uses an asynchronous callback to return the result. +Queries the priority group of this application. This API usesan asynchronous callback to return the result. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | -------------- | + +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| **Example** @@ -97,26 +116,25 @@ Queries the priority group of the current invoker application. This API uses an queryAppUsagePriorityGroup(): Promise<number> -Queries the priority group of the current invoker application. This API uses a promise to return the result. +Queries the priority group of this application. This API uses a promise to return the result. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the result.| +| Type | Description | +| --------------- | --------------------------- | +| Promise<number> | Promise used to return the result.| **Example** ``` - bundleState.queryAppUsagePriorityGroup().then( res => { + bundleState.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); ``` - ## bundleState.queryBundleStateInfos queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<BundleActiveInfoResponse>): void @@ -127,13 +145,15 @@ Queries the application usage duration statistics based on the specified start t **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| - | callback | AsyncCallback<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Yes | Callback used to return the result.| **Example** @@ -144,7 +164,7 @@ Queries the application usage duration statistics based on the specified start t } else { console.log('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); let i = 1; - for(let key in res){ + for (let key in res) { console.log('BUNDLE_ACTIVE queryBundleStateInfos callback number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStateInfos callback result ' + JSON.stringify(res[key])); i++; @@ -163,31 +183,33 @@ Queries the application usage duration statistics based on the specified start t **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | -------------------------------------- | +| Promise<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | Promise used to return the result.| **Example** ``` - bundleState.queryBundleStateInfos(0, 20000000000000).then( res => { + bundleState.queryBundleStateInfos(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); let i = 1; - for(let key in res){ + for (let key in res) { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); i++; } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); }); ``` @@ -202,14 +224,16 @@ Queries the application usage duration statistics in the specified time frame at **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | byInterval | [IntervalType](#intervaltype) | Yes| Interval type.| - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| - | callback | AsyncCallback<Array<[BundleStateInfo](#bundlestateinfo)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried. | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleStateInfo](#bundlestateinfo)>> | Yes | Callback used to return the result.| **Example** @@ -237,30 +261,32 @@ Queries the application usage duration statistics in the specified time frame at **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | byInterval | [IntervalType](#intervaltype) | Yes| Interval type.| - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------- | ---- | ----- | +| byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried.| +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result.| **Example** ``` - bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { + bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); }); ``` @@ -275,13 +301,15 @@ Queries events of all applications based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| - | callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| **Example** @@ -309,29 +337,31 @@ Queries events of all applications based on the specified start time and end tim **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | -------------------------------------- | +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| **Example** ``` - bundleState.queryBundleActiveStates(0, 20000000000000).then( res => { + bundleState.queryBundleActiveStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); }); ``` @@ -346,11 +376,11 @@ Queries events of this application based on the specified start time and end tim **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| - | callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes| Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| begin | number | Yes | Start time. | +| end | number | Yes | End time. | +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| **Example** @@ -363,7 +393,7 @@ Queries events of this application based on the specified start time and end tim 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])); - } + } } }); ``` @@ -378,50 +408,51 @@ Queries events of this application based on the specified start time and end tim **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | begin | number | Yes| Start time.| - | end | number | Yes| End time.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| begin | number | Yes | Start time.| +| end | number | Yes | End time.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | -------------------------------------- | +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| **Example** ``` - bundleState.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { + bundleState.queryCurrentBundleActiveStates(0, 20000000000000).then(res => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); } - }).catch( err => { + }).catch(err => { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); }); ``` ## BundleStateInfo -Provides the usage duration information of an application. + +Provides the usage duration information of applications. ### Attributes **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| abilityPrevAccessTime | number | Yes| Last time when the application was used.| -| abilityInFgTotalTime | number | Yes| Total time that the application runs in the foreground.| -| id | number | No| User ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| abilityPrevSeenTime | number | No| Last time when the application was visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| abilitySeenTotalTime | number | No| Total time when the application is visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| fgAbilityAccessTotalTime | number | No| Total time that the application accesses the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| fgAbilityPrevAccessTime | number | No| Last time when the application accessed the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| infosBeginTime | number | No| Time logged in the first application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| infosEndTime | number | No| Time logged in the last application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| Name | Type | Mandatory | Description | +| ------------------------ | ------ | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| abilityPrevAccessTime | number | Yes | Last time when the application was used. | +| abilityInFgTotalTime | number | Yes | Total time that the application runs in the foreground. | +| id | number | No | User ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| abilityPrevSeenTime | number | No | Last time when the application was visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| abilitySeenTotalTime | number | No | Total time that the application is visible in the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| fgAbilityAccessTotalTime | number | No | Total time that the application accesses the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| fgAbilityPrevAccessTime | number | No | Last time when the application accessed the foreground.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| ### merge @@ -429,15 +460,13 @@ merge(toMerge: BundleStateInfo): void Merges the application usage information that has the same bundle name. -This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. - **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | toMerge | [BundleStateInfo](#bundlestateinfo) | Yes| Application usage information to merge.| +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | -------------- | +| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes | Application usage information to merge.| ## BundleActiveState @@ -445,14 +474,14 @@ Provides information about an application event. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| stateType | number | Yes| Application event type.| -| stateOccurredTime | number | Yes| Timestamp when the application event occurs.| -| appUsagePriorityGroup | number | No| Usage priority group of the application.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| indexOfLink | string | No| Shortcut ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| -| nameOfClass | string | No| Class name.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| Name | Type | Mandatory | Description | +| --------------------- | ------ | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| stateType | number | Yes | Application event type. | +| stateOccurredTime | number | Yes | Timestamp when the application event occurs. | +| appUsagePriorityGroup | number | No | Usage priority group of the application.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| indexOfLink | string | No | Shortcut ID.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| +| nameOfClass | string | No | Class name.
This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.| ## BundleActiveInfoResponse @@ -460,9 +489,10 @@ Provides the usage duration information of applications. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| [key: string]: BundleStateInfo | [key: string]: [BundleStateInfo](#bundlestateinfo) | Yes| Usage duration information by application.| +| Name | Type | Mandatory | Description | +| ------------------------------ | ---------------------------------------- | ---- | -------------- | +| [key: string]: BundleStateInfo | [key: string]: [BundleStateInfo](#bundlestateinfo) | Yes | Usage duration information by application.| + ## IntervalType @@ -470,10 +500,10 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -|Name |Default Value |Description| -| -------- | -------- | -------- | -| BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| -| BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis.| -| BY_WEEKLY | 2 | The system obtains the application usage duration statistics in the specified time frame on a weekly basis.| -| BY_MONTHLY | 3 | The system obtains the application usage duration statistics in the specified time frame on a monthly basis.| -| BY_ANNUALLY | 4 | The system obtains the application usage duration statistics in the specified time frame on an annual basis.| +| Name | Default Value | Description | +| ------------ | ---- | ---------------------------------------- | +| BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| +| BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis. | +| BY_WEEKLY | 2 | The system obtains the application usage duration statistics in the specified time frame on a weekly basis. | +| BY_MONTHLY | 3 | The system obtains the application usage duration statistics in the specified time frame on a monthly basis. | +| BY_ANNUALLY | 4 | The system obtains the application usage duration statistics in the specified time frame on an annual basis. | diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index ffbc73ff530a4d8f9ec39fd6e824760df9448644..aed3f0dfd30e05810bf103c4b04738ae4fe237f9 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,5 +1,5 @@ # Display -Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. +The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** > @@ -14,11 +14,11 @@ import display from '@ohos.display'; ## DisplayState -Provides the state of a display. +Enumerates the display states. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATE_UNKNOWN | 0 | Unknown.| | STATE_OFF | 1 | The display is shut down.| @@ -35,163 +35,169 @@ Describes the attributes of a display. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| ID of the display.| -| name | string | Yes| No| Name of the display.| -| alive | boolean | Yes| No| Whether the display is alive.| -| state | [DisplayState](#displaystate) | Yes| No| State of the display.| -| refreshRate | number | Yes| No| Refresh rate of the display.| -| rotation | number | Yes| No| Screen rotation angle of the display.| -| width | number | Yes| No| Width of the display, in pixels.| -| height | number | Yes| No| Height of the display, in pixels.| -| densityDPI | number | Yes| No| Screen density of the display, in DPI.| -| densityPixels | number | Yes| No| Screen density of the display, in pixels.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| -| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| -| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| +| Name | Type | Readable | Writable | Description | +| ------------- | ----------------------------- | -------- | -------- | ------------------------------------------------------------ | +| id | number | Yes | No | ID of the display. | +| name | string | Yes | No | Name of the display. | +| alive | boolean | Yes | No | Whether the display is alive. | +| state | [DisplayState](#displaystate) | Yes | No | State of the display. | +| refreshRate | number | Yes | No | Refresh rate of the display. | +| rotation | number | Yes | No | Screen rotation angle of the display. | +| width | number | Yes | No | Width of the display, in pixels. | +| height | number | Yes | No | Height of the display, in pixels. | +| densityDPI | number | Yes | No | Screen density of the display, in DPI. | +| densityPixels | number | Yes | No | Screen density of the display, in pixels. | +| scaledDensity | number | Yes | No | Scaling factor for fonts displayed on the display. | +| xDPI | number | Yes | No | Exact physical dots per inch of the screen in the horizontal direction. | +| yDPI | number | Yes | No | Exact physical dots per inch of the screen in the vertical direction. | ## display.getDefaultDisplay getDefaultDisplay(callback: AsyncCallback<Display>): void -Obtains the default display object. +Obtains the default display object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| **Example** - ```js - var displayClass = null; - display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; - }); - ``` + +```js +var displayClass = null; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; +}); +``` ## display.getDefaultDisplay getDefaultDisplay(): Promise<Display> -Obtains the default display object. +Obtains the default display object. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** - | Type | Description | - | ---------------------------------- | ---------------------------------------------- | - | Promise<[Display](#display)> | Promise used to return the default display object.| +| Type | Description | +| ---------------------------------- | ---------------------------------------------- | +| Promise<[Display](#display)> | Promise used to return the default display object.| **Example** - ```js - let promise = display.getDefaultDisplay(); - promise.then(() => { - console.log('getDefaultDisplay success'); - }).catch((err) => { - console.log('getDefaultDisplay fail: ' + JSON.stringify(err)); - }); - ``` +```js +var displayClass = null; +let promise = display.getDefaultDisplay(); +promise.then((data) => { + displayClass = data; + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +}); +``` ## display.getAllDisplay getAllDisplay(callback: AsyncCallback<Array<Display>>): void -Obtains all the display objects. +Obtains all display objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ---------------------------------------------------- | ---- | ------------------------------- | - | callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| **Example** - ```js - display.getAllDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)) - }); - ``` +```js +display.getAllDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}); +``` ## display.getAllDisplay getAllDisplay(): Promise<Array<Display>> -Obtains all the display objects. +Obtains all display objects. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** - | Type | Description | - | ----------------------------------------------- | ------------------------------------------------------- | - | Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------- | +| Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| **Example** - ```js - let promise = display.getAllDisplay(); - promise.then(() => { - console.log('getAllDisplay success'); - }).catch((err) => { - console.log('getAllDisplay fail: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = display.getAllDisplay(); +promise.then((data) => { + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); +}); +``` ## display.on('add'|'remove'|'change') on(type: 'add'|'remove'|'change', callback: Callback<number>): void -Enables listening. +Subscribes to display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| - | callback | Callback<number> | Yes| Callback used to return the ID of the display.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** - ```js - var callback = (data) => { - console.info('Listening enabled. Data: ' + JSON.stringify(data)) - } - display.on("add", callback); - ``` +```js +var callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)) +} +display.on("add", callback); + ``` ## display.off('add'|'remove'|'change') off(type: 'add'|'remove'|'change', callback?: Callback<number>): void -Disables listening. +Unsubscribes from display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Listening type. The available values are as follows:
- **add**: listening for whether a display is added
- **remove**: listening for whether a display is removed
- **change**: listening for whether a display is changed| - | callback | Callback<number> | No| Callback used to return the ID of the display.| + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** - ```js - display.off("remove"); - ``` +```js +display.off("remove"); +``` 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 73f6216d255c4629399dfbf9510ab59b176f0273..bc64da83d9a829da97b02be79a94804df498a670 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,6 +1,8 @@ # Distributed Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. + +> ![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,17 +13,14 @@ import account_distributedAccount from '@ohos.account.distributedAccount'; ``` -## System Capability - -SystemCapability.Account.OsAccount - - ## account_distributedAccount.getDistributedAccountAbility getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. +**System capability**: SystemCapability.Account.OsAccount + - Return value | Type| Description| | -------- | -------- | @@ -40,7 +39,9 @@ Provides methods for querying and updating the login state of a distributed acco queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void -Obtains distributed account information. This method uses an asynchronous callback to return the result. +Obtains distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) @@ -63,7 +64,9 @@ Obtains distributed account information. This method uses an asynchronous callba queryOsAccountDistributedInfo(): Promise<DistributedInfo> -Obtains distributed account information. This method uses a promise to return the result asynchronously. +Obtains distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) @@ -87,7 +90,9 @@ Obtains distributed account information. This method uses a promise to return th updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void -Updates distributed account information. This method uses an asynchronous callback to return the result. +Updates distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) @@ -110,7 +115,9 @@ Updates distributed account information. This method uses an asynchronous callba updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -Updates distributed account information. This method uses a promise to return the result asynchronously. +Updates distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) @@ -140,6 +147,7 @@ Updates distributed account information. This method uses a promise to return th Defines distributed OS account information. +**System capability**: SystemCapability.Account.OsAccount | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | 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 24571aaf04fe72804e5060a3a39e62ce3b794f7d..ea7bbf851ebfd2e6ab6bcd321b5258286a9c97e9 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -1,6 +1,15 @@ # Distributed Data Management -Distributed data management provides collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to the distributed database and perform operations such as adding, deleting, modifying, and querying data in the distributed database. +The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. + +This module provides the following functions: + +- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. +- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. +- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates. +- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. +- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. +- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. >**NOTE**
> @@ -18,7 +27,7 @@ import distributedData from '@ohos.data.distributedData'; createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void -Creates a **KVManager** object to manage key-value (KV) stores. This API uses an asynchronous callback to return the result. +Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -26,8 +35,8 @@ Creates a **KVManager** object to manage key-value (KV) stores. This API uses an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| 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.| +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| +| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** ```js @@ -57,7 +66,7 @@ try { createKVManager(config: KVManagerConfig): Promise<KVManager> -Creates a **KVManager** object to manage KV stores. This API uses a promise to return the result. +Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -65,13 +74,13 @@ Creates a **KVManager** object to manage KV stores. This API uses a promise to r | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| +| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** object created.| +| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| **Example** @@ -121,11 +130,11 @@ Defines user information. ## UserType -Defines the user type. +Enumerates the user types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name| Default Value| Description| +| Name| Value| Description| | ----- | ------ | ------ | | SAME_USER_ID | 0 | User who logs in to different devices using the same account.| @@ -198,7 +207,7 @@ Creates and obtains a KV store. This API uses a promise to return the result. | Type | Description | | -------------------------------------- | ------------------------ | -| Promise<T> <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| +| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| **Example** @@ -241,7 +250,7 @@ Closes a KV store. This API uses an asynchronous callback to return the result. | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -261,7 +270,7 @@ const options = { kvManager.getKVStore('storeId', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { + kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { console.log('closeKVStore success'); }); }); @@ -291,7 +300,7 @@ Closes a KV store. This API uses a promise to return the result. | Type | Description | | ------------- | -------------- | -| Promise\ | Promise used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned.| +| Promise\ | Promise that returns no value.| **Example** @@ -311,7 +320,7 @@ const options = { kvManager.getKVStore('storeId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { + kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { console.log('closeKVStore success'); }).catch((err) => { console.log('closeKVStore err ' + JSON.stringify(err)); @@ -339,7 +348,7 @@ Deletes a KV store. This API uses an asynchronous callback to return the result. | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -359,7 +368,7 @@ try { kvManager.getKVStore('store', options, async function (err, store) { console.log('getKVStore success'); kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + kvManager.deleteKVStore('appId', 'storeId', function (err, data) { console.log('deleteKVStore success'); }); }); @@ -388,7 +397,7 @@ Deletes a KV store. This API uses a promise to return the result. | Type | Description | | ------------- | -------------- | -| Promise<void> | Promise used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +| Promise<void> | Promise that returns no value.| **Example** @@ -408,7 +417,7 @@ try { kvManager.getKVStore('storeId', options).then(async (store) => { console.log('getKVStore success'); kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId').then(() => { + kvManager.deleteKVStore('appId', 'storeId').then(() => { console.log('deleteKVStore success'); }).catch((err) => { console.log('deleteKVStore err ' + JSON.stringify(err)); @@ -426,7 +435,7 @@ try { getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void -Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvstore) and have not been deleted using [deleteKVStore](#deletekvstore8). This API uses an asynchronous callback to return the result. +Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -435,7 +444,7 @@ Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvs | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<void> | Yes |Callback used to return the KV store IDs obtained. | +| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. | **Example** @@ -456,7 +465,7 @@ try { getAllKVStoreId(appId: string): Promise<string[]> -Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvstore) and have not been deleted using [deleteKVStore](#deletekvstore8). This API uses a promise to return the result. +Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -479,7 +488,7 @@ Obtains the IDs of all the KV stores that are created using [getKVStore](#getkvs let kvManager; try { console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('apppId').then((data) => { + kvManager.getAllKVStoreId('appId').then((data) => { console.log('getAllKVStoreId success'); console.log('size = ' + data.length); }).catch((err) => { @@ -495,7 +504,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to the **distributedDataServiceDie** events. This API uses a synchronous callback to return the result. +Subscribes to service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -503,8 +512,8 @@ Subscribes to the **distributedDataServiceDie** events. This API uses a synchron | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Name of the event to subscribe to. The value is **distributedDataServiceDie**, which indicates the service status change event.| -| deathCallback | Callback<void> | Yes | Callback invoked when the distributed data service is dead. | +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.| +| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| **Example** @@ -527,7 +536,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from the **distributedDataServiceDie** events. This API uses a synchronous callback to return the result. +Unsubscribes from the service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -535,8 +544,8 @@ Unsubscribes from the **distributedDataServiceDie** events. This API uses a sync | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Name of the event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates the service status change event.| -| deathCallback | Callback<void> | No | Callback used to return the **distributedDataServiceDie** events. | +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.| +| deathCallback | Callback<void> | No | Callback used to return service status changes.| **Example** @@ -559,45 +568,44 @@ try { Provides KV store configuration. -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created. | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted. | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up. | -| autoSync | boolean | No|Whether to automatically synchronize database files. By default, database files are not automatically synchronized.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | -| 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. | -| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.| +| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | +| 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.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| ## KVStoreType -Defines the KV store types. +Enumerates the KV store types. -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| ## SecurityLevel -Defines the KV store security levels. +Enumerates the KV store security levels. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | | NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public. | -| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. | -| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. | -| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. | -| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. | +| S0 | 1 | The KV store security level is public.| +| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| +| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| +| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| +| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| ## Constants @@ -606,18 +614,18 @@ Defines the KV store constants. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value| Description | +| Name | Value| Description | | --- | ---- | ----------------------- | -| MAX_KEY_LENGTH | 1024 | Maximum length (in bytes) of a key in the KV store. | -| MAX_VALUE_LENGTH | 4194303 | Maximum length (in bytes) of a value in the KV store. | -| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of the device coordinate key, in bytes.| -| MAX_STORE_ID_LENGTH | 128 | Maximum length (in bytes) of a KV store ID. | +| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | +| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. | +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.| +| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | | MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| | MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| ## Schema8+ ## -Defines the schema of a KV store. When creating or opening a KV store, you can create a **Schema** object and put it in [Options](#options). +Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -646,7 +654,7 @@ Represents a **Schema** instance, which provides the methods for defining the va | --- | ---- | ----------------------- | | nullable8+ | boolean | Whether the database field can be null. | | default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value to store.| +| type8+ | number | Value of the data type corresponding to the specified node.| ### constructor8+ ### @@ -694,7 +702,7 @@ try { node.appendChild(child1); node.appendChild(child2); node.appendChild(child3); - console.log("appendNode " + node.toJson()); + console.log("appendNode " + JSON.stringify(node)); child1 = null; child2 = null; child3 = null; @@ -707,14 +715,16 @@ try { ## KvStoreResultSet8+ ## -Provides methods to obtain the KV store result set and query or move the data read position. Before calling any method in **KvStoreResultSet**, you must use **KvStore** to create a **KvStore** instance. +Provides methods to obtain the KV store result sets, and query and move the data read position. + +Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. ### getCount8+ ### getCount(): number -Obtains the number of rows in the result set. +Obtains the total number of rows in the result set. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -722,7 +732,7 @@ Obtains the number of rows in the result set. | Type | Description | | ------ | -------------- | -| number |Number of rows obtained. | +| number |Total number of rows obtained. | **Example** @@ -764,7 +774,7 @@ let kvStore; try { let resultSet; kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeeed.'); + console.log('getResultSet succeeded.'); resultSet = result; }).catch((err) => { console.log('getResultSet failed:' + err); @@ -781,7 +791,7 @@ try { moveToFirst(): boolean -Moves the data read position to the first row. +Moves the data read position to the first row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -815,7 +825,7 @@ try { moveToLast(): boolean -Moves the data read position to the last row. +Moves the data read position to the last row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -849,7 +859,7 @@ try { moveToNext(): boolean -Moves the data read position to the next row. +Moves the data read position to the next row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -883,7 +893,7 @@ try { moveToPrevious(): boolean -Moves the data read position to the previous row. +Moves the data read position to the previous row. If the result set is empty, **false** will be returned. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1072,7 +1082,7 @@ Checks whether the data read position is before the first row. | Type | Description | | ------ | -------------- | -| boolean |Returns **true** if the read position is before the first row; returns **false** otherwise. | +| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. | **Example** @@ -1132,7 +1142,7 @@ try { getEntry(): Entry -Obtains a KV pair. +Obtains the KV pair from the current position. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1181,7 +1191,7 @@ A constructor used to create a **Schema** instance. reset(): Query -Resets the **Query** object that contains common query options. +Resets the **Query** object. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1212,7 +1222,7 @@ try { equalTo(field: string, value: number|string|boolean): Query -Creates a **Query** object to match the specified field whose value is equal to the specified value. +Creates a **Query** object to match the specified field whose value is equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1227,7 +1237,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object reset.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1238,7 +1248,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1273,7 +1283,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1297,7 +1307,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1308,7 +1318,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1332,7 +1342,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1343,7 +1353,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1367,7 +1377,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1378,7 +1388,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1402,7 +1412,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1413,7 +1423,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1424,7 +1434,6 @@ isNull(field: string): Query Creates a **Query** object to match the specified field whose value is **null**. - **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -1437,7 +1446,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1448,7 +1457,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1473,7 +1482,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1484,7 +1493,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1508,7 +1517,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1519,7 +1528,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1543,7 +1552,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1554,7 +1563,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1578,7 +1587,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1589,7 +1598,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1606,14 +1615,14 @@ Creates a **Query** object to match the specified field whose value is similar t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes Field to match. It cannot contain '^'. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | | value | string | Yes | String specified.| **Return value** | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1624,7 +1633,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1648,7 +1657,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1659,7 +1668,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1689,7 +1698,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1719,7 +1728,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1742,7 +1751,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1754,7 +1763,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1777,7 +1786,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1789,7 +1798,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1813,19 +1822,21 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** ```js +let total = 10; +let offset = 1; try { let query = new distributedData.Query(); query.notEqualTo("field", "value"); - query.limit("total", "offset"); + query.limit(total, offset); console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1834,7 +1845,7 @@ try { isNotNull(field: string): Query -Creates a **Query** object with a specified field that is not null. +Creates a **Query** object to match the specified field whose value is not **null**. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1842,13 +1853,13 @@ Creates a **Query** object with a specified field that is not null. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field specified. | +| fieId | string | Yes |Field to match. It cannot contain '^'. | **Return value** | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1859,7 +1870,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1876,7 +1887,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1889,7 +1900,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1906,7 +1917,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1919,7 +1930,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1942,7 +1953,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1954,7 +1965,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -1977,7 +1988,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1989,7 +2000,7 @@ try { console.log("query is " + query.getSqlLike()); query = null; } catch (e) { - console.log("dumplicated calls should be ok :" + e); + console.log("duplicated calls should be ok :" + e); } ``` @@ -2013,7 +2024,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object Created.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2050,14 +2061,16 @@ try { let sql1 = query.getSqlLike(); console.log("GetSqlLike sql=" + sql1); } catch (e) { - console.log("dumplicated calls should be ok : " + e); + console.log("duplicated calls should be ok : " + e); } ``` ## KVStore -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. +Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. + +Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. ### put @@ -2114,7 +2127,7 @@ Adds a KV pair of the specified type to this KV store. This API uses a promise t | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2133,7 +2146,6 @@ try { } ``` - ### delete delete(key: string, callback: AsyncCallback<void>): void @@ -2175,7 +2187,6 @@ try { } ``` - ### delete delete(key: string): Promise<void> @@ -2194,7 +2205,7 @@ Deletes a KV pair from this KV store. This API uses a promise to return the resu | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2217,13 +2228,11 @@ try { console.log("An unexpected error occurred. Error:" + e); } ``` - - ### on('dataChange') on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data change notifications of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2231,9 +2240,9 @@ Subscribes to data changes of the specified type. This API uses a synchronous ca | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **dataChange**, which indicates the data change event. | +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| **Example** @@ -2249,7 +2258,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to data synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2257,8 +2266,8 @@ Subscribes to data synchronization completion events. This API uses a synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | **Example** @@ -2273,7 +2282,7 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', observer?: Callback<ChangeNotification>): void -Unsubscribes from data change events. This API uses a synchronous callback to return the result. +Unsubscribes from data change notifications. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2281,8 +2290,8 @@ Unsubscribes from data change events. This API uses a synchronous callback to re | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **dataChange**, which indicates the data change event. | -| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | +| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| **Example** @@ -2332,14 +2341,14 @@ try { 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) { + kvStore.getEntries('batch_test_string_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { - console.log('PutBatch e ' + e); + console.log('PutBatch e ' + JSON.stringify(e)); } ``` @@ -2362,7 +2371,7 @@ Inserts KV pairs in batches to this KV store. This API uses a promise to return | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2384,7 +2393,7 @@ try { 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) => { + kvStore.getEntries('batch_test_string_key').then((entries) => { console.log('getEntries success'); console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { @@ -2394,7 +2403,7 @@ try { console.log('putBatch fail ' + JSON.stringify(err)); }); }catch(e) { - console.log('PutBatch e ' + e); + console.log('PutBatch e ' + JSON.stringify(e)); } ``` @@ -2436,7 +2445,7 @@ try { 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) { + kvStore.deleteBatch(keys, async function (err,data) { console.log('deleteBatch success'); }); }); @@ -2464,7 +2473,7 @@ Deletes KV pairs in batches from this KV store. This API uses a promise to retur | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2488,7 +2497,7 @@ try { console.log('entries: ' + JSON.stringify(entries)); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.deleteBatch(keys).then((err) => { + kvStore.deleteBatch(keys).then((err) => { console.log('deleteBatch success'); }).catch((err) => { console.log('deleteBatch fail ' + JSON.stringify(err)); @@ -2544,7 +2553,7 @@ try { 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) { + kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); }); }); @@ -2566,7 +2575,7 @@ Starts the transaction in this KV store. This API uses a promise to return the r | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2633,7 +2642,7 @@ Commits the transaction in this KV store. This API uses a promise to return the | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2695,7 +2704,7 @@ Rolls back the transaction in this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2717,7 +2726,7 @@ try { enableSync(enabled: boolean, callback: AsyncCallback<void>): void -Sets data synchronization, which can be enabled or disable. This API uses an asynchronous callback to return the result. +Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2750,7 +2759,7 @@ try { enableSync(enabled: boolean): Promise<void> -Enables or disables data synchronization. This API uses a promise to return the result. +Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2764,7 +2773,7 @@ Enables or disables data synchronization. This API uses a promise to return the | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2834,7 +2843,7 @@ Sets the data synchronization range. This API uses a promise to return the resul | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2856,11 +2865,11 @@ try { ## SubscribeType -Defines the subscription type. +Enumerates the subscription types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----- | ------ | ----------------------- | | SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | | SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | @@ -2893,7 +2902,7 @@ Defines the KV pairs stored in the KV store. ## Value -Defines the value in a KV pair. +Defines the **value** object in a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2904,13 +2913,11 @@ Defines the value in a KV pair. ## ValueType -Enumerates the types of values in KV pairs. - -These value types can be used only by internal applications. +Enumerates the data types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----- | ------ | ----------------------- | | STRING |0 |String. | | INTEGER |1 |Integer. | @@ -2919,16 +2926,19 @@ These value types can be used only by internal applications. | BOOLEAN |4 |Boolean. | | DOUBLE |5 |Double (double-precision floating point). | - ## SingleKVStore -Provides methods to query and synchronize data in a single KV store. This class inherits from **KVStore**. Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** object. +Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). + +Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. + +Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. ### get get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void -Obtains the value of a specified key. This API uses an asynchronous callback to return the result. +Obtains the value of the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2937,7 +2947,7 @@ Obtains the value of a specified key. This API uses an asynchronous callback to | 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 invoked to return the value obtained. | **Example** @@ -2966,7 +2976,7 @@ try { get(key: string): Promise<Uint8Array | string | boolean | number> -Obtains the value of a specified key. This API uses a promise to return the result. +Obtains the value of the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3009,7 +3019,7 @@ try { getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. +Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3018,7 +3028,7 @@ Obtains the KV pairs that match the specified key prefix. This API uses an async | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | **Example** @@ -3039,10 +3049,10 @@ try { } kvStore.putBatch(entries, async function (err,data) { console.log('putBatch success'); - await kvStore.getEntries('batch_test_number_key', function (err,entrys) { + kvStore.getEntries('batch_test_number_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { @@ -3055,7 +3065,7 @@ try { getEntries(keyPrefix: string): Promise<Entry[]> -Obtains the KV pairs that match the specified key prefix. This API uses a promise to return the result. +Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3091,12 +3101,12 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { + kvStore.getEntries('batch_test_string_key').then((entries) => { 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); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); + console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); + console.log('entries[0].value.value: ' + entries[0].value.value); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); @@ -3121,7 +3131,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses an | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | +| query |[Query](#query8) | Yes |Key prefix to match. | | callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** @@ -3147,10 +3157,10 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query, function (err,entrys) { + kvStore.getEntries(query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); console.log('GetEntries success'); @@ -3183,6 +3193,7 @@ Obtains the KV pairs that match the specified **Query** object. This API uses a **Example** ```js +let kvStore; try { var arr = new Uint8Array([21,31]); let entries = []; @@ -3202,7 +3213,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -3221,7 +3232,7 @@ try { getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the result set with the specified key prefix from this single KV store. This API uses an asynchronous callback to return the result. +Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3230,7 +3241,7 @@ Obtains the result set with the specified key prefix from this single KV store. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match.| -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the result set obtained.| +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.| **Example** @@ -3252,7 +3263,7 @@ try { } kvStore.putBatch(entries, async function (err, data) { console.log('GetResultSet putBatch success'); - await kvStore.getResultSet('batch_test_string_key', async function (err, result) { + kvStore.getResultSet('batch_test_string_key', async function (err, result) { console.log('GetResultSet getResultSet succeed.'); resultSet = result; kvStore.closeResultSet(resultSet, function (err, data) { @@ -3270,7 +3281,7 @@ try { getResultSet(keyPrefix: string): Promise<KvStoreResultSet> -Obtains the result set with the specified key prefix from this single KV store. This API uses a promise to return the result. +Obtains the result set with the specified prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3330,7 +3341,7 @@ try { getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3339,7 +3350,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |Query | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback used to return the **KvStoreResultSet** object obtained.| +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** @@ -3363,7 +3374,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSet(query, async function (err, result) { + kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; }); @@ -3378,7 +3389,7 @@ try { getResultSet(query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3482,7 +3493,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet]( | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3514,7 +3525,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -3537,7 +3548,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSize(query, async function (err, resultSize) { + kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -3627,12 +3638,12 @@ 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) { + 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) { + kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } @@ -3662,7 +3673,7 @@ Deletes data of a device. This API uses a promise to return the result. | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3697,7 +3708,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3705,8 +3716,8 @@ Subscribes to the synchronization completion events. This API uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the synchronization result. | **Example** @@ -3733,7 +3744,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This API uses a synchronous callback to return the result. +Unsubscribes from the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3741,7 +3752,7 @@ Unsubscribes from the synchronization completion events. This API uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **syncComplete**, which indicates the synchronization complete event. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | | syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | **Example** @@ -3764,7 +3775,7 @@ try { sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -3774,8 +3785,8 @@ Manually triggers KV store synchronization synchronously. For details about the | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |IDs of the devices to be synchronized. These devices must be in the same networking environment. | -| mode |[SyncMode](#syncmode) | Yes |Data synchronization mode. | +| deviceIdList |string[] | Yes |IDs of the devices to be synchronized. These devices must be in the same networking environment. | +| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -3834,7 +3845,7 @@ Sets the default delay allowed for KV store synchronization. This API uses a pro | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -3865,7 +3876,7 @@ Obtains the security level of this KV store. This API uses an asynchronous callb | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback used to return the security level obtained. | +| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. | **Example** @@ -3876,7 +3887,7 @@ try { console.log('getSecurityLevel success'); }); }catch(e) { - console.log('GetSecurityLeve e ' + e); + console.log('GetSecurityLevel e ' + e); } ``` @@ -3893,7 +3904,7 @@ Obtains the security level of this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the value obtained.| +|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| **Example** @@ -3906,20 +3917,26 @@ try { console.log('getSecurityLevel fail ' + JSON.stringify(err)); }); }catch(e) { - console.log('GetSecurityLeve e ' + e); + console.log('GetSecurityLevel e ' + e); } ``` ## DeviceKVStore8+ ## -Provides methods to manage distributed data by device in the distributed system. This class inherits from **KVStore** and provides data query and synchronization methods. Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. +Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). + +Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. + +For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. + +Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. ### get8+ ### get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void -Obtains the string value that matches the specified key for a device. This API uses an asynchronous callback to return the result. +Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -3954,7 +3971,7 @@ try{ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> -Obtains the string value that matches the specified key for a device. This API uses a promise to return the result. +Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -3969,7 +3986,7 @@ Obtains the string value that matches the specified key for a device. This API u | Type | Description | | ------ | ------- | -|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the value obtained.| +|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| **Example** @@ -3998,7 +4015,7 @@ try { getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified key prefix for a device. This API uses an asynchronous callback to return the result. +Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4030,10 +4047,10 @@ try { 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) { + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); }catch(e) { @@ -4046,7 +4063,7 @@ try { getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> -Obtains the KV pairs that match the specified key prefix for a device. This API uses a promise to return the result. +Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4083,12 +4100,12 @@ try { console.log('entries: ' + entries); kvStore.putBatch(entries).then(async (err) => { console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { 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); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); + console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); + console.log('entries[0].value.value: ' + entries[0].value.value); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); }); @@ -4137,14 +4154,13 @@ try { 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) { + kvStore.getEntries(query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }); }); console.log('GetEntries success'); @@ -4197,7 +4213,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { + kvStore.getEntries(query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -4216,7 +4232,7 @@ try { getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void -Obtains the KV pairs that match the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4226,7 +4242,7 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | **Example** @@ -4249,14 +4265,13 @@ try { 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) { + kvStore.getEntries('localDeviceId', query, function (err,entries) { console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entries.length: ' + entries.length); + console.log('entries[0]: ' + JSON.stringify(entries[0])); }) }); console.log('GetEntries success'); @@ -4270,7 +4285,7 @@ try { getEntries(deviceId: string, query: Query): Promise<Entry[]> -Obtains the KV pairs that match the specified **Query** object for a device. This API uses a promise to return the result. +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4311,7 +4326,7 @@ try { var query = new distributedData.Query(); query.deviceId('localDeviceId'); query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query).then((entrys) => { + kvStore.getEntries('localDeviceId', query).then((entries) => { console.log('getEntries success'); }).catch((err) => { console.log('getEntries fail ' + JSON.stringify(err)); @@ -4330,7 +4345,7 @@ try { getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4340,7 +4355,7 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4351,7 +4366,7 @@ try { kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4365,7 +4380,7 @@ try { getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified key prefix for a device. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4409,7 +4424,7 @@ try { getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4418,7 +4433,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4443,10 +4458,10 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - await kvStore.getResultSet(query, async function (err, result) { + kvStore.getResultSet(query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4461,7 +4476,7 @@ try { getResultSet(query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4525,7 +4540,7 @@ try { getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void -Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4535,7 +4550,7 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback used to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -4559,10 +4574,10 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSet('localDeviceId', query, async function (err, result) { + kvStore.getResultSet('localDeviceId', query, async function (err, result) { console.log('getResultSet succeed.'); resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log('closeResultSet success'); }) }); @@ -4577,7 +4592,7 @@ try { getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> -Obtains the **KvStoreResultSet** object that matches the specified **Query** object for a device. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4692,7 +4707,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet]( | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -4725,7 +4740,7 @@ Obtains the number of results that matches the specified **Query** object. This | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -4749,7 +4764,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - await kvStore.getResultSize(query, async function (err, resultSize) { + kvStore.getResultSize(query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -4819,7 +4834,7 @@ try { getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; -Obtains the number of results that matches the specified **Query** object for a device. This API uses an asynchronous callback to return the result. +Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4829,7 +4844,7 @@ Obtains the number of results that matches the specified **Query** object for a | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback used to return the number of results obtained. | +| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | **Example** @@ -4852,7 +4867,7 @@ try { console.log('putBatch success'); const query = new distributedData.Query(); query.prefixKey("batch_test"); - await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { console.log('getResultSet succeed.'); }); }); @@ -4866,7 +4881,7 @@ try { getResultSize(deviceId: string, query: Query): Promise<number> -Obtains the number of results that matches the specified **Query** object for a device. This API uses a promise to return the result. +Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4922,7 +4937,7 @@ try { removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void -Removes data of a device from this KV store. This API uses an asynchronous callback to return the result. +Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4943,12 +4958,12 @@ 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) { + 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) { + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { console.log('RemoveDeviceData get success'); }); } @@ -4964,7 +4979,7 @@ try { removeDeviceData(deviceId: string): Promise<void> -Removes data of a device from this KV store. This API uses a promise to return the result. +Deletes data of the specified device from this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -4978,7 +4993,7 @@ Removes data of a device from this KV store. This API uses a promise to return t | Type | Description | | ------ | ------- | -|Promise<void> |Promise used to return the result.| +|Promise<void> |Promise that returns no value.| **Example** @@ -5013,7 +5028,7 @@ try { sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void -Manually triggers KV store synchronization synchronously. For details about the synchronization mode of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5052,7 +5067,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the synchronization completion events. This API uses a synchronous callback to return the result. +Subscribes to the data synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5060,12 +5075,13 @@ Subscribes to the synchronization completion events. This API uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to subscribe to. The value is **syncComplete**, which indicates the synchronization complete event.| +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.| | syncCallback |Callback | Yes |Callback used to return the synchronization result. | **Example** ```js +let kvStore; const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; const VALUE_TEST_FLOAT_ELEMENT = 321.12; try { @@ -5087,7 +5103,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This API uses a synchronous callback to return the result. +Unsubscribes from the synchronization complete events. This API uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5095,7 +5111,7 @@ Unsubscribes from the synchronization completion events. This API uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Name of the event to unsubscribe from. The value is **syncComplete**, which indicates the synchronization complete event.| +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| | syncCallback |Callback ![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 APIs of this module will be deprecated and are not recommended for use. An exception will be thrown if any of the APIs is called. +> **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 APIs of this module will be deprecated and are not recommended for use. An exception will be thrown if any of the APIs is called. ## Modules to Import @@ -12,120 +12,128 @@ import document from '@ohos.document'; ## document.choose -choose(type:string[]): Promise<string> +choose(types? : string[]): Promise<string> -Chooses a file of the specified type using the file manager. This method uses a promise to return the result. +Chooses files of the specified types using the file manager. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ---------------------------- | - | type | string[] | No | Type of the file to choose.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| types | string[] | No | Types of the files to choose. | -- Return value +**Return value** - | Type | Description | - | --------------------- | -------------- | - | Promise<string> | Promise used to return the result. An error code is returned.| +| Type | Description | +| --------------------- | -------------- | +| Promise<string> | Promise used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(type); + let types = []; + document.choose(types); ``` ## document.choose choose(callback:AsyncCallback<string>): void -Chooses a file using the file manager. This method uses an asynchronous callback to return the result. +Chooses a file using the file manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(function(err, uri) { + let uri = ""; + document.choose(function(err, uri) { // Do something with the URI. }); ``` ## document.choose -choose(type:string[], callback:AsyncCallback<string>): void +choose(types:string[], callback:AsyncCallback<string>): void -Chooses a file of the specified type using the file manager. This method uses an asynchronous callback to return the result. +Chooses files using the file manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | type | string[] | No | Type of the file to choose.| - | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| types | string[] | No | Types of the files to choose.| +| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.choose(type, function(err, uri) { + let types = []; + let uri = ""; + document.choose(types, function(err, uri) { // Do something with the URI. }); ``` ## document.show -show(url:string, type:string):Promise<number> +show(uri:string, type:string):Promise<void> -Opens a file. This method uses a promise to return the result. +Opens a file. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name| Type | Mandatory| Description | - | ---- | ------ | ---- | ---------------------------- | - | uri | string | Yes | URI of the file to open.| - | type | string | Yes | Type of the file to open.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ---------------------------- | +| uri | string | Yes | URI of the file to open.| +| type | string | Yes | Type of the file to open.| -- Return value +**Return value** - | Type | Description | - | --------------------- | ------------ | - | Promise<void> | Promise used to return the result. An error code is returned.| +| Type | Description | +| --------------------- | ------------ | +| Promise<void> | Promise used to return the result. An error code is returned.| -- Example +**Example** ```js - await document.show(uri, type); + let type = ""; + let uri = ""; + document.show(uri, type); ``` ## document.show -show(url:string, type:string, callback:AsyncCallback<void>): void +show(uri:string, type:string, callback:AsyncCallback<void>): void -Opens a file. This method uses an asynchronous callback to return the result. +Opens a file. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.FileManagement.File.FileIO +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | ---------------------------- | - | uri | string | Yes | URI of the file to open.| - | type | string | Yes | Type of the file to open.| - | callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| uri | string | Yes | URI of the file to open.| +| type | string | Yes | Type of the file to open.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | -- Example +**Example** ```js - await document.show(uri, type, function(err) { + let type = ""; + let uri = ""; + document.show(uri, type, function(err) { //do something }); ``` diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-environment.md index 942e514367c923db4d7aa270218e39ae82f65aa0..d023cdc8403d028ff250d3ea7afa82858d6ad5b8 100644 --- a/en/application-dev/reference/apis/js-apis-environment.md +++ b/en/application-dev/reference/apis/js-apis-environment.md @@ -1,12 +1,12 @@ # Environment +This module provides JS APIs for obtaining the root directories of the storage and public files. + > **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. -This module provides JS APIs for obtaining the root directories of the storage and public files. - ## Modules to Import ```js diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 821407ada202109ab3b17e560402621ac5ae8356..cf862c2d57454b742fb42208e011efcce06029dc 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -138,10 +138,10 @@ Starts an ability. This API uses a callback to return the execution result when **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.startAbilityForResult( - { + { want: { action: "action.system.home", @@ -154,6 +154,9 @@ featureAbility.startAbilityForResult( uri:"" }, }, + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } ) ``` @@ -180,7 +183,7 @@ Starts an ability. This API uses a promise to return the execution result when t **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.startAbilityForResult( { @@ -284,7 +287,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant' featureAbility.terminateSelfWithResult( { @@ -335,7 +338,7 @@ Checks whether the main window of this ability has the focus. This API uses a ca **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus() ``` @@ -358,7 +361,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus().then((data) => { console.info("==========================>hasWindowFocus=======================>"); }); @@ -383,7 +386,7 @@ Obtains the **Want** object sent from this ability. This API uses a callback to **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant() ``` @@ -406,7 +409,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant().then((data) => { console.info("==========================>getWantCallBack=======================>"); }); @@ -429,7 +432,7 @@ Obtains the application context. **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() context.getBundleName() ``` @@ -453,7 +456,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf() ``` @@ -476,7 +479,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** ```javascript -import featureAbility from '@ohos.ability.featureability'; +import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelfCallBack=======================>"); }); ``` @@ -926,6 +929,8 @@ Enumerates operation types of the Data ability. | 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. | +| extensionAbilityType9+ | Read-only | bundle.ExtensionAbilityType | No | Type of the Extension ability. | +| extensionAbilityName9+ | Read-only | string | No | Description of the Extension ability name in the **Want** object. | ## flags diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index c0b25d75f2f3ffa14970cd8c752c81c379c8cfe0..4d3791fd26788b92c136c32df7f298787f887f3d 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,9 +1,10 @@ # File Management +The fileio module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. + > **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. -Provides file storage and management capabilities, including basic file management, file directory management, file information statistics, and stream read and write. ## Modules to Import @@ -15,21 +16,38 @@ import fileio from '@ohos.fileio'; ## Guidelines Before using the APIs provided by this module to perform operations on files or directories, obtain the path of the application sandbox as follows: + +Stage Model + + ```js +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let path = context.filesDir; + } +} + ``` + + For details about how to obtain the stage model context, see [Stage Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-ability-context.md#abilitycontext). + +FA Model + ```js import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); - let path = ''; context.getFilesDir().then((data) => { - path = data; + let path = data; }) -``` - + ``` + + For details about how to obtain the context of the FA model, see [FA Model](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-Context.md#context). ## fileio.stat stat(path: string): Promise<Stat> -Obtains file information. This API uses a promise to return the result asynchronously. +Obtains file information. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -46,11 +64,12 @@ Obtains file information. This API uses a promise to return the result asynchron | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| **Example** + ```js fileio.stat(path).then(function(stat){ - console.info("Got file info successfully:"+ JSON.stringify(stat)); + console.info("Got file info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("getFileInfo failed with error:"+ err); + console.info("Failed to get file info. Error:"+ err); }); ``` @@ -64,12 +83,14 @@ Obtains file information. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ------------------------------ | | path | string | Yes | Application sandbox path of the file. | | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** + ```js fileio.stat(path, function (err, stat) { // Example code in Stat @@ -86,17 +107,20 @@ Synchronously obtains file information. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | File information obtained.| **Example** + ```js let stat = fileio.statSync(path); // Example code in Stat @@ -107,26 +131,29 @@ Synchronously obtains file information. opendir(path: string): Promise<Dir> -Opens a file directory. This API uses a promise to return the result asynchronously. +Opens a file directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------ | | path | string | Yes | Application sandbox path of the directory to open.| **Return value** + | Type | Description | | -------------------------- | -------- | | Promise<[Dir](#dir)> | Promise used to return the **Dir** object.| **Example** + ```js fileio.opendir(path).then(function(dir){ - console.info("Opened directory successfully:"+ JSON.stringify(dir)); + console.info("Directory opened:"+ JSON.stringify(dir)); }).catch(function(err){ - console.info("opendir failed with error:"+ err); + console.info("Failed to open the directory. Error:"+ err); }); ``` @@ -147,6 +174,7 @@ Opens a file directory. This API uses an asynchronous callback to return the res | callback | AsyncCallback<[Dir](#dir)> | Yes | Callback invoked when the directory is open asynchronously. | **Example** + ```js fileio.opendir(path, function (err, dir) { // Example code in Dir struct @@ -171,11 +199,13 @@ Synchronously opens a directory. | path | string | Yes | Application sandbox path of the directory to open.| **Return value** + | Type | Description | | ----------- | -------- | | [Dir](#dir) | A **Dir** instance corresponding to the directory.| **Example** + ```js let dir = fileio.opendirSync(path); // Example code in Dir struct @@ -187,7 +217,7 @@ Synchronously opens a directory. access(path: string, mode?: number): Promise<void> -Checks whether the current process can access a file. This API uses a promise to return the result asynchronously. +Checks whether the current process can access a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -199,16 +229,18 @@ Checks whether the current process can access a file. This API uses a promise to | 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 | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.access(path).then(function() { - console.info("access succeed"); + console.info("Access successful"); }).catch(function(err){ - console.info("access failed with error:"+ err); + console.info("Access failed. Error:"+ err); }); ``` @@ -222,6 +254,7 @@ Checks whether the current process can access a file. This API uses an asynchron **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | @@ -229,6 +262,7 @@ Checks whether the current process can access a file. This API uses an asynchron | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously checked. | **Example** + ```js fileio.access(path, function (err) { // Do something. @@ -245,17 +279,19 @@ 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 | Application sandbox path of the 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 try { fileio.accessSync(path); } catch(err) { - console.info("accessSync failed with error:"+ err); + console.info("accessSync failed. Error:"+ err); } ``` @@ -264,27 +300,30 @@ Synchronously checks whether the current process can access the specified file. close(fd: number):Promise<void> -Closes a file. This API uses a promise to return the result asynchronously. +Closes a file. This API 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.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let fd = fileio.openSync(path); fileio.close(fd).then(function(){ - console.info("close file succeed"); + console.info("File closed"); }).catch(function(err){ - console.info("close file failed with error:"+ err); + console.info("Failed to close the file. Error:"+ err); }); ``` @@ -298,12 +337,14 @@ Closes a file. This API uses an asynchronous 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.| **Example** + ```js let fd = fileio.openSync(path); fileio.close(fd, function (err) { @@ -321,57 +362,16 @@ 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.| **Example** - ```js - fileio.closeSync(fd); - ``` - - -## fileio.close7+ - -close(): Promise<void> - -Closes the stream. This API uses a promise to return the result asynchronously. - -**System capability**: SystemCapability.FileManagement.File.FileIO - -**Return value** - | Type | Description | - | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| - -**Example** - ```js - fileio.close().then(function(){ - console.info("close file stream succeed"); - }).catch(function(err){ - console.info("close file stream failed with error:"+ err); - }); - ``` - - -## fileio.close7+ - -close(callback: AsyncCallback<void>): void - -Closes the stream. This API uses an asynchronous 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 - fileio.close(function(err){ - // Do something. - }); + let fd = fileio.openSync(path); + fileio.closeSync(fd); ``` @@ -379,11 +379,12 @@ Closes the stream. This API uses an asynchronous callback to return the result. copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> -Copies a file. This API uses a promise to return the result asynchronously. +Copies a file. This API 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. | @@ -391,16 +392,20 @@ Copies a file. This API uses a promise to return the result asynchronously. | 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 | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let src = path; + let dest = src + 'tgt'; fileio.copyFile(src, dest).then(function(){ - console.info("copyFile succeed"); + console.info("File copied"); }).catch(function(err){ - console.info("copyFile failed with error:"+ err); + console.info("Failed to copy the file. Error:"+ err); }); ``` @@ -414,6 +419,7 @@ Copies a file. This API uses an asynchronous 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. | @@ -422,7 +428,10 @@ Copies a file. This API uses an asynchronous callback to return the result. | callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | **Example** + ```js + let src = path; + let dest = src + 'tgt'; fileio.copyFile(src, dest, function (err) { // Do something. }); @@ -438,6 +447,7 @@ 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. | @@ -445,7 +455,10 @@ Synchronously copies a 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 + let src = path; + let dest = src + 'tgt'; fileio.copyFileSync(src, dest); ``` @@ -454,27 +467,30 @@ Synchronously copies a file. mkdir(path:string, mode?: number): Promise<void> -Creates a directory. This API uses a promise to return the result asynchronously. +Creates a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the directory. | | 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 | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.mkdir(path).then(function() { - console.info("mkdir succeed"); + console.info("Directory created"); }).catch(function (error){ - console.info("mkdir failed with error:"+ error); + console.info("Failed to create the directory. Error:"+ error); }); ``` @@ -488,6 +504,7 @@ Creates a directory. This API uses an asynchronous callback to return the result **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the directory. | @@ -495,9 +512,10 @@ Creates a directory. This API uses an asynchronous callback to return the result | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | **Example** + ```js fileio.mkdir(path, function(err) { - console.info("mkdir succeed"); + console.info("Directory created"); }); ``` @@ -511,12 +529,14 @@ Synchronously creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the directory. | | 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 fileio.mkdirSync(path); ``` @@ -526,28 +546,31 @@ Synchronously creates a directory. open(path: string, flags?: number, mode?: number): Promise<number> -Opens a file. This API uses a promise to return the result asynchronously. +Opens a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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.| +| 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** does not point 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 | | --------------------- | ----------- | | Promise<number> | Promise used to return the file descriptor of the file opened.| **Example** + ```js fileio.open(path, 0o1, 0o0200).then(function(number){ - console.info("Opened file successfully"); - }).catch(function(error){ - console.info("open file failed with error:"+ err); + console.info("File opened"); + }).catch(function(err){ + console.info("Failed to open the file. Error:"+ err); }); ``` @@ -561,14 +584,16 @@ Opens a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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.| +| 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** does not point 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 fileio.open(path, 0, function(err, fd) { // Do something. @@ -585,18 +610,21 @@ Synchronously opens a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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.| +| 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** does not point 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.
- **0o640**: The owner has the read and write permissions, and the user group has the read permission.
- **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 | | ------ | ----------- | | number | File descriptor of the file opened.| **Example** + ```js let fd = fileio.openSync(path, 0o102, 0o640); ``` @@ -618,11 +646,12 @@ read(fd: number, buffer: ArrayBuffer, options?: { position?: number; }): Promise<ReadOut> -Reads data from a file. This API uses a promise to return the result asynchronously. +Reads data from a file. This API 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 read. | @@ -636,14 +665,15 @@ Reads data from a file. This API uses a promise to return the result asynchronou | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); - fileio.read(fd, buf).then(function(readout){ + fileio.read(fd, buf).then(function(readOut){ console.info("Read file data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(error){ - console.info("read file data failed with error:"+ error); + }).catch(function(err){ + console.info("Failed to read file data. Error:"+ err); }); ``` @@ -661,6 +691,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the file to read. | @@ -669,6 +700,7 @@ Reads data from a file. This API uses an asynchronous callback to return the res | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); @@ -694,6 +726,7 @@ 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. | @@ -701,11 +734,13 @@ Synchronously reads data from a file. | 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.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data read.| **Example** + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); @@ -717,26 +752,29 @@ Synchronously reads data from a file. rmdir(path: string): Promise<void> -Deletes a directory. This API uses a promise to return the result asynchronously. +Deletes a directory. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.rmdir(path).then(function() { - console.info("rmdir succeed"); + console.info("Directory deleted"); }).catch(function(err){ - console.info("rmdir failed with error:"+ err); + console.info("Failed to delete the directory. Error:"+ err); }); ``` @@ -750,16 +788,18 @@ Deletes a directory. This API uses an asynchronous callback to return the result **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously. | **Example** + ```js fileio.rmdir(path, function(err){ // Do something. - console.info("rmdir succeed"); + console.info("Directory deleted"); }); ``` @@ -773,11 +813,13 @@ Synchronously deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the directory to delete.| +| path | string | Yes | Application sandbox path of the directory.| **Example** + ```js fileio.rmdirSync(path); ``` @@ -787,26 +829,29 @@ Synchronously deletes a directory. unlink(path:string): Promise<void> -Deletes a file. This API uses a promise to return the result asynchronously. +Deletes a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the file to delete.| +| path | string | Yes | Application sandbox path of the file.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js fileio.unlink(path).then(function(){ - console.info("Removed file successfully"); + console.info("File deleted"); }).catch(function(error){ - console.info("remove file failed with error:"+ error); + console.info("Failed to delete the file. Error:"+ error); }); ``` @@ -820,15 +865,17 @@ Deletes a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously. | **Example** + ```js fileio.unlink(path, function(err) { - console.info("Removed file successfully"); + console.info("File deleted"); }); ``` @@ -842,11 +889,13 @@ Synchronously deletes a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| **Example** + ```js fileio.unlinkSync(path); ``` @@ -861,11 +910,12 @@ write(fd: number, buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Writes data into a file. This API uses a promise to return the result asynchronously. +Writes data into a file. This API 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 write. | @@ -873,17 +923,19 @@ Writes data into a file. This API uses a promise to return the result asynchrono | 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.
Constraints: offset + length <= Buffer size| **Return value** + | Type | Description | | --------------------- | -------- | | Promise<number> | Promise used to return the length of the data written.| **Example** + ```js - let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666); + let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ - console.info("Wrote data to file successfully and size is:"+ number); + console.info("Data written to the file. Size is:"+ number); }).catch(function(err){ - console.info("write data to file failed with error:"+ err); + console.info("Failed to write data to the file. Error:"+ err); }); ``` @@ -902,6 +954,7 @@ Writes data into a file. This API uses an asynchronous 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 write. | @@ -910,11 +963,12 @@ Writes data into a file. This API uses an asynchronous callback to return the re | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { - console.info("Wrote data to file successfully and size is:"+ bytesWritten); + console.info("Data written to the file. Size is:"+ bytesWritten); } }); ``` @@ -934,6 +988,7 @@ 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. | @@ -941,11 +996,13 @@ Synchronously writes data into a file. | 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.
Constraints: offset + length <= Buffer size| **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data written in the file.| **Example** + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let num = fileio.writeSync(fd, "hello, world"); @@ -956,27 +1013,30 @@ Synchronously writes data into a file. hash(path: string, algorithm: string): Promise<string> -Calculates the hash value of a file. This API uses a promise to return the result asynchronously. +Calculates the hash value of a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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 | | --------------------- | -------------------------- | | Promise<string> | Promise used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** + ```js fileio.hash(path, "sha256").then(function(str){ - console.info("Calculated file hash successfully:"+ str); - }).catch(function(error){ - console.info("calculate file hash failed with error:"+ err); + console.info("Calculated file hash:"+ str); + }).catch(function(err){ + console.info("Failed to calculate the file hash. Error:"+ err); }); ``` @@ -990,6 +1050,7 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | --------- | --------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | @@ -997,10 +1058,11 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r | callback | AsyncCallback<string> | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.| **Example** + ```js - fileio.hash(fpath, "sha256", function(err, hashStr) { + fileio.hash(path, "sha256", function(err, hashStr) { if (hashStr) { - console.info("Calculated file hash successfully:"+ hashStr); + console.info("Calculated file hash:"+ hashStr); } }); ``` @@ -1010,27 +1072,30 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r chmod(path: string, mode: number):Promise<void> -Changes file permissions. This API uses a promise to return the result asynchronously. +Changes file permissions. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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 | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js - fileio.chmod(path, mode).then(function() { - console.info("chmod succeed"); + fileio.chmod(path, 0o700).then(function() { + console.info("File permissions changed"); }).catch(function(err){ - console.info("chmod failed with error:"+ err); + console.info("Failed to change file permissions. Error:"+ err); }); ``` @@ -1044,6 +1109,7 @@ Changes file permissions. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | @@ -1051,8 +1117,9 @@ Changes file permissions. This API uses an asynchronous callback to return the r | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** + ```js - fileio.chmod(path, mode, function (err) { + fileio.chmod(path, 0o700, function (err) { // Do something. }); ``` @@ -1067,14 +1134,16 @@ Synchronously changes file permissions. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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 - fileio.chmodSync(fpath, mode); + fileio.chmodSync(path, 0o700); ``` @@ -1082,26 +1151,30 @@ Synchronously changes file permissions. fstat(fd: number): Promise<Stat> -Obtains file information based on the file descriptor. This API uses a promise to return the result asynchronously. +Obtains file information based on the file descriptor. This API 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 target file.| **Return value** + | Type | Description | | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the file information.| **Example** + ```js + let fd = fileio.openSync(path); fileio.fstat(fd).then(function(stat){ - console.info("fstat succeed:"+ JSON.stringify(stat)); + console.info("Obtained file info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("fstat failed with error:"+ err); + console.info("Failed to obtain file info. Error:"+ err); }); ``` @@ -1115,12 +1188,14 @@ Obtains file information based on the file descriptor. This API uses an asynchro **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 to return the file information obtained.| **Example** + ```js let fd = fileio.openSync(path); fileio.fstat(fd, function (err) { @@ -1138,16 +1213,19 @@ Synchronously obtains file 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.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | File information obtained.| **Example** + ```js let fd = fileio.openSync(path); let stat = fileio.fstatSync(fd); @@ -1158,26 +1236,29 @@ Synchronously obtains file information based on the file descriptor. ftruncate(fd: number, len?: number): Promise<void> -Truncates a file based on the file descriptor. This API uses a promise to return the result asynchronously. +Truncates a file based on the file descriptor. This API 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 truncate. | | len | number | No | File length, in bytes, after truncation.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let fd = fileio.openSync(path); fileio.ftruncate(fd, 5).then(function(err) { - console.info("truncate file succeed"); + console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1193,15 +1274,19 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal **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 which returns no value. | + | callback | AsyncCallback<void> | Yes | Callback that returns no value.| **Example** + ```js - fileio.ftruncate(fd, len, function(err){ + let fd = fileio.openSync(path); + let len = 5; + fileio.ftruncate(fd, 5, function(err){ // Do something. }); ``` @@ -1216,13 +1301,17 @@ 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.| **Example** + ```js + let fd = fileio.openSync(path); + let len = 5; fileio.ftruncateSync(fd, len); ``` @@ -1231,25 +1320,29 @@ Synchronously truncates a file based on the file descriptor. truncate(path: string, len?: number): Promise<void> -Truncates a file based on the file path. This API uses a promise to return the result asynchronously. +Truncates a file based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | No | File length, in bytes, after truncation.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let len = 5; fileio.truncate(path, len).then(function(){ - console.info("Truncated file successfully"); + console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1265,14 +1358,17 @@ Truncates a file based on the file path. This API uses an asynchronous callback **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | Yes | File length, in bytes, after truncation.| -| callback | AsyncCallback<void> | Yes | Callback which returns no value. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| **Example** + ```js + let len = 5; fileio.truncate(path, len, function(err){ // Do something. }); @@ -1288,13 +1384,16 @@ Synchronously truncates a file based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to truncate. | +| path | string | Yes | Application sandbox path of the file to truncate.| | len | number | No | File length, in bytes, after truncation.| **Example** + ```js + let len = 5; fileio.truncateSync(path, len); ``` @@ -1307,27 +1406,30 @@ readText(filePath: string, options?: { encoding?: string; }): Promise<string> -Reads the text content of a file. This API uses a promise to return the result asynchronously. +Reads the text content of a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox 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 | | --------------------- | ---------- | | Promise<string> | Promise used to return the content read.| **Example** + ```js fileio.readText(path).then(function(str) { console.info("Read text successfully:"+ str); }).catch(function(err){ - console.info("readText failed with error:"+ err); + console.info("Failed to read the text. Error:"+ err); }); ``` @@ -1345,15 +1447,17 @@ Reads the text content of a file. This API uses an asynchronous callback to retu **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox 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**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| +| options | Object | Yes | 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**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| | callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** + ```js - fileio.readText(path, function(err, str){ + fileio.readText(path, { position: 1, encoding: 'UTF-8' }, function(err, str){ // Do something. }); ``` @@ -1372,17 +1476,20 @@ Synchronously reads the text of a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filePath | string | Yes | Application sandbox path of the file to be read. | +| filePath | string | Yes | Application sandbox 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 | Promise used to return the content of the file read.| **Example** + ```js let str = fileio.readTextSync(path, {position: 1, length: 3}); ``` @@ -1392,26 +1499,29 @@ Synchronously reads the text of a file. lstat(path: string): Promise<Stat> -Obtains link information. This API uses a promise to return the result asynchronously. +Obtains link information. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| path | string | Yes | Application sandbox path of the target file, pointing to the link.| +| path | string | Yes | Application sandbox path of the target file.| **Return value** + | Type | Description | | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the link information obtained. For details, see [Stat](#stat).| **Example** + ```js fileio.lstat(path).then(function(stat){ - console.info("Got link info successfully:"+ number); + console.info("Got link info:"+ JSON.stringify(stat)); }).catch(function(err){ - console.info("Failed to obtain the link status. Error:"+ err); + console.info("Failed to obtain link info. Error:"+ err); }); ``` @@ -1425,12 +1535,14 @@ Obtains link information. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | -| path | string | Yes | Application sandbox path of the target file, pointing to the link.| +| path | string | Yes | Application sandbox path of the target file.| | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the link information obtained. | **Example** + ```js fileio.lstat(path, function (err, stat) { // Do something. @@ -1447,83 +1559,21 @@ Synchronously obtains the link information. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | path | string | Yes | Application sandbox path of the target file.| **Return value** + | Type | Description | | ------------- | ---------- | | [Stat](#stat) | Link information obtained.| **Example** - ```js - let stat = fileio.lstatSync(path); - ``` - - -## fileio.read7+ - -read(buffer: ArrayBuffer, options?: { - position?: number; - offset?: number; - length?: number; -}): Promise<ReadOut> - -Reads data from a file. This API uses a promise to return the result asynchronously. - -**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.
Constraints: offset + length <= Buffer size| - -**Return value** - | Type | Description | - | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Promise used to return the data read.| - -**Example** - ```js - fileio.read(new ArrayBuffer(4096)).then(function(readout){ - console.info("Read file data successfully"); - console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - }).catch(function(err){ - console.info("Failed to read file data. Error:"+ err); - }); - ``` - - -## fileio.read7+ -read(buffer: ArrayBuffer, options: { - position?: number; - offset?: number; - length?: number; -}, callback: AsyncCallback<ReadOut>): void - -Reads data from a file. This API uses an asynchronous 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 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.
Constraints: offset + length <= Buffer size| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously from the file. | - -**Example** ```js - let buf = new ArrayBuffer(4096); - fileio.read(buf, function (err, readOut) { - if (readOut) { - console.info("Read file data successfully"); - console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); - } - }); + let stat = fileio.lstatSync(path); ``` @@ -1531,27 +1581,32 @@ Reads data from a file. This API uses an asynchronous callback to return the res rename(oldPath: string, newPath: string): Promise<void> -Renames a file. This API uses a promise to return the result asynchronously. +Renames a file. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| | newPath | String | Yes | Application sandbox path of the file renamed. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.rename(oldPath, newPath).then(function() { - console.info("rename succeed"); + console.info("File renamed"); }).catch(function(err){ - console.info("rename failed with error:"+ err); + console.info("Failed to rename the file. Error:"+ err); }); ``` @@ -1565,6 +1620,7 @@ Renames a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| @@ -1572,7 +1628,10 @@ Renames a file. This API uses an asynchronous callback to return the result. | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | **Example** + ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.rename(oldPath, newPath, function(err){ }); ``` @@ -1587,13 +1646,17 @@ Synchronously renames a file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | Yes | Application sandbox path of the file to rename.| | newPath | String | Yes | Application sandbox path of the file renamed. | **Example** + ```js + let oldPath = path; + let newPath = oldPath + '123'; fileio.renameSync(oldPath, newPath); ``` @@ -1602,26 +1665,30 @@ Synchronously renames a file. fsync(fd: number): Promise<void> -Flushes data of a file to disk. This API uses a promise to return the result asynchronously. +Flushes data of a file to disk. This API 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 flush.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let fd = fileio.openSync(path); fileio.fsync(fd).then(function(){ - console.info("sync data successfully"); + console.info("Data flushed"); }).catch(function(err){ - console.info("sync data failed with error:"+ err); + console.info("Failed to flush data. Error:"+ err); }); ``` @@ -1635,13 +1702,16 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------- | | fd | number | Yes | File descriptor of the file to flush. | | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is synchronized in asynchronous mode.| **Example** + ```js + let fd = fileio.openSync(path); fileio.fsync(fd, function(err){ // Do something. }); @@ -1657,13 +1727,16 @@ Flushes data of a file to disk in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the file to flush.| **Example** + ```js - fileio.fyncsSync(fd); + let fd = fileio.openSync(path); + fileio.fsyncSync(fd); ``` @@ -1671,26 +1744,30 @@ Flushes data of a file to disk in synchronous mode. fdatasync(fd: number): Promise<void> -Flushes data of a file to disk. This API uses a promise to return the result asynchronously. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. +Flushes data of a file to disk. This API uses a promise to return the result. **fdatasync()** is similar to **fsync()**, but does not flush modified metadata unless that metadata is needed. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | | fd | number | Yes | File descriptor of the file to flush.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let fd = fileio.openSync(path); fileio.fdatasync(fd).then(function(err) { - console.info("sync data succeed"); + console.info("Data flushed"); }).catch(function(err){ - console.info("sync data failed with error:"+ err); + console.info("Failed to flush data. Error:"+ err); }); ``` @@ -1704,13 +1781,16 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **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.| **Example** + ```js + let fd = fileio.openSync(path); fileio.fdatasync (fd, function (err) { // Do something. }); @@ -1726,12 +1806,15 @@ 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 flush.| **Example** + ```js + let fd = fileio.openSync(path); let stat = fileio.fdatasyncSync(fd); ``` @@ -1740,27 +1823,32 @@ Synchronizes data in a file in synchronous mode. symlink(target: string, srcPath: string): Promise<void> -Creates a symbolic link based on a path. This API uses a promise to return the result asynchronously. +Creates a symbolic link based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | target | string | Yes | Application sandbox path of the target file. | | srcPath | string | Yes | Application sandbox path of the symbolic link file.| **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlink(target, srcPath).then(function() { - console.info("symlink succeed"); + console.info("Symbolic link created"); }).catch(function(err){ - console.info("symlink failed with error:"+ err); + console.info("Failed to create the symbolic link. Error:"+ err); }); ``` @@ -1769,11 +1857,12 @@ Creates a symbolic link based on a path. This API uses a promise to return the r symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void -Creates a symbolic link based on a path. This API uses an asynchronous callback to return the result. +Creates a symbolic link based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | | target | string | Yes | Application sandbox path of the target file. | @@ -1781,7 +1870,10 @@ Creates a symbolic link based on a path. This API uses an asynchronous callback | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| **Example** + ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlink(target, srcPath, function (err) { // Do something. }); @@ -1797,13 +1889,17 @@ Synchronously creates a symbolic link based on a specified path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | | target | string | Yes | Application sandbox path of the target file. | | srcPath | string | Yes | Application sandbox path of the symbolic link file.| **Example** + ```js + let target = path; + let srcPath = target + 'aaa'; fileio.symlinkSync(target, srcPath); ``` @@ -1812,11 +1908,12 @@ Synchronously creates a symbolic link based on a specified path. chown(path: string, uid: number, gid: number): Promise<void> -Changes the file owner based on the file path. This API uses a promise to return the result asynchronously. +Changes the file owner based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| @@ -1824,17 +1921,19 @@ Changes the file owner based on the file path. This API uses a promise to return | gid | number | Yes | New group ID (GID). | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let stat = fileio.statSync(path); fileio.chown(path, stat.uid, stat.gid).then(function(){ - console.info("chown succeed"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -1848,6 +1947,7 @@ Changes the file owner based on the file path. This API uses an asynchronous cal **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------ | | path | string | Yes | Application sandbox path of the file. | @@ -1856,8 +1956,9 @@ Changes the file owner based on the file path. This API uses an asynchronous cal | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js - let stat = fileio.statSync(fpath) + let stat = fileio.statSync(path) fileio.chown(path, stat.uid, stat.gid, function (err){ // Do something. }); @@ -1873,6 +1974,7 @@ Synchronously changes the file owner based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| @@ -1880,8 +1982,9 @@ Synchronously changes the file owner based on its path. | gid | number | Yes | New GID. | **Example** + ```js - let stat = fileio.statSync(fpath) + let stat = fileio.statSync(path) fileio.chownSync(path, stat.uid, stat.gid); ``` @@ -1890,26 +1993,29 @@ Synchronously changes the file owner based on its path. mkdtemp(prefix: string): Promise<string> -Creates a temporary directory. This API uses a promise to return the result asynchronously. +Creates a temporary directory. This API uses a promise to return the result. **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.| **Return value** - | Name | Description | + + | Type | Description | | --------------------- | ---------- | - | Promise<string> | Promise used to return the directory generated.| + | Promise<string> | Promise used to return the unique directory generated.| **Example** + ```js fileio.mkdtemp(path + "XXXX").then(function(path){ - console.info("mkdtemp succeed:"+ path); + console.info("Temporary directory created:"+ path); }).catch(function(err){ - console.info("mkdtemp failed with error:"+ err); + console.info("Failed to create the temporary directory. Error:"+ err); }); ``` @@ -1923,12 +2029,14 @@ Creates a temporary directory. This API uses an asynchronous callback to return **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. | **Example** + ```js fileio.mkdtemp(path + "XXXX", function (err, res) { // Do something. @@ -1945,16 +2053,19 @@ 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.| **Return value** - | Name | Description | + + | Type | Description | | ------ | ---------- | | string | Unique path generated.| **Example** + ```js let res = fileio.mkdtempSync(path + "XXXX"); ``` @@ -1964,27 +2075,32 @@ Synchronously creates a temporary directory. fchmod(fd: number, mode: number): Promise<void> -Changes file permissions based on the file descriptor. This API uses a promise to return the result asynchronously. +Changes file permissions based on the file descriptor. This API 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 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 | + + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmod(fd, mode).then(function() { - console.info("chmod succeed"); + console.info("File permissions changed"); }).catch(function(err){ - console.info("chmod failed with error:"+ err); + console.info("Failed to change file permissions. Error:"+ err); }); ``` @@ -1998,6 +2114,7 @@ Changes file permissions based on the file descriptor. This API uses an asynchro **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | Yes | File descriptor of the target file. | @@ -2005,7 +2122,10 @@ Changes file permissions based on the file descriptor. This API uses an asynchro | callback | AsyncCallback <void> | Yes | Callback invoked when the file permissions are changed asynchronously. | **Example** + ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmod(fd, mode, function (err) { // Do something. }); @@ -2021,13 +2141,17 @@ 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.| **Example** + ```js + let fd = fileio.openSync(path); + let mode = 0o700; fileio.fchmodSync(fd, mode); ``` @@ -2036,27 +2160,30 @@ Synchronously changes the file permissions based on the file descriptor. createStream(path: string, mode: string): Promise<Stream> -Opens a file stream based on the file path. This API uses a promise to return the result asynchronously. +Opens a file stream based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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 | | --------------------------------- | --------- | - | Promise<[Stream](#stream7)> | Promise used to return the result.| + | Promise<[Stream](#stream)> | Promise used to return the result.| **Example** + ```js fileio.createStream(path, "r+").then(function(stream){ - console.info("createStream succeed"); + console.info("Stream opened"); }).catch(function(err){ - console.info("createStream failed with error:"+ err); + console.info("Failed to create the stream. Error:"+ err); }); ``` @@ -2065,20 +2192,22 @@ Opens a file stream based on the file path. This API uses a promise to return th createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void -Opens a stream based on the file path. This API uses an asynchronous callback to return the result. +Opens a file stream based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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. | +| callback | AsyncCallback<[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** + ```js - fileio.createStream(path, mode, function(err, stream){ + fileio.createStream(path, "r+", function(err, stream){ // Do something. }); ``` @@ -2093,17 +2222,20 @@ Synchronously opens a stream based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the 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 | + + | Type | Description | | ------------------ | --------- | - | [Stream](#stream7) | Stream opened.| + | [Stream](#stream) | Stream opened.| **Example** + ```js let ss = fileio.createStreamSync(path, "r+"); ``` @@ -2113,27 +2245,31 @@ Synchronously opens a stream based on the file path. fdopenStream(fd: number, mode: string): Promise<Stream> -Opens a file stream based on the file descriptor. This API uses a promise to return the result asynchronously. +Opens a file stream based on the file descriptor. This API 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 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 | + + | Type | Description | | --------------------------------- | --------- | - | Promise<[Stream](#stream7)> | Promise used to return the result.| + | Promise<[Stream](#stream)> | Promise used to return the result.| **Example** + ```js - fileio.fdopenStream(fd, mode).then(function(stream){ - console.info("openStream succeed"); + let fd = fileio.openSync(path); + fileio.fdopenStream(fd, "r+").then(function(stream){ + console.info("Stream opened"); }).catch(function(err){ - console.info("openStream failed with error:"+ err); + console.info("Failed to open the stream. Error:"+ err); }); ``` @@ -2147,15 +2283,18 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous **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. | + | callback | AsyncCallback <[Stream](#stream)> | Yes | Callback invoked when the stream is open asynchronously. | **Example** + ```js - fileio.fdopenStream(fd, mode, function (err, stream) { + let fd = fileio.openSync(path); + fileio.fdopenStream(fd, "r+", function (err, stream) { // Do something. }); ``` @@ -2170,18 +2309,22 @@ 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).| **Return value** + | Type | Description | | ------------------ | --------- | - | [Stream](#stream7) | Stream opened.| + | [Stream](#stream) | Stream opened.| **Example** + ```js + let fd = fileio.openSync(path); let ss = fileio.fdopenStreamSync(fd, "r+"); ``` @@ -2190,11 +2333,12 @@ Synchronously opens a stream based on the file descriptor. fchown(fd: number, uid: number, gid: number): Promise<void> -Changes the file owner based on the file descriptor. This API uses a promise to return the result asynchronously. +Changes the file owner based on the file descriptor. This API 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 target file.| @@ -2202,17 +2346,20 @@ Changes the file owner based on the file descriptor. This API uses a promise to | gid | number | Yes | New GID. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js + let fd = fileio.openSync(path); let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid).then(function() { - console.info("chown succeed"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -2226,6 +2373,7 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | --------------- | | fd | number | Yes | File descriptor of the target file. | @@ -2234,8 +2382,10 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js - let stat = fileio.statSync(fpath); + let fd = fileio.openSync(path); + let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid, function (err){ // Do something. }); @@ -2251,6 +2401,7 @@ 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.| @@ -2258,8 +2409,10 @@ Synchronously changes the file owner based on the file descriptor. | gid | number | Yes | New GID. | **Example** + ```js - let stat = fileio.statSync(fpath); + let fd = fileio.openSync(path); + let stat = fileio.statSync(path); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -2268,11 +2421,12 @@ Synchronously changes the file owner based on the file descriptor. lchown(path: string, uid: number, gid: number): Promise<void> -Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses a promise to return the result asynchronously. +Changes the file owner (owner of the symbolic link, not the file referred to by the symbolic link) based on the file path. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | | path | string | Yes | Application sandbox path of the file.| @@ -2280,17 +2434,19 @@ Changes the file owner (owner of the symbolic link, not the file referred to by | gid | number | Yes | New GID. | **Return value** + | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise which returns no value.| + | Promise<void> | Promise that returns no value.| **Example** + ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid).then(function() { - console.info("chown succeed"); + console.info("File owner changed"); }).catch(function(err){ - console.info("chown failed with error:"+ err); + console.info("Failed to change the file owner. Error:"+ err); }); ``` @@ -2304,6 +2460,7 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------ | | path | string | Yes | Application sandbox path of the file. | @@ -2312,6 +2469,7 @@ Changes the file owner (owner of the symbolic link, not the file referred to by | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| **Example** + ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid, function (err){ @@ -2329,6 +2487,7 @@ 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 | Application sandbox path of the file.| @@ -2336,6 +2495,7 @@ Synchronously changes the file owner based on the file path and changes the owne | gid | number | Yes | New GID. | **Example** + ```js let stat = fileio.statSync(path); fileio.lchownSync(path, stat.uid, stat.gid); @@ -2351,6 +2511,7 @@ Listens for file or directory changes. This API uses an asynchronous callback to **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | | filename | string | Yes | Application sandbox path of the file. | @@ -2358,15 +2519,19 @@ Listens for file or directory changes. This API uses an asynchronous callback to | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | **Return value** - | Name | Description | + + | Type | Description | | -------------------- | ---------- | | [Watcher](#watcher7) | Promise used to return the **Watcher** instance.| **Example** + ```js - fileio.createWatcher(filename, events, function(watcher){ - // Do something. + let filename = path +"/test.txt"; + fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); }); + ``` @@ -2416,11 +2581,13 @@ Checks whether this file is a block special file. A block special file supports **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ---------------- | | boolean | Whether the file is a block special file.| **Example** + ```js let isBLockDevice = fileio.statSync(path).isBlockDevice(); ``` @@ -2435,11 +2602,13 @@ Checks whether this file is a character special file. A character special file s **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ----------------- | | boolean | Whether the file is a character special file.| **Example** + ```js let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); ``` @@ -2454,11 +2623,13 @@ Checks whether this file is a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | ------------- | | boolean | Whether the file is a directory.| **Example** + ```js let isDirectory = fileio.statSync(path).isDirectory(); ``` @@ -2473,11 +2644,13 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------------- | | boolean | Whether the file is an FIFO.| **Example** + ```js let isFIFO = fileio.statSync(path).isFIFO(); ``` @@ -2492,13 +2665,15 @@ Checks whether this file is a regular file. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the file is a regular file.| **Example** + ```js - let isFile = fileio.statSync(fpath).isFile(); + let isFile = fileio.statSync(path).isFile(); ``` @@ -2511,11 +2686,13 @@ Checks whether this file is a socket. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | -------------- | | boolean | Whether the file is a socket.| **Example** + ```js let isSocket = fileio.statSync(path).isSocket(); ``` @@ -2530,11 +2707,13 @@ Checks whether this file is a symbolic link. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | ------- | --------------- | | boolean | Whether the file is a symbolic link.| **Example** + ```js let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); ``` @@ -2549,13 +2728,20 @@ Listens for the changes of a file. You can call the **Watcher.stop()** method sy stop(): Promise<void> -Stops the **watcher** instance. This API uses a promise to return the result asynchronously. +Stops the **watcher** instance. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - fileio.stop(); + let filename = path +"/test.txt"; + let watcher = fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); + }); + watcher.stop().then(function(){ + console.info("Watcher stopped"); + }); ``` @@ -2568,20 +2754,24 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| **Example** + ```js - fileio.stop(function(err){ - // Do something. + let filename = path +"/test.txt"; + let watcher = fileio.createWatcher(filename, 1, function(number){ + console.info("Monitoring times: "+number); }); + watcher.stop(function(){ + console.info("Watcher stopped"); + }) ``` - - -## Stream7+ +## Stream Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. @@ -2590,22 +2780,24 @@ Provides file stream management. Before calling a method of the **Stream** class close(): Promise<void> -Closes the stream. This API uses a promise to return the result asynchronously. +Closes the stream. This API 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); + let ss= fileio.createStreamSync(path, "r+"); ss.close().then(function(){ - console.info("Closed fileStream successfully"); + console.info("File stream closed"); }).catch(function(err){ - console.info("close fileStream failed with error:"+ err); + console.info("Failed to close the file stream. Error:"+ err); }); ``` @@ -2619,13 +2811,15 @@ Closes the stream. This API uses an asynchronous 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); + let ss= fileio.createStreamSync(path, "r+"); ss.close(function (err) { // Do something }); @@ -2641,8 +2835,9 @@ Synchronously closes the stream. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.closeSync(); ``` @@ -2651,22 +2846,24 @@ Synchronously closes the stream. flush(): Promise<void> -Flushes the stream. This API uses a promise to return the result asynchronously. +Flushes the stream. This API 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); + let ss= fileio.createStreamSync(path, "r+"); ss.flush().then(function (){ - console.info("Flushed stream successfully"); + console.info("Stream flushed"); }).catch(function(err){ - console.info("flush failed with error:"+ err); + console.info("Failed to flush the stream. Error:"+ err); }); ``` @@ -2680,13 +2877,15 @@ Flushes the stream. This API uses an asynchronous 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); + let ss= fileio.createStreamSync(path, "r+"); ss.flush(function (err) { // Do something }); @@ -2702,8 +2901,9 @@ Synchronously flushes the stream. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let ss= fileio.createStreamSync(path); + let ss= fileio.createStreamSync(path, "r+"); ss.flushSync(); ``` @@ -2717,28 +2917,31 @@ write(buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Writes data into the stream. This API uses a promise to return the result asynchronously. +Writes data into the stream. This API 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.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | --------------------- | -------- | | Promise<number> | Promise used to return the length of the data written.| **Example** + ```js - let ss= fileio.createStreamSync(fpath, "r+"); + let ss= fileio.createStreamSync(path, "r+"); ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ - console.info("Wrote data successfully and size is:"+ number); + console.info("Data written to the stream. Size is:"+ number); }).catch(function(err){ - console.info("write failed with error:"+ err); + console.info("Failed to write data to the stream. Error:"+ err); }); ``` @@ -2757,6 +2960,7 @@ Writes data into the stream. This API uses an asynchronous callback to return th **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. | @@ -2764,12 +2968,13 @@ Writes data into the stream. This API uses an asynchronous callback to return th | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | **Example** + ```js - let ss= fileio.createStreamSync(fpath, "r+"); + let ss= fileio.createStreamSync(path, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { // Do something - console.info("Wrote data successfully and size is:"+ bytesWritten); + console.info("Data written to the stream. Size is:"+ bytesWritten); } }); ``` @@ -2789,19 +2994,22 @@ 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.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ------ | -------- | | number | Length of the data written in the file.| **Example** + ```js - let ss= fileio.createStreamSync(fpath,"r+"); + let ss= fileio.createStreamSync(path,"r+"); let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); ``` @@ -2814,29 +3022,32 @@ read(buffer: ArrayBuffer, options?: { length?: number; }): Promise<ReadOut> -Reads data from the stream. This API uses a promise to return the result asynchronously. +Reads data from the stream. This API 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.
Constraints: offset + length <= Buffer size | **Return value** + | Type | Description | | ---------------------------------- | ------ | | Promise<[ReadOut](#readout)> | Promise used to return the data read.| **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); - ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ + let ss = fileio.createStreamSync(path, "r+"); + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){ console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); }).catch(function(err){ - console.info("read data failed with error:"+ err); + console.info("Failed to read data. Error:"+ err); }); ``` @@ -2854,6 +3065,7 @@ Reads data from the stream. This API uses an asynchronous callback to return the **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | @@ -2861,8 +3073,9 @@ Reads data from the stream. This API uses an asynchronous callback to return the | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); + let ss = fileio.createStreamSync(path, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (readOut) { console.info("Read data successfully"); @@ -2898,37 +3111,39 @@ Synchronously reads data from the stream. | number | Length of the data read.| **Example** + ```js - let ss = fileio.createStreamSync(fpath, "r+"); + let ss = fileio.createStreamSync(path, "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. +Manages directories. Before calling a method of the **Dir** class, use the **opendir()** method synchronously or asynchronously to create a **Dir** instance. ### read read(): Promise<Dirent> -Reads the next directory entry. This API uses a promise to return the result asynchronously. +Reads the next directory entry. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** + | Type | Description | | -------------------------------- | ------------- | | Promise<[Dirent](#dirent)> | Promise used to return the directory entry read.| **Example** + ```js - let dir = fileio.opendirSync(path); dir.read().then(function (dirent){ - console.log("read succeed:"+JSON.stringify(dirent)); + console.log("Read the next directory entry:"+JSON.stringify(dirent)); }).catch(function(err){ - console.info("read failed with error:"+ err); + console.info("Failed to read the next directory entry. Error:"+ err); }); ``` @@ -2942,17 +3157,18 @@ Reads the next directory entry. This API uses an asynchronous callback to return **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 (dirent) { // Do something - console.log("read succeed:"+JSON.stringify(dirent)); + console.log("Read the next directory entry:"+JSON.stringify(dirent)); } }); ``` @@ -2967,35 +3183,36 @@ 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(); ``` -### close +### close7+ close(): Promise<void> -Closes a directory. This API uses a promise to return the result asynchronously. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. +Closes a directory. This API uses a promise to return the result. 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.close().then(function(err){ console.info("close dir successfully"); }); ``` - ### close + ### close7+ close(callback: AsyncCallback<void>): void @@ -3004,8 +3221,8 @@ Closes a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let dir = fileio.opendirSync(path); dir.close(function(err){ console.info("close dir successfully"); }); @@ -3021,8 +3238,8 @@ Closes a directory. After a directory is closed, the file descriptor in Dir will **System capability**: SystemCapability.FileManagement.File.FileIO **Example** + ```js - let dir = fileio.opendirSync(path); dir.closeSync(); ``` @@ -3049,11 +3266,13 @@ Checks whether this directory entry is a block special file. A block special fil **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(); @@ -3069,11 +3288,13 @@ Checks whether a directory entry is a character special file. A character specia **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(); @@ -3089,11 +3310,13 @@ 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(); @@ -3109,11 +3332,13 @@ Checks whether this directory entry is a named pipe (or FIFO). Named pipes are u **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(); @@ -3129,11 +3354,13 @@ 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(); @@ -3149,13 +3376,15 @@ 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 dir = fileio.opendirSync(path); let isSocket = dir.readSync().isSocket(); ``` @@ -3169,11 +3398,13 @@ 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 a1422c1bff0f93f58e8ce5ddac6c177eec96e16a..9aa6294c56aed0d897ceecc46c4fd4ca6ecd48c6 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -1,11 +1,12 @@ # User File Access and Management + +The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. + >**NOTE**
> >- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. -This module provides service APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. - ## Modules to Import ```js @@ -18,28 +19,26 @@ getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> Obtains information about the root album or directory in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -- Return value +**Return value** - | Type| Description| - | --- | -- | - | Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| +| Type| Description| +| --- | -- | +| Promise<[FileInfo](#fileinfo)[]> | Promise used to return the root album or directory information obtained.| -- Example +**Example** ```js - filemanager.getRoot().then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + filemanager.getRoot().then((fileInfos) => { + for (var i = 0; i < fileInfos.length; i++) { + console.log("files:"+JSON.stringify(fileInfos)); + } }).catch((err) => { console.log(err) }); @@ -51,31 +50,28 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) Obtains information about the root album or directory in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ----------------------------- | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------- | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | -- Example +**Example** ```js - let option = { - "dev":{ - name:"", - } + let options = { + "dev":{ + "name":"local" + } }; - filemanager.getRoot(option,(err, fileInfo)=>{ - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + filemanager.getRoot(options, (err, fileInfos)=>{ + for (var i = 0; i < fileInfos.length; i++) { + console.log("files:"+JSON.stringify(fileInfos)); + } }); - ``` ## filemanager.listFile @@ -84,102 +80,85 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num Obtains information about the second-level album or files in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService + +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| path | string | Yes| URI of the directory to query.| +| type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | path | string | Yes| URI of the directory to query.| - | type | string | Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - -- Return value +**Return value** - | Type| Description| - | --- | -- | - | Promise<FileInfo[]> | Promise used to return the album or file information obtained.| +| Type| Description| +| --- | -- | +| Promise<FileInfo[]> | Promise used to return the album or file information obtained.| -- Error - | Error Info| Error Code|Description| - | -- | --- | -- | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service.| - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +**Error** -- Example +| Error Info| Error Code|Description| +| -- | --- | -- | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service.| +| Not a directory | 20 | The object specified by the URI is not a directory or album.| + +**Example** ```js - // Obtain all files in the directory. - // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.path - filemanager.listFile(media_path, "file") - .then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + // Obtain all files in the directory. You can use getRoot to obtain the directory URI. + filemanager.getRoot().then((fileInfos) => { + let file = fileInfos.find(item => item.name == "file_folder"); + let path = file.path; + filemanager.listFile(path, "file").then((files) => { + console.log("files:" + JSON.stringify(files)); + }).catch((err) => { + console.log("failed to get files" + err); + }); }).catch((err) => { - - console.log(err) - }); + console.log("failed to get root" + err); + }); ``` - - ## filemanager.listFile listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void Obtains information about the second-level album or files in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ------------------------------------------------------------ | - | path | string | Yes | URI of the directory to query. | - | type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the file information obtained. | -- Error +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| path | string | Yes | URI of the directory to query. | +| type | string | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.
-  **offset**: position to start the query. The value is a number.
-  **count**: number of files to query.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | - | Error Info | Error Code| Description | - | ------------------------- | ------ | ------------------------- | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service. | - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +**Error** -- Example +| Error Info | Error Code| Description | +| ------------------------- | ------ | ------------------------- | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service. | +| Not a directory | 20 | The object specified by the URI is not a directory or album.| - ```js - // Call listFile() and getRoot() to obtain the file path. - let fileInfos = await filemanager.getRoot(); - let media_path = ""; - for (let i = 0; i < fileInfos.length; i++) { - if (fileInfos[i].name == "image_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "audio_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "video_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "file_folder") { - media_path = fileInfos[i].path; - } - } - - filemanager.listFile(media_path, "file") - .then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } - }).catch((err) => { - console.log(err) - }); - ``` +**Example** + +```js +// Obtain all files in the directory. You can use getRoot to obtain the directory URI. +filemanager.getRoot().then((fileInfos) => { + let file = fileInfos.find(item => item.name == "image_album"); + let path = file.path; + filemanager.listFile(path, "image",function(err, files){ + console.log("files:" + JSON.stringify(files)); + }) +}).catch((err) => { + console.log("failed to get root" + err); +}); +``` ## filemanager.createFile @@ -187,34 +166,35 @@ createFile(path : string, filename : string, options? : {dev? : DevInfo}) : P Creates a file in the specified path in asynchronous mode. This API uses a promise to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters - | Name| Type| Mandatory| Description| - | --- | --- | --- | -- | - | filename | string | Yes| Name of the file to create.| - | path | string | Yes| URI of the file to create.| - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +**Parameters** +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| filename | string | Yes| Name of the file to create.| +| path | string | Yes| URI of the file to create.| +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| -- Return value +**Return value** - | Type| Description| - | --- | -- | - | promise| Promise used to return the URI of the file created.| +| Type| Description| +| --- | -- | +| Promise<string> | Promise used to return the URI of the file created.| -- Error - | Error Info| Error Code|Description| - | -- | --- | -- | - | Operation not permitted | 1 | A file with the same name already exists.| - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service.| - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +**Error** -- Example +| Error Info| Error Code|Description| +| -- | --- | -- | +| Operation not permitted | 1 | A file with the same name already exists.| +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service.| +| Not a directory | 20 | The object specified by the URI is not a directory or album.| + +**Example** ```js // Create a file. - let media_path = file.uri // Obtain the file URI using listFile() and getRoot(). + let media_path = "" // Obtain the file URI using listFile() and getRoot(). let name = "xxx.jpg" // File to be saved. filemanager.createFile(media_path, name).then((uri) => { // The URI of the file created is returned. @@ -230,44 +210,50 @@ createFile(path : string, filename: string, options? : {dev? : DevInfo}, callbac Creates a file in the specified path in asynchronous mode. This API uses a callback to return the result. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | ------------------------- | ---- | ----------------------------- | - | filename | string | Yes | Name of the file to create. | - | path | string | Yes | URI of the file to create. | - | options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the file information obtained. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------- | +| filename | string | Yes | Name of the file to create. | +| path | string | Yes | URI of the file to create. | +| options | Object | No| The options are as follows:
-  **dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| +| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | Yes | Callback invoked to return the root album or directory information obtained. | -- Error +**Error** - | Error Info | Error Code| Description | - | ------------------------- | ------ | ------------------------- | - | Operation not permitted | 1 | A file with the same name already exists. | - | No such file or directory | 2 | The directory or album of the specified URI does not exist.| - | No such process | 3 | Failed to obtain the FMS service. | - | Not a directory | 20 | The object specified by the URI is not a directory or album.| +| Error Info | Error Code| Description | +| ------------------------- | ------ | ------------------------- | +| Operation not permitted | 1 | A file with the same name already exists. | +| No such file or directory | 2 | The directory or album of the specified URI does not exist.| +| No such process | 3 | Failed to obtain the FMS service. | +| Not a directory | 20 | The object specified by the URI is not a directory or album.| -- Example +**Example** ```js // Create a file. // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.path + let media_path = "" // File to be saved. let name = "xxx.jpg" - filemanager.createFile(media_path, name, (err, uri) => { - // The URI of the file created is returned. - console.log("file uri:"+uri); + let options = { + "dev":{ + "name":"local" + } + }; + filemanager.createFile(media_path, name, options, function(err, uri) { + // The URI of the file created is returned. + console.log("file uri:"+uri); }); + ``` ## FileInfo Defines the file information returned by **getRoot()** or **listFile()**. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService ### Attributes @@ -284,7 +270,7 @@ Defines the file information returned by **getRoot()** or **listFile()**. Defines the device type. -**System capability**: SystemCapability.FileManagement.FileManagerService +**System capability**: SystemCapability.FileManagement.UserFileService ### Attributes diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 4d45271a8791a8370ed4950c75ac96c0fb408b8c..fd44ed62b3e67dfac8c3fa44f0f23485e2eeff5d 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,6 +1,6 @@ # HiLog -The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. +The HiLog module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -23,8 +23,8 @@ Checks whether logs are printable based on the specified service domain, log tag | Name| Type | Mandatory| Description | | ------ | --------------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | level | [LogLevel](#loglevel) | Yes | Log level. | **Return value** @@ -48,7 +48,7 @@ Enumerates the log levels. | Name | Default Value| Description | | ----- | ------ | ------------------------------------------------------------ | | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| -| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,
for example, no network signal or login failure.
These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| +| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running, for example, no network signal or login failure.
These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.| | ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.| | FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified. | @@ -67,8 +67,8 @@ DEBUG logs are not recorded in official versions by default. They are available | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| @@ -98,8 +98,8 @@ Prints INFO logs. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| @@ -129,8 +129,8 @@ Prints WARN logs. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| @@ -160,8 +160,8 @@ Prints ERROR logs. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| @@ -191,8 +191,8 @@ Prints FATAL logs. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| -| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| +| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.
You can define the value as required.| +| tag | string | Yes | Log tag in the string format.
You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index e856ee20a4c8956ff0f05707b596935b68ca9e7a..04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,8 +1,9 @@ # Performance Tracing -This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **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,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; startTrace(name: string, taskId: number): void -Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. +Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 9611d7e68637b765327e81e9ed68db9e68ceb9ef..885fde56d55291c2922af84d177f7a64ba29cedc 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -1438,4 +1438,4 @@ Defines the **HuksResult** structure. | errorCode | number | Yes | Error code. | | outData | Uint8Array | No | Output data.| | properties | Array\ | No | Properties. | -| certChains | Array\ | No | Certificate chain. | +| certChains | Array\ | No | Reserved. | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 7d7ec04c6ca3bcbaf5cb8d1f314d256f15efbef8..06d2731b53f9e803be6cb72a60f63076f595c4f8 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,9 +1,13 @@ -# Internationalization – i18n +# Internationalization – I18N + +This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. + +The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. + +> **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. -> -> - This module contains enhanced i18n APIs, which are not defined in ECMA 402. ## Modules to Import @@ -49,15 +53,15 @@ Obtains the localized script for the specified country. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ------- | ---- | ---------------- | +| 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 | -| ------ | ------------- | +| Type | Description | +| ------ | ------------------------------------------ | | string | Localized script for the specified country.| **Example** @@ -76,12 +80,12 @@ 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.| +| Name | Type | Description | +| ------ | ------ | ----------- | +| locale | string | Locale ID. | **Return Value** -| Type | Description | +| Type | Description | | ------- | ---------------------------------------- | | boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.| @@ -115,7 +119,9 @@ Obtains the system language. setSystemLanguage(language: string): boolean -Sets the system language. +Sets the system language. Currently, this API does not support real-time updating of the system language. + +**System API**: This is a system API. **Required permission**: ohos.permission.UPDATE_CONFIGURATION @@ -145,9 +151,9 @@ getSystemLanguages(): Array<string> Obtains the list of system languages. -**System capability**: SystemCapability.Global.I18n +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Global.I18n **Return Value** | Type | Description | @@ -166,9 +172,9 @@ getSystemCountries(language: string): Array<string> Obtains the list of countries and regions supported for the specified language. -**System capability**: SystemCapability.Global.I18n +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Global.I18n **Parameters** | Name | Type | Description | @@ -211,12 +217,12 @@ setSystemRegion(region: string): boolean Sets the system region. +**System API**: This is a system API. + **Required permission**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Global.I18n -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Description | | ------ | ------ | ----- | @@ -258,12 +264,12 @@ setSystemLocale(locale: string): boolean Sets the system locale. +**System API**: This is a system API. + **Required permission**: ohos.permission.UPDATE_CONFIGURATION **System capability**: SystemCapability.Global.I18n -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Description | | ------ | ------ | --------------- | @@ -286,9 +292,9 @@ isSuggested(language: string, region?: string): boolean Checks whether the system language matches the specified region. -**System capability**: SystemCapability.Global.I18n +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Global.I18n **Parameters** | Name | Type | Mandatory | Description | @@ -673,6 +679,31 @@ Formats a phone number. phonenumberfmt.format("15812312312"); ``` +### getLocationName9+ + +getLocationName(number: string, locale: string): string + +Obtains the home location of a phone number. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------- | +| number | string | Yes | Phone number.| +| locale | string | Yes | Locale ID.| + +**Return value** +| Type | Description | +| ------ | ---------- | +| string | Home location of the phone number.| + +**Example** + ```js + var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); + phonenumberfmt.isValidNumber("15812312312"); + ``` + ## PhoneNumberFormatOptions8+ @@ -727,6 +758,28 @@ Converts one measurement unit into another and formats the unit based on the spe i18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); ``` +### getDateOrder9+ + +static getDateOrder(locale: string): string + +Obtains the sequence of the year, month, and day in the specified locale. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. | + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| string | Sequence of the year, month, and day.| + +**Example** + ``` + i18n.Util.getDateOrder("zh-CN"); + ``` ## getInstance8+ @@ -816,7 +869,7 @@ Obtains the index of a text object. **Example** ``` var indexUtil= i18n.getInstance("zh-CN"); - indexUtil.getIndex("hi"); // Return h. + indexUtil.getIndex("hi"); // Return hi. ``` @@ -1442,10 +1495,10 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. ``` -## RelativeTimeFormat8+ +## TimeZone -### getID8+ +### getID getID(): string @@ -1465,7 +1518,7 @@ Obtains the ID of the specified **TimeZone** object. ``` -### getDisplayName8+ +### getDisplayName getDisplayName(locale?: string, isDST?: boolean): string @@ -1491,7 +1544,7 @@ Obtains the representation of a **TimeZone** object in the specified locale. ``` -### getRawOffset8+ +### getRawOffset getRawOffset(): number @@ -1511,7 +1564,7 @@ Obtains the offset between the time zone represented by a **TimeZone** object an ``` -### getOffset8+ +### getOffset getOffset(date?: number): number @@ -1529,3 +1582,207 @@ Obtains the offset between the time zone represented by a **TimeZone** object an var timezone = i18n.getTimeZone(); timezone.getOffset(1234567890); ``` + +### getAvailableIDs9+ + +static getAvailableIDs(): Array<string> + +Obtains the list of time zone IDs supported by the system. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Array<string> | List of time zone IDs supported by the system.| + +**Example** + ```ts + var ids = i18n.TimeZone.getAvailableIDs(); + ``` + + +### getAvailableZoneCityIDs9+ + +static getAvailableZoneCityIDs(): Array<string> + +Obtains the list of time zone city IDs supported by the system. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------------------- | ------------- | +| Array<string> | List of time zone city IDs supported by the system.| + +**Example** + ```ts + var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + ``` + + +### getCityDisplayName9+ + +static getCityDisplayName(cityID: string, locale: string): string + +Obtains the localized display of a time zone city in the specified locale. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------ | +| cityID | string | Yes | Time zone city ID.| +| locale | string | Yes | Locale ID. | + +**Return value** +| Type | Description | +| ------ | ------------------ | +| string | Localized display of the time zone city in the specified locale.| + +**Example** + ```ts + var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + ``` + + +### getTimezoneFromCity9+ + +static getTimezoneFromCity(cityID: string): TimeZone + +Obtains the **TimeZone** object corresponding to the specified time zone city ID. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------ | +| cityID | string | Yes | Time zone city ID.| + +**Return value** +| Type | Description | +| -------- | ----------- | +| TimeZone | **TimeZone** object corresponding to the specified time zone city ID.| + +**Example** + ```ts + var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + ``` + + +## i18n.setUsingLocalDigit9+ + +setUsingLocalDigit(flag: boolean): boolean + +Sets whether to turn on the local digit switch. + +This is a system API. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------- | ---- | ------------------------------- | +| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| + +**Return value** +| Type | Description | +| ------- | ----------------------------------- | +| boolean | Result indicating whether the local digit switch is successfully set. The value **true** indicates that the local digit switch is successfully set, and the value **false** indicates the opposite.| + +**Example** + ```ts + var status = i18n.setUsingLocalDigit(true); + ``` + + +## i18n.getUsingLocalDigit9+ + +getUsingLocalDigit(): boolean + +Checks whether the local digit switch is turned on. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Result indicating whether the local digit switch is turned on. The value **true** indicates that the local digit switch is turned on, and the value **false** indicates the opposite.| + +**Example** + ```ts + var status = i18n.getUsingLocalDigit(); + ``` + + +## Transliterator9+ + + +### getAvailableIDs9+ + +static getAvailableIDs(): string[] + +Obtains a list of IDs supported by the **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| -------- | ---------- | +| string[] | List of IDs supported by the **Transliterator** object.| + +**Example** + ```ts + i18n.Transliterator.getAvailableIDs(); + ``` + + +### getInstance9+ + +static getInstance(id: string): Transliterator + +Creates a **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------- | +| id | string | Yes | ID supported by the **Transliterator** object.| + +**Return value** +| Type | Description | +| ---------------------------------- | ----- | +| [Transliterator](#transliterator9) | **Transliterator** object.| + +**Example** + ```ts + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + ``` + + +### transform9+ + +transform(text: string): string + +Converts the input string from the source format to the target format. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------ | +| text | string | Yes | Input string.| + +**Return value** +| Type | Description | +| ------ | -------- | +| string | Target string.| + +**Example** + ```ts + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + transliterator.transform ("China"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 72f4e341792546d1423ee4f9b55f660f168bed84..30ead3b023cbb8bf673f948a549e8867f381cb01 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,29 +1,31 @@ # Image Processing -> **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 **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area). + +> **NOTE** > -> API version 9 is a canary release for trial use. The APIs of this version may be unstable. +> 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 -``` +```js import image from '@ohos.multimedia.image'; ``` ## image.createPixelMap8+ + createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\ Creates a **PixelMap** object. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | 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.| +| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | +| options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** @@ -34,9 +36,12 @@ Creates a **PixelMap** object. This API uses a promise to return the result. **Example** ```js -image.createPixelMap(Color, opts) - .then((pixelmap) => { - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts) + .then((pixelmap) => { + }) ``` ## image.createPixelMap8+ @@ -45,21 +50,24 @@ createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: As Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------------- | -| colors | ArrayBuffer | Yes | Color array. | -| options | [InitializetionOptions](#initializationoptions8) | Yes | Pixel properties. | +| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | +| options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties. | | callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js -image.createPixelMap(Color, opts, (pixelmap) => { - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (pixelmap) => { + }) ``` ## PixelMap7+ @@ -68,9 +76,11 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i ### Attributes -| Name | Type | Readable| Writable| Description | -| ----------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | -| isEditable7+ | boolean | Yes | No | Whether the image pixel map is editable.
**System capability**: SystemCapability.Multimedia.Image| +**System capability**: SystemCapability.Multimedia.Image.Core + +| Name | Type | Readable| Writable| Description | +| ---------- | ------- | ---- | ---- | -------------------------- | +| isEditable | boolean | Yes | No | Whether the image pixel map is editable.| ### readPixelsToBuffer7+ @@ -78,28 +88,29 @@ readPixelsToBuffer(dst: ArrayBuffer): Promise\ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------- | ---- | ------------------------------------------------------------ | -| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written.| +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ----------------------------------------------------------------------------------------------------- | +| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.| **Return value** | Type | Description | -| :------------- | :---------------------------------------------- | -| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.| +| -------------- | ----------------------------------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** ```js +const readBuffer = new ArrayBuffer(400); pixelmap.readPixelsToBuffer(readBuffer).then(() => { - // Called if the condition is met. - }).catch(error => { - // Called if no condition is met. - }) + console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. +}).catch(error => { + console.log('Failed to read image pixel data.'); // Called if no condition is met. +}) ``` ### readPixelsToBuffer7+ @@ -108,20 +119,26 @@ readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------------------ | -| dst | ArrayBuffer | Yes | Buffer to which the image 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. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ----------------------------------------------------------------------------------------------------- | +| dst | ArrayBuffer | Yes | Buffer to which the image pixel map data will be written. The buffer size is obtained by calling **getPixelBytesNumber**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned. | **Example** ```js -pixelmap.readPixelsToBuffer(readBuffer, () => { - }) +const readBuffer = new ArrayBuffer(400); +pixelmap.readPixelsToBuffer(readBuffer, (err, res) => { + if(err) { + console.log('Failed to read image pixel data.'); // Called if no condition is met. + } else { + console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. + } +}) ``` ### readPixels7+ @@ -130,7 +147,7 @@ readPixels(area: PositionArea): Promise\ Reads image pixel map data in an area. This API uses a promise to return the data read. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** @@ -142,16 +159,17 @@ Reads image pixel map data in an area. This API uses a promise to return the dat | Type | Description | | :------------- | :-------------------------------------------------- | -| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** ```js -pixelmap.readPixels(area).then((data) => { - // Called if the condition is met. - }).catch(error => { - // Called if no condition is met. - }) +const area = new ArrayBuffer(400); +pixelmap.readPixels(area).then(() => { + console.log('Succeeded in reading the image data in the area.'); // Called if the condition is met. +}).catch(error => { + console.log('Failed to read the image data in the area.'); // Called if no condition is met. +}) ``` ### readPixels7+ @@ -160,33 +178,33 @@ readPixels(area: PositionArea, callback: AsyncCallback\): void Reads image pixel map data in an area. This API uses an asynchronous callback to return the data read. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------ | ---- | ------------------------------ | | area | [PositionArea](#positionarea7) | Yes | Area from which the image pixel map data will be read. | -| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Example** ```js +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (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'); - }) - } + if(pixelmap == undefined){ + console.info('createPixelMap failed.'); + } 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'); + }) + } }) ``` @@ -196,7 +214,7 @@ writePixels(area: PositionArea): Promise\ Writes image pixel map data to an area. This API uses a promise to return the operation result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** @@ -208,26 +226,25 @@ Writes image pixel map data to an area. This API uses a promise to return the op | Type | Description | | :------------- | :-------------------------------------------------- | -| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** ```js const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts) .then( pixelmap => { if (pixelmap == undefined) { - console.info('createPixelMap failed'); - expect(false).assertTrue() - done(); + console.info('createPixelMap failed.'); } 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); + let bufferArr = new Uint8Array(area.pixels); for (var i = 0; i < bufferArr.length; i++) { bufferArr[i] = i + 1; } @@ -240,11 +257,8 @@ image.createPixelMap(color, opts) region: { size: { height: 1, width: 2 }, x: 0, y: 0 } } }) - }) - .catch(error => { + }).catch(error => { console.log('error: ' + error); - expect().assertFail(); - done(); }) ``` @@ -254,26 +268,31 @@ writePixels(area: PositionArea, callback: AsyncCallback\): void Writes image pixel map data to an area. This API uses an asynchronous callback to return the operation result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | Name | Type | Mandatory| Description | | --------- | ------------------------------ | ---- | ------------------------------ | | area | [PositionArea](#positionarea7) | Yes | Area to which the image 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.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Example** ```js -pixelmap.writePixels(area, () => { - const readArea = { - pixels: new ArrayBuffer(20), - offset: 0, - stride: 8, - region: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - } - }) +const area = new ArrayBuffer(400); +pixelmap.writePixels(area, (error) => { + if (error!=undefined) { + console.info('Failed to write pixelmap into the specified area.'); + } else { + const readArea = { + pixels: new ArrayBuffer(20), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 }, + } + } +}) ``` ### writeBufferToPixels7+ @@ -282,7 +301,7 @@ writeBufferToPixels(src: ArrayBuffer): Promise\ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** @@ -294,16 +313,19 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj | Type | Description | | -------------- | ----------------------------------------------- | -| Promise\ | Promise used to return the operation result. If the operation fails, an error message is returned.| +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| **Example** ```js -pixelMap.writeBufferToPixels(colorBuffer).then(() => { +const color = new ArrayBuffer(96); +const pixelMap = new ArrayBuffer(400); +let bufferArr = new Uint8Array(color); +pixelMap.writeBufferToPixels(color).then(() => { console.log("Succeeded in writing data from a buffer to a PixelMap."); }).catch((err) => { console.error("Failed to write data from a buffer to a PixelMap."); -}); +}) ``` ### writeBufferToPixels7+ @@ -312,24 +334,28 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\): void Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** object. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------ | | src | ArrayBuffer | Yes | Buffer from which the image data will be read. | -| callback | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| **Example** ```js -pixelMap.writeBufferToPixels(colorBuffer, function(err) { +const color = new ArrayBuffer(96);\ +const pixelMap = new ArrayBuffer(400); +let bufferArr = new Uint8Array(color); +pixelMap.writeBufferToPixels(color, function(err) { if (err) { console.error("Failed to write data from a buffer to a PixelMap."); return; - } - console.log("Succeeded in writing data from a buffer to a PixelMap."); + } else { + console.log("Succeeded in writing data from a buffer to a PixelMap."); + } }); ``` @@ -339,7 +365,7 @@ getImageInfo(): Promise\ Obtains pixel map information of this image. This API uses a promise to return the information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Return value** @@ -350,6 +376,7 @@ Obtains pixel map information of this image. This API uses a promise to return t **Example** ```js +const pixelMap = new ArrayBuffer(400); pixelMap.getImageInfo().then(function(info) { console.log("Succeeded in obtaining the image pixel map information."); }).catch((err) => { @@ -363,7 +390,7 @@ getImageInfo(callback: AsyncCallback\): void Obtains pixel map information of this image. This API uses an asynchronous callback to return the information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** @@ -374,36 +401,43 @@ Obtains pixel map information of this image. This API uses an asynchronous callb **Example** ```js -pixelmap.getImageInfo((imageInfo) => {}) +pixelmap.getImageInfo((imageInfo) => { + console.log("Succeeded in obtaining the image pixel map information."); +}) ``` ### getBytesNumberPerRow7+ getBytesNumberPerRow(): number -Obtains the number of bytes per line of the image pixel map. +Obtains the number of bytes per row of this image pixel map. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Return value** | Type | Description | | ------ | -------------------- | -| number | Number of bytes per line.| +| number | Number of bytes per row.| **Example** ```js -rowCount = pixelmap.getBytesNumberPerRow() +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err,pixelmap) => { + let rowCount = pixelmap.getBytesNumberPerRow(); +}) ``` ### getPixelBytesNumber7+ getPixelBytesNumber(): number -Obtains the total number of bytes of the image pixel map. +Obtains the total number of bytes of this image pixel map. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Return value** @@ -414,7 +448,7 @@ Obtains the total number of bytes of the image pixel map. **Example** ```js -pixelBytesNumber = pixelmap.getPixelBytesNumber() +let pixelBytesNumber = pixelmap.getPixelBytesNumber(); ``` ### release7+ @@ -423,19 +457,27 @@ release():Promise\ Releases this **PixelMap** object. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Return value** -| Type | Description | -| -------------- | ------------------ | -| Promise\ | Promise used to return the operation result.| +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js - pixelmap.release().then(() => { }) - .catch(error => {}) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (pixelmap) => { + pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); + }).catch(error => { + console.log('Failed to release pixelmap object.'); + }) +}) ``` ### release7+ @@ -444,18 +486,27 @@ release(callback: AsyncCallback\): void Releases this **PixelMap** object. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the operation result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js -pixelmap.release(()=>{ }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (pixelmap) => { + pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); + }).catch(error => { + console.log('Failed to release pixelmap object.'); + }) +}) ``` ## image.createImageSource @@ -464,7 +515,7 @@ createImageSource(uri: string): ImageSource Creates an **ImageSource** instance based on the URI. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -491,12 +542,12 @@ createImageSource(fd: number): ImageSource Creates an **ImageSource** instance based on the file descriptor. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------- | | fd | number | Yes | File descriptor.| **Return value** @@ -517,9 +568,11 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour ### Attributes +**System capability**: SystemCapability.Multimedia.Image.ImageSource + | Name | Type | Readable| Writable| Description | | ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| supportedFormats | Array\ | Yes | No | Supported image formats, including png, jpeg, wbmp, bmp, gif, webp, and heif.
**System capability**: SystemCapability.Multimedia.Image| +| supportedFormats | Array\ | Yes | No | Supported image formats, including png, jpeg, wbmp, bmp, gif, webp, and heif.| ### getImageInfo @@ -527,7 +580,7 @@ getImageInfo(index: number, callback: AsyncCallback\): void Obtains information about an image with the specified index. This API uses an asynchronous callback to return the information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -539,7 +592,13 @@ Obtains information about an image with the specified index. This API uses an as **Example** ```js -imageSourceApi.getImageInfo(0,(error, imageInfo) => {}) +imageSourceApi.getImageInfo(0,(error, imageInfo) => { + if(error) { + console.log('getImageInfo failed.'); + } else { + console.log('getImageInfo succeeded.'); + } +}) ``` ### getImageInfo @@ -548,7 +607,7 @@ getImageInfo(callback: AsyncCallback\): void Obtains information about this image. This API uses an asynchronous callback to return the information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -559,7 +618,9 @@ Obtains information about this image. This API uses an asynchronous callback to **Example** ```js -imageSourceApi.getImageInfo(imageInfo => {}) +imageSourceApi.getImageInfo(imageInfo => { + console.log('Succeeded in obtaining the image information.'); +}) ``` ### getImageInfo @@ -568,7 +629,7 @@ getImageInfo(index?: number): Promise\ Obtains information about an image with the specified index. This API uses a promise to return the image information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -586,8 +647,11 @@ Obtains information about an image with the specified index. This API uses a pro ```js imageSourceApi.getImageInfo(0) - .then(imageInfo => {}) - .catch(error => {}) + .then(imageInfo => { + console.log('Succeeded in obtaining the image information.'); + }).catch(error => { + console.log('Failed to obtain the image information.'); + }) ``` ### getImageProperty7+ @@ -596,7 +660,7 @@ getImageProperty(key:string, options?: GetImagePropertyOptions): Promise\ | Promise used to return the property value. If the operation fails, the default value is returned.| **Example** ```js imageSourceApi.getImageProperty("BitsPerSample") - .then(data => {}) - .catch(error => {}) + .then(data => { + console.log('Succeeded in getting the value of the specified attribute key of the image.'); + }) ``` ### getImageProperty7+ @@ -625,7 +690,7 @@ getImageProperty(key:string, callback: AsyncCallback\): void Obtains the value of a property with the specified index in this image. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -637,7 +702,13 @@ Obtains the value of a property with the specified index in this image. This API **Example** ```js -imageSourceApi.getImageProperty("BitsPerSample",(error,data) => {}) +imageSourceApi.getImageProperty("BitsPerSample",(error,data) => { + if(error) { + console.log('Failed to get the value of the specified attribute key of the image.'); + } else { + console.log('Succeeded in getting the value of the specified attribute key of the image.'); + } +}) ``` ### getImageProperty7+ @@ -646,20 +717,27 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa Obtains the value of a property in this image. This API uses an asynchronous callback to return the property value in a string. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| key | string | Yes | Name of the property. | -| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------- | +| key | string | Yes | Name of the property. | +| options | [GetImagePropertyOptions](#getimagepropertyoptions7) | Yes | Image properties, including the image index and default property value. | | callback | AsyncCallback\ | Yes | Callback used to return the property value. If the operation fails, the default value is returned.| **Example** ```js -imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {}) +const property = new ArrayBuffer(400); +imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { + if(error) { + console.log('Failed to get the value of the specified attribute key of the image.'); + } else { + console.log('Succeeded in getting the value of the specified attribute key of the image.'); + } +}) ``` ### createPixelMap7+ @@ -668,7 +746,7 @@ createPixelMap(options?: DecodingOptions): Promise\ Creates a **PixelMap** object based on image decoding parameters. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -685,8 +763,11 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Example** ```js -imageSourceApi.createPixelMap().then(pixelmap => {}) - .catch(error => {}) +imageSourceApi.createPixelMap().then(pixelmap => { + console.log('Succeeded in creating pixelmap object through image decoding parameters.'); +}).catch(error => { + console.log('Failed to create pixelmap object through image decoding parameters.'); +}) ``` ### createPixelMap7+ @@ -695,7 +776,7 @@ createPixelMap(callback: AsyncCallback\): void Creates a **PixelMap** object based on the default parameters. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -706,7 +787,11 @@ Creates a **PixelMap** object based on the default parameters. This API uses an **Example** ```js -imageSourceApi.createPixelMap(pixelmap => {}) +imageSourceApi.createPixelMap(pixelmap => { + console.log('Succeeded in creating pixelmap object.'); +}).catch(error => { + console.log('Failed to create pixelmap object.'); +}) ``` ### createPixelMap7+ @@ -715,7 +800,7 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\): vo Creates a **PixelMap** object based on image decoding parameters. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -727,7 +812,10 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Example** ```js -imageSourceApi.createPixelMap(decodingOptions, pixelmap => {}) +const decodingOptions = new ArrayBuffer(400); +imageSourceApi.createPixelMap(decodingOptions, pixelmap => { + console.log('Succeeded in creating pixelmap object.'); +}) ``` ### release @@ -736,7 +824,7 @@ release(callback: AsyncCallback\): void Releases this **ImageSource** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Parameters** @@ -747,7 +835,9 @@ Releases this **ImageSource** instance. This API uses an asynchronous callback t **Example** ```js -imageSourceApi.release(() => {}) +imageSourceApi.release(() => { + console.log('release succeeded.'); +}) ``` ### release @@ -756,18 +846,22 @@ release(): Promise\ Releases this **ImageSource** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise\ | Promise used to return the operation result.| +| Promise\ | Promise used to return the result.| **Example** ```js -imageSourceApi.release().then(()=>{ }).catch(error => {}) +imageSourceApi.release().then(()=>{ + console.log('Succeeded in releasing the image source instance.'); +}).catch(error => { + console.log('Failed to release the image source instance.'); +}) ``` ## image.createImagePacker @@ -776,7 +870,7 @@ createImagePacker(): ImagePacker Creates an **ImagePacker** instance. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageReceiver **Return value** @@ -796,9 +890,11 @@ Provide APIs to pack images. Before calling any API in **ImagePacker**, you must ### Attributes -| Name | Type | Readable| Writable| Description | -| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| supportedFormats | Array\ | Yes | No | Supported image format, which can be jpeg.
**System capability**: SystemCapability.Multimedia.Image| +**System capability**: SystemCapability.Multimedia.Image.ImagePacker + +| Name | Type | Readable| Writable| Description | +| ---------------- | -------------- | ---- | ---- | -------------------------- | +| supportedFormats | Array\ | Yes | No | Supported image format, which can be jpeg.| ### packing @@ -806,7 +902,7 @@ packing(source: ImageSource, option: PackingOption, 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 } +let packOpts = { format:"image/jpeg", quality:98 }; +const imageSourceApi = new ArrayBuffer(400); imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -829,7 +926,7 @@ packing(source: ImageSource, option: PackingOption): Promise\ Packs an image. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImagePacker **Parameters** @@ -841,16 +938,20 @@ Packs an image. This API uses a promise to return the result. **Return value** | Type | Description | -| :--------------------------- | :-------------------------------------------- | -| Promise\ | Promise used to return the packed data.| +| ---------------------------- | --------------------------------------------- | +| Promise\ | Promise used to return the packed data.| **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 } +let packOpts = { format:"image/jpeg", quality:98 } +const imageSourceApi = new ArrayBuffer(400); imagePackerApi.packing(imageSourceApi, packOpts) - .then( data => { }) - .catch(error => {}) + .then( data => { + console.log('packing succeeded.'); + }).catch(error => { + console.log('packing failed.'); + }) ``` ### packing8+ @@ -859,7 +960,7 @@ packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\ {}) +let packOpts = { format:"image/jpeg", quality:98 } +const pixelMapApi = new ArrayBuffer(400); +imagePackerApi.packing(pixelMapApi, packOpts, data => { + console.log('Succeeded in packing the image.'); +}).catch(error => { + console.log('Failed to pack the image.'); +}) ``` ### packing8+ @@ -882,28 +988,32 @@ packing(source: PixelMap, option: PackingOption): Promise\ Packs an image. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImagePacker **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------- | ---- | -------------- | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | ------------------ | | source | [PixelMap](#pixelmap) | Yes | **PixelMap** object to pack.| -| option | [PackingOption](#packingoption) | Yes | Option for image packing.| +| option | [PackingOption](#packingoption) | Yes | Option for image packing. | **Return value** -| Type | Description | -| :--------------------------- | :-------------------------------------------- | +| Type | Description | +| --------------------- | -------------------------------------------- | | Promise\ | Promise used to return the packed data.| **Example** ```js -let packOpts = { format:["image/jpeg"], quality:98 } +let packOpts = { format:"image/jpeg", quality:98 } +const pixelMapApi = new ArrayBuffer(400); imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { }) - .catch(error => {}) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image.'); + }) ``` ### release @@ -912,7 +1022,7 @@ release(callback: AsyncCallback\): void Releases this **ImagePacker** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImagePacker **Parameters** @@ -923,7 +1033,9 @@ Releases this **ImagePacker** instance. This API uses an asynchronous callback t **Example** ```js -imagePackerApi.release(()=>{}) +imagePackerApi.release(()=>{ + console.log('Succeeded in releasing image packaging.'); +}) ``` ### release @@ -932,39 +1044,43 @@ release(): Promise\ Releases this **ImagePacker** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImagePacker **Return value** -| Type | Description | -| :------------- | :------------------------------------------------------ | +| Type | Description | +| -------------- | ------------------------------------------------------ | | Promise\ | Promise used to return the instance release result. If the operation fails, an error message is returned.| **Example** ```js - imagePackerApi.release().then(()=>{ - }).catch((error)=>{}) +imagePackerApi.release().then(()=>{ + console.log('Succeeded in releasing image packaging.'); +}).catch((error)=>{ + console.log('Failed to release image packaging.'); +}) ``` + ## PositionArea7+ Describes area information in an image. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core | 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. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo Describes image information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | @@ -974,7 +1090,7 @@ Describes image information. Describes the size of an image. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core | Name | Type | Readable| Writable| Description | | ------ | ------ | ---- | ---- | -------------- | @@ -983,57 +1099,35 @@ Describes the size of an image. ## PixelMapFormat7+ -Enumerates pixel map formats. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| --------- | ------ | ----------------- | -| UNKNOWN | 0 | Unknown format. | -| RGBA_8888 | 3 | RGBA_8888.| -| RGB_565 | 2 | RGB_565. | - -## AlphaType9+ - -Enumerates alpha types. +Enumerates the pixel formats of images. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | -| -------- | ------ | ----------------------- | -| UNKNOWN | 0 | Unknown alpha type. | -| OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| Name | Default Value| Description | +| ---------------------- | ------ | ----------------- | +| UNKNOWN | 0 | Unknown format. | +| RGBA_8888 | 3 | RGBA_8888.| +| RGB_565 | 2 | RGB_565. | -## ScaleMode9+ -Enumerates scale modes. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| --------------- | ------ | -------------------------------------------------- | -| CENTER_CROP | 1 | The image is scaled in such a way that it fits the dimensions of the target and centered in the target.| -| FIT_TARGET_SIZE | 2 | The image size is reduced to fit the dimensions of the target. | ## InitializationOptions8+ -**System capability**: SystemCapability.Multimedia.Image +Defines pixel map initialization options. + +**System capability**: SystemCapability.Multimedia.Image.Core -| Name | Type | Readable| Writable| Description | -| ----------- | ---------------------------------- | ---- | ---- | -------------- | -| alphaType9+ | [AlphaType](#alphatype9) | Yes | Yes | Alpha type. | -| editable | boolean | Yes | Yes | Whether the image is editable. | -| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. | -| scaleMode9+ | [ScaleMode](#scalemode9) | Yes | Yes | Scale mode. | -| size | [Size](#size) | Yes | Yes | Image size.| +| Name | Type | Readable| Writable| Description | +| ------------------------ | ---------------------------------- | ---- | ---- | -------------- | +| editable | boolean | Yes | Yes | Whether the image is editable. | +| pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. | +| size | [Size](#size) | Yes | Yes | Image size.| ## DecodingOptions7+ -Describes the decoding options. +Defines image decoding options. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource | Name | Type | Readable| Writable| Description | | ------------------ | ---------------------------------- | ---- | ---- | ---------------- | @@ -1043,13 +1137,13 @@ Describes the decoding options. | desiredSize | [Size](#size) | Yes | Yes | Expected output size. | | 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. | +| index | number | Yes | Yes | Index of the image to decode. | ## Region7+ Describes region information. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.Core | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | @@ -1059,20 +1153,20 @@ Describes region information. ## PackingOption -Describes the option for image packing. +Defines the option for image packing. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImagePacker -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------- | -| format | string | Yes | Yes | Format of the packed image. | -| quality | number | Yes | Yes | Quality of the packed image.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | --------------------------------------------------- | +| format | string | Yes | Yes | Format of the packed image. | +| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| ## GetImagePropertyOptions7+ Describes image properties. -**System capability**: SystemCapability.Multimedia.Image +**System capability**: SystemCapability.Multimedia.Image.ImageSource | Name | Type | Readable| Writable| Description | | ------------ | ------ | ---- | ---- | ------------ | @@ -1081,17 +1175,60 @@ Describes image properties. ## PropertyKey7+ -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 bits per pixel. | -| ORIENTATION | "Orientation" | Image orientation. | -| IMAGE_LENGTH | "ImageLength" | Image length. | -| IMAGE_WIDTH | "ImageWidth" | Image width. | -| GPS_LATITUDE | "GPSLatitude" | Image latitude. | -| GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S.| -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E.| +Describes the exchangeable image file format (EXIF) information of an image. + +**System capability**: SystemCapability.Multimedia.Image.Core + +| Name | Default Value | Description | +| ----------------- | ----------------------- | ------------------------ | +| BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. | +| ORIENTATION | "Orientation" | Image orientation. | +| IMAGE_LENGTH | "ImageLength" | Image length. | +| IMAGE_WIDTH | "ImageWidth" | Image width. | +| GPS_LATITUDE | "GPSLatitude" | Image latitude. | +| GPS_LONGITUDE | "GPSLongitude" | Image longitude. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | + + +## ResponseCode + +Enumerates the response codes returned upon build errors. + +| Name | Value | Description | +| ----------------------------------- | -------- | --------------------------------------------------- | +| ERR_MEDIA_INVALID_VALUE | -1 | Invalid value. | +| SUCCESS | 0 | Operation successful. | +| ERROR | 62980096 | Operation failed. | +| ERR_IPC | 62980097 | IPC error. | +| ERR_SHAMEM_NOT_EXIST | 62980098 | The shared memory does not exist. | +| ERR_SHAMEM_DATA_ABNORMAL | 62980099 | The shared memory is abnormal. | +| ERR_IMAGE_DECODE_ABNORMAL | 62980100 | An error occurs during image decoding. | +| ERR_IMAGE_DATA_ABNORMAL | 62980101 | The input image data is incorrect. | +| ERR_IMAGE_MALLOC_ABNORMAL | 62980102 | An error occurs during image memory allocation. | +| ERR_IMAGE_DATA_UNSUPPORT | 62980103 | Unsupported image type. | +| ERR_IMAGE_INIT_ABNORMAL | 62980104 | An error occurs during image initialization. | +| ERR_IMAGE_GET_DATA_ABNORMAL | 62980105 | An error occurs during image data retrieval. | +| ERR_IMAGE_TOO_LARGE | 62980106 | The image data is too large. | +| ERR_IMAGE_TRANSFORM | 62980107 | An error occurs during image transformation. | +| ERR_IMAGE_COLOR_CONVERT | 62980108 | An error occurs during image color conversion. | +| ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. | +| ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. | +| ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. | +| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image formats do not match. | +| ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. | +| ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. | +| ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. | +| ERR_IMAGE_DECODE_FAILED | 62980116 | Decoding failed. | +| ERR_IMAGE_PLUGIN_REGISTER_FAILED | 62980117 | Failed to register the plug-in. | +| ERR_IMAGE_PLUGIN_CREATE_FAILED | 62980118 | Failed to create the plug-in. | +| ERR_IMAGE_ENCODE_FAILED | 62980119 | Failed to encode the image. | +| ERR_IMAGE_ADD_PIXEL_MAP_FAILED | 62980120 | Failed to add the image pixel map. | +| ERR_IMAGE_HW_DECODE_UNSUPPORT | 62980121 | Unsupported image hardware decoding. | +| ERR_IMAGE_DECODE_HEAD_ABNORMAL | 62980122 | The image decoding header is incorrect. | +| ERR_IMAGE_DECODE_EXIF_UNSUPPORT | 62980123 | EXIF decoding is not supported. | +| ERR_IMAGE_PROPERTY_NOT_EXIST | 62980124 | The image property does not exist. The error codes for the image start from 150.| +| ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. | +| ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. | +| ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. | +| ERR_IMAGE_CONFIG_FAILED | 62980259 | The configuration is incorrect. | diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 0910c74e3242704a54627501f0d1f6721e7b0125..02b1e4e44cff5a54804801a82980a8f9aea8f779 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,5 +1,6 @@ # Combination Key +The input consumer module implements listening for key events. > **NOTE**
> @@ -22,23 +23,23 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): v Enables listening for combination key events. When a combination key event that meets the specified conditions occurs, **KeyOptions** will be passed as an input parameter to **callback**. -**System capability**: SystemCapability.MultimodalInput.Input.InputConsumer +This is a system API. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| -| keyOptions | [KeyOptions](#keyoption) | Yes| Key option, which specifies the condition for combination key input.| -| callback | Callback<KeyOptions> | Yes| Callback used to return the result. When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| +| keyOptions | [keyOptions](#keyoptions) | Yes| Key option, which specifies the condition for combination key input.| +| callback | Callback<[keyOptions](#keyoptions)> | Yes| Callback used to return the result. When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| **Example** ``` -let keyOptions = { preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0 } -let callback = function (keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} +let callback = function(keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) } inputConsumer.on('key', keyOptions, callback); ``` @@ -50,6 +51,8 @@ off(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): Stops listening for combination key events. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** @@ -57,16 +60,16 @@ Stops listening for combination key events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| -| keyOptions | [KeyOptions](#keyoption) | Yes| Key options passed to the key input event when listening starts.| -| callback | Callback<KeyOptions> | Yes| Callback function passed to the key input event with the key options when listening starts.| +| keyOptions | [keyOptions](#keyoptions) | Yes| Key options passed to the key input event when listening starts.| +| callback | Callback<[keyOptions](#keyoptions)> | Yes| Callback function passed to the key input event with the key option when listening starts.| **Example** ``` -let keyOptions = { preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0 } -let callback = function (keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} +let callback = function(keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) } inputConsumer.off('key', keyOptions, callback); ``` @@ -76,6 +79,8 @@ inputConsumer.off('key', keyOptions, callback); Defines the key options that are met when a combination key input event occurs. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index b5d06d979b5a7a6d29a3bff59cf5d91792bc1562..2a5d8cc98a8fbda9b052496e22bf3d3ee6ea1811 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -41,7 +41,7 @@ inputDevice.getDeviceIds((ids)=>{ ## inputDevice.getDeviceIds -function getDeviceIds(): Promise> +getDeviceIds(): Promise<Array<number>> Obtains the IDs of all input devices. This API uses a promise to return the result. @@ -51,7 +51,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu | Parameter | Description | | ---------------------- | ------------------ | -| Promise\> | Promise used to return the result.| +| Promise<Array<number>> | Promise used to return the result.| **Example** @@ -91,17 +91,23 @@ inputDevice.getDevice(1, (inputDevice)=>{ ## inputDevice.getDevice -function getDevice(deviceId: number): Promise\ +getDevice(deviceId: number): Promise<InputDeviceData> Obtains the information about an input device. This API uses a promise to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| deviceId | number | Yes | ID of the input device.| + **Return value** | Parameter | Description | | ------------------------ | ------------------ | -| Promise\ | Promise used to return the result.| +| Promise<[InputDeviceData](#inputdevicedata)> | Promise used to return the result.| **Example** @@ -121,21 +127,15 @@ 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. | -| axisRanges | Array<[axisRanges](#axisrange)> | Axis information of the input device. | -| bus | number | Bus type of the input device. | -| product | number | Product information of the input device. | -| vendor | number | Vendor information of the input device. | -| version | number | Version information of the input device. | -| phys | string | Physical address of the input device. | -| uniq | string | Unique ID of the input device. | - -## AxisType - -Defines the axis type of an input device, which is **NULL**. +| -------------------- | -------------------------------------- | ---------------------------------------- | +| id | number | Unique ID of the 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 type of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| +| axisRanges | Array<[axisRanges](#axisrange)> | Axis information of the input device. | + +## AxisType9+ + +Defines the axis type of an input device. ## AxisRange @@ -154,7 +154,7 @@ Defines the axis information of an input device. ## SourceType -Enumerates the input source types. For example, if a mouse reports an x-axis event, the source of the x-axis is the mouse. +Enumerates the input source types of the axis. 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 diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index 4d6bf02375fb726e84e47f12883e6ec0d7ecab69..1dde2335e6364982ab92cb7c91c1c0e09f1483f8 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,11 +1,12 @@ # Input Event Client +The input event client provides the key injection capability. > **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 of this module are system APIs 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 @@ -22,6 +23,8 @@ injectEvent({KeyEvent: KeyEvent}): void Injects a key. +This is a system API. + **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator **Parameters** @@ -47,11 +50,13 @@ let res = inputEventClient.injectEvent({KeyEvent: keyEvent}); Defines the information about the key to inject. +This is a system API. + **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.| +| keyCode | number | Yes | Key code. | +| keyDownDuration | number | Yes | Duration within which the key is pressed. | +| isIntercepted | boolean | 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 index 90c3c95c7c6f3a57edda9b2408c58533ee5eaa1f..41307f217099bd9991dfa6cd97745f24a532dcea 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,44 +1,45 @@ # Input Method Framework -> **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. +> **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'; +import inputMethod from '@ohos.inputmethod'; ``` ## inputMethod6+ Provides the constants. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| -## InputMethodProperty6+ +## InputMethodProperty6+ Describes the input method application attributes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | packageName | string | Yes| No| Package name.| | methodId | string | Yes| No| Ability name.| -## inputMethod.getInputMethodController +## inputMethod.getInputMethodController getInputMethodController(): InputMethodController Obtains an [InputMethodController](#InputMethodController) instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -48,17 +49,17 @@ Obtains an [InputMethodController](#InputMethodController) instance. **Example** - ```js +```js var InputMethodController = inputMethod.getInputMethodController(); - ``` +``` -## inputMethod.getInputMethodSetting6+ +## inputMethod.getInputMethodSetting6+ getInputMethodSetting(): InputMethodSetting Obtains an [InputMethodSetting](#InputMethodSetting) instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -69,10 +70,10 @@ Obtains an [InputMethodSetting](#InputMethodSetting) instance. **Example** ```js -var InputMethodSetting = inputMethod.getInputMethodSetting(); + var InputMethodSetting = inputMethod.getInputMethodSetting(); ``` -## InputMethodController +## 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. @@ -82,7 +83,7 @@ stopInput(callback: AsyncCallback<boolean>): void Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -104,7 +105,7 @@ stopInput(): Promise<boolean> Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -116,11 +117,11 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ```js - var isSuccess = InputMethodController.stopInput(); - console.info('stopInput isSuccess = ' + isSuccess); + var isSuccess = InputMethodController.stopInput(); + console.info('stopInput isSuccess = ' + isSuccess); ``` -## InputMethodSetting6+ +## InputMethodSetting6+ 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. @@ -130,7 +131,7 @@ listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>) Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -140,14 +141,14 @@ Obtains the list of installed input methods. This API uses an asynchronous callb **Example** - ```js - InputMethodSetting.listInputMethod((properties)=>{ - for (var i = 0;i < properties.length; i++) { - var property = properties[i]; - console.info(property.packageName + "/" + property.methodId); - } +```js + InputMethodSetting.listInputMethod((properties)=>{ + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } }); - ``` +``` ### listInputMethod @@ -155,7 +156,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -166,11 +167,11 @@ Obtains the list of installed input methods. This API uses an asynchronous callb **Example** ```js - var properties = InputMethodSetting.listInputMethod(); - for (var i = 0;i < properties.length; i++) { - var property = properties[i]; - console.info(property.packageName + "/" + property.methodId); - } + var properties = InputMethodSetting.listInputMethod(); + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } ``` ### displayOptionalInputMethod @@ -179,7 +180,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework - Parameters @@ -189,9 +190,9 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono **Example** ```js - InputMethodSetting.displayOptionalInputMethod(()=>{ + InputMethodSetting.displayOptionalInputMethod(()=>{ console.info('displayOptionalInputMethod is called'); - }); + }); ``` ### displayOptionalInputMethod @@ -200,7 +201,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -211,5 +212,5 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono **Example** ```js - InputMethodSetting.displayOptionalInputMethod(); + InputMethodSetting.displayOptionalInputMethod(); ``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 753992ebd71d29a5a2bc77b717ef0df6cd988125..5ad3a192a82939747f94ec7aeefc4c5baea7d0aa 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,19 +1,20 @@ # 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. +> **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'; +import inputMethodEngine from '@ohos.inputmethodengine'; ``` ## inputMethodEngine Defines constant values. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -50,7 +51,7 @@ getInputMethodEngine(): InputMethodEngine Obtains an **InputMethodEngine** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -70,7 +71,7 @@ createKeyboardDelegate(): KeyboardDelegate Obtains a **KeyboardDelegate** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -94,7 +95,7 @@ on(type: 'inputStart', callback: (kbController: KeyboardController, textInputCli Listens for the input method binding event. This API uses a callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -118,7 +119,7 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC Cancels listening for the input method binding event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -139,7 +140,7 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void Listens for an input method event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -162,7 +163,7 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void Cancels listening for an input method event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -187,7 +188,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -210,7 +211,7 @@ off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void Cancels listening for a hard keyboard even. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -231,7 +232,7 @@ on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) = Listens for cursor context changes. This API uses a callback to return the cursor information. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -254,7 +255,7 @@ off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) Cancels listening for cursor context changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -275,7 +276,7 @@ on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegi Listens for text selection changes. This API uses a callback to return the text selection information. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -298,7 +299,7 @@ off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBe Cancels listening for text selection changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -320,7 +321,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -343,7 +344,7 @@ off(type: 'textChange', callback?: (text: string) => void): void Cancels listening for text changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -368,7 +369,7 @@ hideKeyboard(callback: AsyncCallback<void>): void Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -390,7 +391,7 @@ hideKeyboard(): Promise<void> Hides the keyboard. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -415,7 +416,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -438,7 +439,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -465,7 +466,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -488,7 +489,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -515,7 +516,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -538,7 +539,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -565,7 +566,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -588,7 +589,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -615,7 +616,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -638,7 +639,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -665,7 +666,7 @@ insertText(text:string, callback: AsyncCallback<boolean>): void Inserts text. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -688,7 +689,7 @@ insertText(text:string): Promise<boolean> Inserts text. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -715,7 +716,7 @@ 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 +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -736,7 +737,7 @@ getEditorAttribute(): Promise<EditorAttribute> Obtains the attribute of the edit box. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -754,7 +755,7 @@ var EditorAttribute = TextInputClient.getEditorAttribute(); Describes the attribute of the edit box. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name | Type| Readable| Writable| Description | | ------------ | -------- | ---- | ---- | ------------------ | @@ -765,7 +766,7 @@ Describes the attribute of the edit box. Describes the attribute of a key. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------ | diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 60d0705b23023859d7c24804a4d55e64c6159ff7..1cd5b9527fdbc5fb070faebad7167be67c2c9da7 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,5 +1,6 @@ # Input Monitor +The input monitor module implements listening for global touch events. > **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. @@ -10,7 +11,7 @@ ## Modules to Import -``` +```js import inputMonitor from '@ohos.multimodalInput.inputMonitor'; ``` @@ -24,7 +25,9 @@ ohos.permission.INPUT_MONITORING on(type: "touch", receiver: TouchEventReceiver): void -Starts listening for global input events. +Starts listening for global touch events. + +This is a system API. **Required permissions**: ohos.permission.INPUT_MONITORING @@ -32,32 +35,17 @@ Starts listening for global input events. **Parameters** | 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. | +| -------- | ----------------------------------------- | ---- | ------------------------------- | +| type | string | Yes | Type of the input event to listen for. The value is **touch**.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | **Example** -``` -export default { - callback: function (value) { - if (checkEvent(value)) { - // The event meets the service requirement and is consumed. - return true; - } else { - // The event does not meet the service requirement and is not consumed. - return false; - } - }, - testOn: function () { - console.info("InputMonitorJsTest---start---testOn"); - inputMonitor.on( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOn"); - } -} +```js +inputMonitor.off("touch", (event) => { + // A touch event is consumed. + return false; +}); ``` @@ -65,7 +53,9 @@ export default { off(type: "touch", receiver?: TouchEventReceiver): void -Stops listening for global input events. +Stops listening for global touch events. + +This is a system API. **Required permissions**: ohos.permission.INPUT_MONITORING @@ -73,43 +63,22 @@ Stops listening for global input events. **Parameters** | 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. | +| -------- | ----------------------------------------- | ---- | ------------------------------- | +| type | string | Yes | Type of the input event to listen for. The value is **touch**.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | **Example** -``` -export default { - callback: function (value) { - if (checkEvent(value)) { - // The event meets the service requirement and is consumed. - return true; - } else { - // The event does not meet the service requirement and is not consumed. - return false; - } - }, - testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); - } - } +```js +inputMonitor.off("touch"); ``` ## TouchEventReceiver -Represents the class of the callback used to return the touch event. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite. - +Represents the class of the callback used to return the touch event. If the value **true** is returned, the touch event has been consumed, and the event monitor will be closed. -### (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. +This is a system API. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -125,24 +94,10 @@ Represents the callback used to return the touch event. You need to define the n **Example** -``` -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 { - // The event does not meet the service requirement and is not consumed. - return false; - } - }, - testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); - } -} +```js +inputMonitor.on("touch", (event) => { + // A touch event is consumed. + return false; +}); +inputMonitor.off("touch"); ``` diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 39735b35ebe1a6a0d2dce8e43e59a99b5b4f981e..b335be1b5cf4826da51120cd2156a64a7cd55bff 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,14 +1,17 @@ -# Internationalization – intl +# Internationalization – Intl -> ![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. -> -> - This module contains standard i18n APIs, which are defined in ECMA 402. + This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. + +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. + +> **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 -``` +```js import Intl from '@ohos.intl'; ``` @@ -43,7 +46,7 @@ Creates a Locale object. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var locale = new Intl.Locale(); ``` @@ -63,7 +66,7 @@ Creates a Locale object. | options | LocaleOptions | No | Options for creating the **Locale** object. | **Example** - ``` + ```js var locale = new Intl.Locale("zh-CN"); ``` @@ -82,7 +85,7 @@ Converts locale information to a string. | string | String containing locale information.| **Example** - ``` + ```js var locale = new Intl.Locale("zh-CN"); locale.toString(); ``` @@ -102,7 +105,7 @@ Maximizes information of the **Locale** object. If the script and locale informa | [Locale](#locale) | **Locale** object with the maximized information.| **Example** - ``` + ```js var locale = new Intl.Locale("zh-CN"); locale.maximize(); ``` @@ -122,7 +125,7 @@ Minimizes information of the **Locale** object. If the script and locale informa | [Locale](#locale) | **Locale** object with the minimized information.| **Example** - ``` + ```js var locale = new Intl.Locale("zh-CN"); locale.minimize(); ``` @@ -156,7 +159,7 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var datefmt= new Intl.DateTimeFormat(); ``` @@ -176,13 +179,13 @@ Creates a **DateTimeOptions** object for the specified locale. | options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | **Example** - ``` + ```js var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` **Example** - ``` + ```js var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -206,7 +209,7 @@ Formats the specified date and time. | string | A string containing the formatted date and time.| **Example** - ``` + ```js var date = new Date(2021, 11, 17, 3, 24, 0); var datefmt = new Intl.DateTimeFormat("en-GB"); datefmt.format(date); @@ -233,7 +236,7 @@ Formats the specified date range. | string | A string containing the formatted date and time range.| **Example** - ``` + ```js var startDate = new Date(2021, 11, 17, 3, 24, 0); var endDate = new Date(2021, 11, 18, 3, 24, 0); var datefmt = new Intl.DateTimeFormat("en-GB"); @@ -255,7 +258,7 @@ Obtains the formatting options for **DateTimeFormat** object. | [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| **Example** - ``` + ```js var datefmt = new Intl.DateTimeFormat("en-GB"); datefmt.resolvedOptions(); ``` @@ -302,7 +305,7 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var numfmt = new Intl.NumberFormat(); ``` @@ -322,7 +325,7 @@ Parameters | options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | **Example** - ``` + ```js var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -347,7 +350,7 @@ Formats a number. **Example** - ``` + ```js var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.format(1223); ``` @@ -368,7 +371,7 @@ Obtains the options of the **NumberFormat** object. **Example** - ``` + ```js var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.resolvedOptions(); ``` @@ -388,7 +391,7 @@ Provides the device capability. | 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**.| -| unitUsage8+ | 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**.| +| unitUsage8+ | 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**.| @@ -415,7 +418,7 @@ Creates a Collator object. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var collator = new Intl.Collator(); ``` @@ -436,7 +439,7 @@ Creates a Collator object. | options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | **Example** - ``` + ```js var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -461,7 +464,7 @@ Compares two strings based on the sorting policy of the **Collator** object. | 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** - ``` + ```js var collator = new Intl.Collator("zh-Hans"); collator.compare("first", "second"); ``` @@ -481,13 +484,13 @@ Returns properties reflecting the locale and collation options of a **Collator** | [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| **Example** - ``` + ```js var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); ``` -## CollatorOptions8+ +## CollatorOptions8+ Represents the properties of a **Collator** object. @@ -516,7 +519,7 @@ Create a **PluralRules** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var pluralRules = new Intl.PluralRules(); ``` @@ -536,8 +539,8 @@ Parameters | options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | **Example** - ``` - var pluralRules= new Intl.PluraRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ```js + var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -560,13 +563,13 @@ Obtains a string that represents the singular-plural type of the specified numbe | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| **Example** - ``` + ```js var pluralRules = new Intl.PluralRules("zh-Hans"); pluralRules.select(1); ``` -## PluralRulesOptions8+ +## PluralRulesOptions8+ Represents the properties of a **PluralRules** object. @@ -595,7 +598,7 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` + ```js var relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -615,7 +618,7 @@ Parameters | options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | **Example** - ``` + ```js var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -640,7 +643,7 @@ Formats the value and unit based on the specified locale and formatting options. | string | Relative time after formatting.| **Example** - ``` + ```js var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); relativetimefmt.format(3, "quarter") ``` @@ -666,7 +669,7 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt | Array<object> | An array of **RelativeTimeFormat** objects in parts.| **Example** - ``` + ```js var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); var parts = relativetimefmt.format(10, "seconds"); ``` @@ -686,13 +689,13 @@ Obtains the formatting options for **RelativeTimeFormat** objects. | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| **Example** - ``` + ```js var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); relativetimefmt.resolvedOptions(); ``` -## RelativeTimeFormatInputOptions8+ +## RelativeTimeFormatInputOptions8+ Represents the properties of a **RelativeTimeFormat** object. @@ -705,7 +708,7 @@ Represents the properties of a **RelativeTimeFormat** object. | style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -## RelativeTimeFormatResolvedOptions8+ +## RelativeTimeFormatResolvedOptions8+ Represents the properties of a **RelativeTimeFormat** object. diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index e2d0aff5a5eec1f468b0511a08f1f593a9af3548..a1e0786bda3cae69131a317ac6d61db35d0652c0 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,30 +1,42 @@ # Log -> ![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. +The Log module provides basic log printing capabilities and supports log printing by log level. -## console.debug - -debug(message: string): void +If you want to use more advanced log printing services, for example, filtering logs by the specified ID, you are advised to use [`@ohos.hilog`](js-apis-hilog.md). -Prints debug logs. - -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ----------- | - | message | string | Yes | Text to print.| +> **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. ## console.log log(message: string): void -Prints debug logs. +Prints logs. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ----------- | - | message | string | Yes | Text to print.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------- | +| message | string | Yes | Text to print.| + + +## console.debug + +debug(message: string): void + +Prints debug-level logs. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------- | +| message | string | Yes | Text to print.| ## console.info @@ -33,10 +45,13 @@ info(message: string): void Prints info-level logs. -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ----------- | - | message | string | Yes | Text to print.| +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------- | +| message | string | Yes | Text to print.| ## console.warn @@ -45,10 +60,13 @@ warn(message: string): void Prints warn-level logs. -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ----------- | - | message | string | Yes | Text to print.| +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------- | +| message | string | Yes | Text to print.| ## console.error @@ -57,10 +75,13 @@ error(message: string): void Prints error-level logs. -- Parameters - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ----------- | - | message | string | Yes | Text to print.| +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----------- | +| message | string | Yes | Text to print.| ## Example diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 778a22b5bbcac7ce661ed3cdf3c9601a8778e171..2c5a40a58caa3804a260910005af85a27f2a67b8 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -3,8 +3,6 @@ > **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. -> -> API version 9 is a canary release for trial use. The APIs of this version may be unstable. The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -13,7 +11,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. @@ -63,7 +60,7 @@ Creates a **VideoPlayer** instance in asynchronous mode. This API uses a callbac let videoPlayer media.createVideoPlayer((error, video) => { - if (typeof(video) != 'undefined') { + if (video != null) { videoPlayer = video; console.info('video createVideoPlayer success'); } else { @@ -92,7 +89,7 @@ Creates a **VideoPlayer** instance in asynchronous mode. This API uses a promise let videoPlayer media.createVideoPlayer().then((video) => { - if (typeof(video) != 'undefined') { + if (video != null) { videoPlayer = video; console.info('video createVideoPlayer success'); } else { @@ -108,6 +105,7 @@ media.createVideoPlayer().then((video) => { createAudioRecorder(): AudioRecorder Creates an **AudioRecorder** instance to control audio recording. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -123,65 +121,6 @@ Creates an **AudioRecorder** instance to control audio recording. let audioRecorder = media.createAudioRecorder(); ``` -## media.createVideoRecorder9+ - -createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void - -Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance created.| - -**Example** - -```js -let videoRecorder - -media.createVideoRecorder((error, video) => { - if (typeof(video) != 'undefined') { - videoRecorder = video; - console.info('video createVideoRecorder success'); - } else { - console.info(`video createVideoRecorder fail, error:${error.message}`); - } -}); -``` - -## media.createVideoRecorder9+ - -createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> - -Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| ----------------------------------------- | ----------------------------------- | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created.| - -**Example** - -```js -let videoRecorder - -media.createVideoRecorder().then((video) => { - if (typeof(video) != 'undefined') { - videoRecorder = video; - console.info('video createVideoRecorder success'); - } else { - console.info('video createVideoRecorder fail'); - } -}).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); -}); -``` @@ -274,13 +213,13 @@ For details about the audio playback demo, see [Audio Playback Development](../. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Readable| Writable| Description | -| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio 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. | -| state | [AudioState](#audiostate) | Yes | No | Audio playback state. | +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ----------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**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. | +| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| ### play @@ -368,7 +307,7 @@ Seeks to the specified playback position. ```js audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (typeof (seekDoneTime) == 'undefined') { + if (seekDoneTime == null) { console.info('audio seek fail'); return; } @@ -441,7 +380,7 @@ function printfDescription(obj) { } audioPlayer.getTrackDescription((error, arrlist) => { - if (typeof (arrlist) != 'undefined') { + if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); } @@ -477,7 +416,7 @@ function printfDescription(obj) { } audioPlayer.getTrackDescription().then((arrlist) => { - if (typeof (arrlist) != 'undefined') { + if (arrlist != null) { arrayDescription = arrlist; } else { console.log('audio getTrackDescription fail'); @@ -503,7 +442,7 @@ Subscribes to the audio buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -527,7 +466,7 @@ Subscribes to the audio playback events. | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed.| +| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed. | | callback | () => void | Yes | Callback invoked when the event is triggered. | **Example** @@ -552,7 +491,7 @@ audioPlayer.on('reset', () => { // Set the 'reset' event callback. audioPlayer = undefined; }); audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (typeof(seekDoneTime) == "undefined") { + if (seekDoneTime == null) { console.info('audio seek fail'); return; } @@ -600,14 +539,14 @@ Subscribes to the 'timeUpdate' event. | Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'timeUpdate' in this API.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) API is called.| +| type | string | Yes | Event type, which is 'timeUpdate' in this case.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) API is called.| | callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. | **Example** ```js audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (typeof (seekDoneTime) == 'undefined') { + if (seekDoneTime == null) { console.info('audio seek fail'); return; } @@ -620,7 +559,7 @@ audioPlayer.seek(30000); // Seek to 30000 ms. on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio playback error event. +Subscribes to audio playback error events. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -628,7 +567,7 @@ Subscribes to the audio playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during audio playback.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio playback.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -648,17 +587,17 @@ Enumerates the audio playback states. You can obtain the state through the **sta **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Description | -| ------------------ | ------ | -------------- | -| idle | string | The audio player is idle.| -| playing | string | Audio playback is in progress.| -| paused | string | Audio playback is paused.| -| stopped | string | Audio playback is stopped.| -| error8+ | string | Audio playback is in the error state. | +| Name | Type | Description | +| ------------------ | ------ | ---------------------------------------------- | +| idle | string | No audio playback is in progress.| +| playing | string | Audio playback is in progress. | +| paused | string | Audio playback is paused. | +| stopped | string | Audio playback is stopped. | +| error8+ | string | Audio playback is in the error state. | ## VideoPlayer8+ -Provides APIs to manage and play video. Before calling an API of the **VideoPlayer** class, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. +Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). @@ -668,13 +607,13 @@ 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: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**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. | +| currentTime8+ | number | Yes | No | Current video playback position. | +| duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live mode. | | state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state. | -| width8+ | number | Yes | No | Video width. | -| height8+ | number | Yes | No | Video height. | +| width8+ | number | Yes | No | Video width. | +| height8+ | number | Yes | No | Video height. | ### setDisplaySurface8+ @@ -695,7 +634,7 @@ Sets **SurfaceId**. This API uses a callback to return the result. ```js videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('setDisplaySurface success!'); } else { console.info('setDisplaySurface fail!'); @@ -719,8 +658,8 @@ Sets **SurfaceId**. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------- | ------------------------------ | +| Type | Description | +| -------------- | ------------------------------ | | Promise\ | Promise used to return the result.| **Example** @@ -751,7 +690,7 @@ Prepares for video playback. This API uses a callback to return the result. ```js videoPlayer.prepare((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('prepare success!'); } else { console.info('prepare fail!'); @@ -801,7 +740,7 @@ Starts to play video resources. This API uses a callback to return the result. ```js videoPlayer.play((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('play success!'); } else { console.info('play fail!'); @@ -851,7 +790,7 @@ Pauses video playback. This API uses a callback to return the result. ```js videoPlayer.pause((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('pause success!'); } else { console.info('pause fail!'); @@ -901,7 +840,7 @@ Stops video playback. This API uses a callback to return the result. ```js videoPlayer.stop((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('stop success!'); } else { console.info('stop fail!'); @@ -951,7 +890,7 @@ Switches the video resource to be played. This API uses a callback to return the ```js videoPlayer.reset((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('reset success!'); } else { console.info('reset fail!'); @@ -1002,7 +941,7 @@ Seeks to the specified playback position. The next key frame at the specified po ```js videoPlayer.seek((seekTime, err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('seek success!'); } else { console.info('seek fail!'); @@ -1030,7 +969,7 @@ Seeks to the specified playback position. This API uses a callback to return the ```js videoPlayer.seek((seekTime, seekMode, err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('seek success!'); } else { console.info('seek fail!'); @@ -1094,7 +1033,7 @@ Sets the volume. This API uses a callback to return the result. ```js videoPlayer.setVolume((vol, err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('setVolume success!'); } else { console.info('setVolume fail!'); @@ -1150,7 +1089,7 @@ Releases the video playback resource. This API uses a callback to return the res ```js videoPlayer.release((err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('release success!'); } else { console.info('release fail!'); @@ -1208,7 +1147,7 @@ function printfDescription(obj) { } videoPlayer.getTrackDescription((error, arrlist) => { - if (typeof (arrlist) != 'undefined') { + if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); } @@ -1245,7 +1184,7 @@ function printfDescription(obj) { let arrayDescription; videoPlayer.getTrackDescription().then((arrlist) => { - if (typeof (arrlist) != 'undefined') { + if (arrlist != null) { arrayDescription = arrlist; } else { console.log('video getTrackDescription fail'); @@ -1277,7 +1216,7 @@ Sets the video playback speed. This API uses a callback to return the result. ```js videoPlayer.setSpeed((speed:number, err) => { - if (typeof (err) == 'undefined') { + if (err == null) { console.info('setSpeed success!'); } else { console.info('setSpeed fail!'); @@ -1327,7 +1266,7 @@ Subscribes to the video playback completion event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Type of the event to subscribe to, which is 'playbackCompleted' in this example.| +| type | string | Yes | Event type, which is 'playbackCompleted' in this case.| | callback | function | Yes | Callback invoked when the event is triggered. | **Example** @@ -1350,7 +1289,7 @@ Subscribes to the video buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'bufferingUpdate' in this example. | +| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -1374,7 +1313,7 @@ Subscribes to the frame rendering start event. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'startRenderFrame' in this example.| +| type | string | Yes | Event type, which is 'startRenderFrame' in this case.| | callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -1397,7 +1336,7 @@ Subscribes to the video width and height change event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'videoSizeChanged' in this example.| +| type | string | Yes | Event type, which is 'videoSizeChanged' in this case.| | callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | **Example** @@ -1413,7 +1352,7 @@ videoPlayer.on('videoSizeChanged', (width, height) => { on(type: 'error', callback: ErrorCallback): void -Subscribes to the video playback error event. +Subscribes to video playback error events. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1421,7 +1360,7 @@ Subscribes to the video playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during video playback.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during video playback.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -1432,7 +1371,7 @@ videoPlayer.on('error', (error) => { // Set the 'error' event callback. 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. }); -videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` ## VideoPlayState8+ @@ -1498,7 +1437,7 @@ function printfItemDescription(obj, key) { } audioPlayer.getTrackDescription((error, arrlist) => { - if (typeof (arrlist) != 'undefined') { + if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } @@ -1510,7 +1449,7 @@ audioPlayer.getTrackDescription((error, arrlist) => { ## AudioRecorder -Implements audio recording. Before calling an API of the **AudioRecorder** class, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. +Implements audio recording. Before calling an API of **AudioRecorder**, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). @@ -1528,7 +1467,7 @@ Prepares for recording. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, [encoding format](#audioencoder), sampling rate, number of audio channels, and [output format](#audiooutputformat).| +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Audio recording parameters, including the audio output URI, encoding format, sampling rate, number of audio channels, and output format.| **Example** @@ -1666,7 +1605,7 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- The 'reset' event is triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| +| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset. | | callback | ()=>void | Yes | Callback invoked when the event is triggered. | **Example** @@ -1716,7 +1655,7 @@ audioRecorder.prepare(audioRecorderConfig) on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio recording error event. +Subscribes to audio recording error events. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -1724,7 +1663,7 @@ Subscribes to the audio recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during audio recording.| +| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio recording.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -1746,14 +1685,15 @@ Describes audio recording configurations. | Name | Type | Mandatory| Description | | --------------------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | +| audioEncoder(deprecated) | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**.
**Note**: This parameter is deprecated since API version 8. Use **audioEncoderMime** instead. | | audioEncodeBitRate | number | No | Audio encoding bit rate. The default value is **48000**. | | audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | | 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**. | +| format(deprecated) | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**.
**Note**: This parameter is deprecated since API version 8. Use **fileFormat** instead. | | 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.| -| audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| audioEncoderMime8+ | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | +| fileFormat8+ | [ContainerFormatType](#containerformattype8) | No | Audio encoding format. | ## AudioEncoder(deprecated) @@ -1771,13 +1711,13 @@ Enumerates the audio encoding formats. | 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 defined but not implemented yet.| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| ## AudioOutputFormat(deprecated) > **NOTE** -> This API is deprecated since API version 8. You are advised to use [ContainerFormatType ](#containerformattype8) instead. +> This API is deprecated since API version 8. You are advised to use [ContainerFormatType](#containerformattype8) instead. Enumerates the audio output formats. @@ -1791,643 +1731,6 @@ Enumerates the audio output formats. | 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.| -## VideoRecorder9+ - -Implements video recording. Before calling an API of the **VideoRecorder** class, you must call [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance. - -For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md). - -### Attributes - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Type | Readable| Writable| Description | -| ------------------ | -------------------------------------- | ---- | ---- | ---------------- | -| state8+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| - -### prepare9+ - -prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; - -Sets video recording parameters in asynchronous mode. This API uses a callback to return the result. - -**Required permissions:** ohos.permission.MICROPHONE - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ----------------------------------- | -| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -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 : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// asyncallback -let videoRecorder = null; -let events = require('events'); -let eventEmitter = new events.EventEmitter(); - -eventEmitter.on('prepare', () => { - videoRecorder.prepare(videoConfig, (err) => { - if (typeof (err) == 'undefined') { - console.info('prepare success'); - } else { - console.info('prepare failed and error is ' + err.message); - } - }); -}); - -media.createVideoRecorder((err, recorder) => { - if (typeof (err) == 'undefined' && typeof (recorder) != 'undefined') { - videoRecorder = recorder; - console.info('createVideoRecorder success'); - eventEmitter.emit('prepare'); // Trigger the 'prepare' event. - } else { - console.info('createVideoRecorder failed and error is ' + err.message); - } -}); -``` - -### prepare9+ - -prepare(config: VideoRecorderConfig): Promise\; - -Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. - -**Required permissions:** ohos.permission.MICROPHONE and ohos.permission.CAMERA - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------------- | ---- | ------------------------ | -| config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set.| - -**Return value** - -| Type | Description | -| -------------- | ---------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -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 : 'fd://xx', // The file must be created by the caller and granted with proper permissions. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// promise -let videoRecorder = null; -media.createVideoRecorder().then((recorder) => { - if (typeof (recorder) != 'undefined') { - videoRecorder = recorder; - console.info('createVideoRecorder success'); - } else { - console.info('createVideoRecorder failed'); - } -}).catch((err) => { - console.info('catch err error message is ' + err.message); -}); - -videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); -}).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); -}); -``` - -### getInputSurface9+ - -getInputSurface(callback: AsyncCallback\): void; - -Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. - -Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. - -This API can be called only after [prepare()](#videorecorder_prepare1) is called. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | --------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to obtain the result.| - -**Example** - -```js -// asyncallback -let surfaceID = null; // Surface ID passed to the external system. -videoRecorder.getInputSurface((err, surfaceId) => { - if (typeof (err) == 'undefined') { - console.info('getInputSurface success'); - surfaceID = surfaceId; - } else { - console.info('getInputSurface failed and error is ' + err.message); - } -}); -``` - -### getInputSurface9+ - -getInputSurface(): Promise\; - - Obtains the surface required for recording in asynchronous mode. This surface is provided for the caller. The caller obtains the **surfaceBuffer** from this surface and fills in the corresponding data. - -Note that the video data must carry the timestamp (in ns) and buffer size, and the start time of the timestamp is based on the system startup time. - -This API can be called only after [prepare()](#videorecorder_prepare1) is called. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| ---------------- | -------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -let surfaceID = null; // Surface ID passed to the external system. -videoRecorder.getInputSurface().then((surfaceId) => { - console.info('getInputSurface success'); - surfaceID = surfaceId; -}).catch((err) => { - console.info('getInputSurface failed and catch error is ' + err.message); -}); -``` - -### start9+ - -start(callback: AsyncCallback\): void; - -Starts video recording in asynchronous mode. This API uses a callback to return the result. - -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.start((err) => { - if (typeof (err) == 'undefined') { - console.info('start videorecorder success'); - } else { - console.info('start videorecorder failed and error is ' + err.message); - } -}); -``` - -### start9+ - -start(): Promise\; - -Starts video recording in asynchronous mode. This API uses a promise to return the result. - -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.start().then(() => { - console.info('start videorecorder success'); -}).catch((err) => { - console.info('start videorecorder failed and catch error is ' + err.message); -}); -``` - -### pause9+ - -pause(callback: AsyncCallback\): void; - -Pauses video recording in asynchronous mode. This API uses a callback to return the result. - -This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.pause((err) => { - if (typeof (err) == 'undefined') { - console.info('pause videorecorder success'); - } else { - console.info('pause videorecorder failed and error is ' + err.message); - } -}); -``` - -### pause9+ - -pause(): Promise\; - -Pauses video recording in asynchronous mode. This API uses a promise to return the result. - -This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.pause().then(() => { - console.info('pause videorecorder success'); -}).catch((err) => { - console.info('pause videorecorder failed and catch error is ' + err.message); -}); -``` - -### resume9+ - -resume(callback: AsyncCallback\): void; - -Resumes video recording in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.resume((err) => { - if (typeof (err) == 'undefined') { - console.info('resume videorecorder success'); - } else { - console.info('resume videorecorder failed and error is ' + err.message); - } -}); -``` - -### resume9+ - -resume(): Promise\; - -Resumes video recording in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.resume().then(() => { - console.info('resume videorecorder success'); -}).catch((err) => { - console.info('resume videorecorder failed and catch error is ' + err.message); -}); -``` - -### stop9+ - -stop(callback: AsyncCallback\): void; - -Stops video recording in asynchronous mode. This API uses a callback to return the result. - -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.stop((err) => { - if (typeof (err) == 'undefined') { - console.info('stop videorecorder success'); - } else { - console.info('stop videorecorder failed and error is ' + err.message); - } -}); -``` - -### stop9+ - -stop(): Promise\; - -Stops video recording in asynchronous mode. This API uses a promise to return the result. - -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.stop().then(() => { - console.info('stop videorecorder success'); -}).catch((err) => { - console.info('stop videorecorder failed and catch error is ' + err.message); -}); -``` - -### release9+ - -release(callback: AsyncCallback\): void; - -Releases the video recording resource in asynchronous mode. This API uses a callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.release((err) => { - if (typeof (err) == 'undefined') { - console.info('release videorecorder success'); - } else { - console.info('release videorecorder failed and error is ' + err.message); - } -}); -``` - -### release9+ - -release(): Promise\; - -Releases the video recording resource in asynchronous mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ----------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.release().then(() => { - console.info('release videorecorder success'); -}).catch((err) => { - console.info('release videorecorder failed and catch error is ' + err.message); -}); -``` - -### reset9+ - -reset(callback: AsyncCallback\): void; - -Resets video recording in asynchronous mode. This API uses a callback to return the result. - -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| - -**Example** - -```js -// asyncallback -videoRecorder.reset((err) => { - if (typeof (err) == 'undefined') { - console.info('reset videorecorder success'); - } else { - console.info('reset videorecorder failed and error is ' + err.message); - } -}); -``` - -### reset9+ - -reset(): Promise\; - -Resets video recording in asynchronous mode. This API uses a promise to return the result. - -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the result.| - -**Example** - -```js -// promise -videoRecorder.reset().then(() => { - console.info('reset videorecorder success'); -}).catch((err) => { - console.info('reset videorecorder failed and catch error is ' + err.message); -}); -``` - -### on('error')9+ - -on(type: 'error', callback: ErrorCallback): void - -Subscribes to the video recording error event. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of the event to subscribe to, which is 'error' in this API.
The 'error' event is triggered when an error occurs during video recording.| -| callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | - -**Example** - -```js -videoRecorder.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. -}); -// This event is reported when an error occurs during the retrieval of videoRecordState. -``` - -## VideoRecordState9+ - -Enumerates the video recording states. You can obtain the state through the **state** attribute. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Type | Description | -| -------- | ------ | ---------------------- | -| idle | string | The video recorder is idle. | -| prepared | string | The video recording parameters are set.| -| playing | string | Video recording is in progress. | -| paused | string | Video recording is paused. | -| stopped | string | Video recording is stopped. | -| error | string | Video recording is in the error state. | - -## VideoRecorderConfig9+ - -Describes the video recording parameters. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Type | Mandatory| Description | -| --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | -| videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | -| profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | -| rotation | number | No | Rotation angle of the recorded video. | -| location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| - -## AudioSourceType9+ - -Enumerates the audio source types for video recording. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Value | Description | -| ------------------------- | ---- | ---------------------- | -| AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| -| AUDIO_SOURCE_TYPE_MIC | 1 | Mic audio input source. | - -## VideoSourceType9+ - -Enumerates the video source types for video recording. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------- | -| VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| -| VIDEO_SOURCE_TYPE_SURFACE_ES | 1 | The input surface carries ES data. | - -## VideoRecorderProfile9+ - -Describes the video recording profile. - -**System capability**: SystemCapability.Multimedia.Media.VideoRecorder - -| Name | Type | Mandatory| Description | -| ---------------- | -------------------------------------------- | ---- | ---------------- | -| audioBitrate | number | Yes | Audio encoding bit rate.| -| audioChannels | number | Yes | Number of audio channels.| -| audioCodec | [CodecMimeType](#codecmimetype8) | Yes | Audio encoding format. | -| audioSampleRate | number | Yes | Audio sampling rate. | -| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file.| -| videoBitrate | number | Yes | Video encoding bit rate.| -| videoCodec | [CodecMimeType](#codecmimetype8) | Yes | Video encoding format. | -| videoFrameWidth | number | Yes | Width of the recorded video frame.| -| videoFrameHeight | number | Yes | Height of the recorded video frame.| -| videoFrameRate | number | Yes | Video frame rate. | ## ContainerFormatType8+ @@ -2437,7 +1740,7 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MPEG-4 .| +| 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 17a2f3badd90a7e1431d25bd744b518a3c25fea1..b66eeec85c124ac083b27859849a86e1a5f1d4c2 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -15,6 +15,8 @@ getMediaLibrary(context: Context): MediaLibrary Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. +This API can be used only in the stage model. + **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -29,7 +31,13 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal | ----------------------------- | :---- | | [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| -**Example** +**Example (from API version 9)** + +``` +var media = mediaLibrary.getMediaLibrary(this.context); +``` + +**Example (API version 8)** ``` import featureAbility from '@ohos.ability.featureAbility'; @@ -43,7 +51,11 @@ 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. +This API can be used only in the FA model. + +> **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 @@ -88,12 +100,14 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { +media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { if (fetchFileResult != undefined) { console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); fetchFileResult.getAllObject((err, fileAssetList) => { if (fileAssetList != undefined) { - fileAssetList.forEach(getAllObjectInfo); + fileAssetList.forEach(function(getAllObjectInfo){ + console.info("getAllObjectInfo.displayName :" + getAllObjectInfo.displayName); + }); } }); } @@ -130,8 +144,8 @@ let imagesfetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -mediaLibrary.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ - console.info("getFileAssets successfully:"+ JSON.stringify(dir)); +media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ + console.info("getFileAssets successfully: image number is "+ fetchFileResult.getCount()); }).catch(function(err){ console.info("getFileAssets failed with error:"+ err); }); @@ -155,7 +169,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback **Example** ``` -mediaLibrary.on('imageChange', () => { +media.on('imageChange', () => { // image file had changed, do something }) ``` @@ -177,7 +191,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb **Example** ``` -mediaLibrary.off('imageChange', () => { +media.off('imageChange', () => { // stop listening success }) ``` @@ -209,7 +223,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - mediaLibrary.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { + media.createAsset(mediaType, 'imageCallBack.jpg', path + 'myPicture/', (err, fileAsset) => { if (fileAsset != undefined) { console.info('createAsset successfully, message = ' + err); } else { @@ -246,17 +260,12 @@ Creates a media asset. This API uses a promise to return the result. **Example** ``` -async function example() { - // Create an image file in promise mode. - let mediaType = mediaLibrary.MediaType.IMAGE; - let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; - const path = await media.getPublicDirectory(DIR_IMAGE); - mediaLibrary.createAsset(mediaType, "image01.jpg", path + 'myPicture/').then (function (asset) { - console.info("createAsset successfully:"+ JSON.stringify(asset)); - }).catch(function(err){ - console.info("createAsset failed with error:"+ err); - }); -} +let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; +media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ + console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult)); +}).catch(function(err){ + console.info("getPublicDirectory failed with error:"+ err); +}); ``` ### getPublicDirectory8+ @@ -345,7 +354,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { +media.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { if (albumList != undefined) { const album = albumList[0]; console.info('album.albumName = ' + album.albumName); @@ -385,7 +394,7 @@ let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], }; -mediaLibrary.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ +media.getAlbums(AlbumNoArgsfetchOp).then(function(albumList){ console.info("getAlbums successfully:"+ JSON.stringify(albumList)); }).catch(function(err){ console.info("getAlbums failed with error:"+ err); @@ -434,7 +443,6 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in **Example** ``` -var media = mediaLibrary.getMediaLibrary(context); media.release() ``` @@ -444,7 +452,9 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback<string>) Stores a media asset. This API uses an asynchronous callback to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -480,7 +490,9 @@ storeMediaAsset(option: MediaAssetOption): Promise<string> Stores a media asset. This API uses a promise to return the URI that stores the media asset. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -519,7 +531,9 @@ startImagePreview(images: Array<string>, index: number, callback: AsyncCal Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -561,7 +575,9 @@ startImagePreview(images: Array<string>, callback: AsyncCallback<void&g Starts image preview. This API can be used to preview local images whose URIs start with **dataability://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -601,7 +617,9 @@ startImagePreview(images: Array<string>, index?: number): Promise<void& Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with dataability:// or online images whose URIs start with https://. It uses a promise to return the execution result. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. The **\** component can be used to render and display local and online images. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -646,7 +664,9 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback<Array< Starts media selection. This API uses an asynchronous callback to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -661,7 +681,7 @@ Starts media selection. This API uses an asynchronous callback to return the lis ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { @@ -681,7 +701,9 @@ startMediaSelect(option: MediaSelectOption): Promise<Array<string>> Starts media selection. This API uses a promise to return the list of URIs that store the selected media assets. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, visit [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -701,7 +723,7 @@ Starts media selection. This API uses a promise to return the list of URIs that ``` let option = { - type : "image", + type : "media", count : 2 }; mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { @@ -740,7 +762,7 @@ Provides APIs for encapsulating file asset attributes. | 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. | +| duration8+ | number | Yes | No | Duration, in ms. | | 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. | @@ -766,6 +788,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -801,6 +824,7 @@ Checks whether this file asset is a directory. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -838,6 +862,7 @@ Commits the modification in this file asset to the database. This API uses an as ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -874,6 +899,7 @@ Commits the modification in this file asset to the database. This API uses a pro ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -894,7 +920,11 @@ open(mode: string, callback: AsyncCallback<number>): void Opens this file asset. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -912,7 +942,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw', (openError, fd) => { if(fd > 0){ asset.close(fd); @@ -929,7 +959,11 @@ open(mode: string): Promise<number> Opens this file asset. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +> **NOTE** +> +> Currently, the write operations are mutually exclusive. After the write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -937,7 +971,7 @@ Opens this file asset. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------------------------------- | -| mode | string | Yes | Mode of opening the file, for example, **r** (read-only), **w** (write-only), and **rw** (read-write).| +| mode | string | Yes | Mode of opening the file, for example, **'r'** (read-only), **'w'** (write-only), and **'rw'** (read-write).| **Return value** @@ -952,7 +986,7 @@ async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; const path = await media.getPublicDirectory(DIR_IMAGE); - asset = await media.createAsset(mediaType, "image00003.jpg", path); + const asset = await media.createAsset(mediaType, "image00003.jpg", path); asset.open('rw') .then((fd) => { console.info('File fd!' + fd); @@ -969,7 +1003,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 (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -984,6 +1018,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -993,13 +1028,19 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd, (closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd, (closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1010,7 +1051,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 (when **mode** is set to **'r'**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **'w'**) +**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1030,6 +1071,7 @@ Closes this file asset. This API uses a promise to return the result. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1039,14 +1081,20 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.close(fd).then((closeErr) => { - if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); - console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd).then((closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); - } else { - console.info("=======asset.close success====>"); - } + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); }); } ``` @@ -1071,6 +1119,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1107,6 +1156,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1114,6 +1164,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (err, pixelmap) => { @@ -1148,6 +1199,7 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1155,6 +1207,7 @@ async function example() { order: fileKeyObj.DATE_ADDED + " DESC", extendArgs: "", }; + let size = { width: 720, height: 720 }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size) @@ -1188,6 +1241,7 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1229,6 +1283,7 @@ Favorites or unfavorites this file asset. This API uses a promise to return the ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1266,6 +1321,7 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1305,6 +1361,7 @@ Checks whether this file asset is favorited. This API uses a promise to return t ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1345,6 +1402,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1389,6 +1447,7 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1426,6 +1485,7 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1439,7 +1499,7 @@ async function example() { function isTrashCallBack(err, isTrash) { if (isTrash == true) { console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK isTrash = ' + isTrash); - asset.trash(true, trashCallBack); + asset.trash(true, istrashCallBack); } else { console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessfull = ' + err); @@ -1470,6 +1530,7 @@ Checks whether this file asset is in the trash. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1509,6 +1570,8 @@ Obtains the total number of files in the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE; let getFileCountOneOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [fileType.toString()], @@ -1538,6 +1601,7 @@ Checks whether the cursor is in the last row of the result set. ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1575,6 +1639,7 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1605,6 +1670,7 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1613,12 +1679,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getFirstObject((err, value) => { + fetchFileResult.getFirstObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1641,6 +1707,7 @@ Obtains the first file asset in the result set. This API uses a promise to retur ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1663,8 +1730,6 @@ async function example() { Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1677,6 +1742,7 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1685,12 +1751,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getNextObject((err, value) => { + fetchFileResult.getNextObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1701,8 +1767,6 @@ async function example() { Obtains the next file asset in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Return value** @@ -1715,6 +1779,7 @@ Obtains the next file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1725,7 +1790,7 @@ async function example() { let fetchFileResult = await media.getFileAssets(getImageOp); const fetchCount = fetchFileResult.getCount(); console.info('mediaLibraryTest : count:' + fetchCount); - fileAsset = await fetchFileResult.getNextObject(); + let fileAsset = await fetchFileResult.getNextObject(); } ``` @@ -1747,6 +1812,7 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1755,12 +1821,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getLastObject((err, value) => { + fetchFileResult.getLastObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1783,6 +1849,7 @@ Obtains the last file asset in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1814,6 +1881,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1822,12 +1890,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(0, (err, value) => { + fetchFileResult.getPositionObject(0, (err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1838,8 +1906,6 @@ getPositionObject(index: number): Promise<FileAsset> Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1858,6 +1924,7 @@ Obtains a file asset with the specified index in the result set. This API uses a ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1866,13 +1933,11 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getPositionObject(1, (err, value) => { - if (err) { - console.error('Failed '); - return; - } - console.log(value); - }) + fetchFileResult.getPositionObject(1) .then(function (fileAsset){ + console.log('[Demo] fileAsset.displayName : ' + fileAsset.displayName); + }).catch(function (err) { + console.info("[Demo] getFileAssets failed with error:" + err); + }); } ``` @@ -1882,8 +1947,6 @@ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA - **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** @@ -1896,6 +1959,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1904,12 +1968,12 @@ async function example() { extendArgs: "", }; let fetchFileResult = await media.getFileAssets(getImageOp); - fetchFileResult.getAllObject((err, value) => { + fetchFileResult.getAllObject((err, fileAsset) => { if (err) { console.error('Failed '); return; } - console.log(value); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }) } ``` @@ -1932,6 +1996,7 @@ Obtains all the file assets in the result set. This API uses a promise to return ``` async function example() { + let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -2059,6 +2124,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp, getFileAssetsCallBack); @@ -2098,6 +2167,10 @@ async function example() { selections: '', selectionArgs: [], }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ @@ -2111,8 +2184,9 @@ async function example() { ## PeerInfo8+ Describes information about a registered device. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore | Name | Type | Readable| Writable| Description | | ---------- | -------------------------- | ---- | ---- | ---------------- | @@ -2129,12 +2203,12 @@ Enumerates media types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value| Description| -| ----- | ------ | ---- | -| FILE | 1 | File.| -| IMAGE | 3 | Image.| -| VIDEO | 4 | Video.| -| AUDIO | 5 | Audio.| +| Name | Description| +| ----- | ---- | +| FILE | File.| +| IMAGE | Image.| +| VIDEO | Video.| +| AUDIO | Audio.| ## FileKey8+ @@ -2157,7 +2231,7 @@ Enumerates key file information. | TITLE | title | Title in the file. | | ARTIST | artist | Artist of the file. | | AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in seconds. | +| DURATION | duration | Duration, in ms. | | 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).| @@ -2170,30 +2244,31 @@ 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 | Description | +| ------------- | ------------------ | +| DIR_CAMERA | Directory of camera files.| +| DIR_VIDEO | Directory of video files. | +| DIR_IMAGE | Directory of image files. | +| DIR_AUDIO | Directory of audio files. | +| DIR_DOCUMENTS | Directory of documents. | +| DIR_DOWNLOAD | Download directory. | ## DeviceType8+ Enumerates device types. +This is a system API. -**System capability**: SystemCapability.Multimedia.MediaLibrary.Core +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore -| 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 | Description | +| ------------ | ---------- | +| TYPE_UNKNOWN | Unknown.| +| TYPE_LAPTOP | Laptop.| +| TYPE_PHONE | Phone. | +| TYPE_TABLET | Tablet. | +| TYPE_WATCH | Smart watch. | +| TYPE_CAR | Vehicle-mounted device. | +| TYPE_TV | TV. | ## MediaFetchOptions7+ @@ -2203,9 +2278,9 @@ Describes options for fetching media files. | 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 + '= ?',| +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| +| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | | uri8+ | string | Yes | Yes | No | File URI. | | networkId8+ | string | Yes | Yes | No | Network ID of the registered device. | | extendArgs8+ | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | @@ -2213,6 +2288,7 @@ Describes options for fetching media files. ## Size8+ Describes the image size. +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | -------- | @@ -2223,7 +2299,9 @@ Describes the image size. Implements the media asset option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2238,7 +2316,9 @@ Implements the media asset option. Describes media selection option. -> **NOTE**
This API is deprecated since API version 9. +> **NOTE** +> +> This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 2f052176253fbbe14159bb8551aecbce13cc7de2..2adc09bf03b7dc3f818443eaf0f7ca56abc3439d 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -26,6 +26,7 @@ Sets the media query criteria and returns the corresponding listening handle. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| @@ -37,7 +38,7 @@ Sets the media query criteria and returns the corresponding listening handle. **Example** ```js -listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. ``` @@ -88,10 +89,10 @@ Deregisters a callback with the corresponding query condition by using the handl | callback | Callback<MediaQueryResult> | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| **Example** - ```js + ```ts import mediaquery from '@ohos.mediaquery' - listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. function onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { // do something here @@ -117,10 +118,9 @@ Deregisters a callback with the corresponding query condition by using the handl ### Example -```js +```ts import mediaquery from '@ohos.mediaquery' -let portraitFunc = null @Entry @Component @@ -140,7 +140,7 @@ struct MediaQueryExample { } aboutToAppear() { - portraitFunc = this.onPortrait.bind(this) //bind current js instance + let portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance. this.listener.on('change', portraitFunc) } diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 0884f2a2eaafb587cc7e6e3ff831ba3a3c32d2a8..1305ce8f886430d5797e4e3654d7791d710068fe 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,6 +1,7 @@ # Notification > **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 @@ -2526,12 +2527,12 @@ function onConsumeCallback(data) { let wantAgent = data.wantAgent; wantAgent .getWant(wantAgent) .then((data1) => { - console.log('===> getWant success want:' + JSON.stringfy(data1)); + console.log('===> getWant success want:' + JSON.stringify(data1)); }) .catch((err) => { - console.error('===> getWant failed because' + JSON.stringfy(err)); + console.error('===> getWant failed because' + JSON.stringify(err)); }); - console.info('===> onConsume callback req.wantAgent:' + JSON.stringfy(req.wantAgent)); + console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent)); }; var subscriber = { @@ -3056,7 +3057,7 @@ Notification.subscribe(subscriber, subscribeCallback); | 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. | +| lockscreenVisibility | Yes | Yes | number | No | Mode for displaying the notification on the lock screen. | | vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | | sound | Yes | Yes | string | No | Notification alert tone. | | lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index f0e93479b923928923f27bcda147a7c8d23f0d59..b6e03161522d41099f7372728566e012cfba38e7 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,8 @@ # OS Account Management -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The **osAccount** module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks. + +> **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. @@ -18,7 +20,7 @@ Obtains an **AccountManager** instance. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | --------------------------------- | ------------------------ | | [AccountManager](#accountmanager) | Obtains an **AccountManager** instance.| @@ -48,7 +50,7 @@ Provides methods to manage OS accounts. activateOsAccount(localId: number, callback: AsyncCallback<void>): void -Activates an OS account. This method uses an asynchronous callback to return the result. +Activates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -76,7 +78,7 @@ This is a system API and cannot be called by third-party applications. activateOsAccount(localId: number): Promise<void> -Activates an OS account. This method uses a promise to return the result. +Activates an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -90,7 +92,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to activate.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -111,7 +113,7 @@ This is a system API and cannot be called by third-party applications. isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void -Checks whether multiple OS accounts are supported. This method uses an asynchronous callback to return the result. +Checks whether multiple OS accounts are supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -135,11 +137,11 @@ Checks whether multiple OS accounts are supported. This method uses an asynchron isMultiOsAccountEnable(): Promise<boolean> -Checks whether multiple OS accounts are supported. This method uses a promise to return the result. +Checks whether multiple OS accounts are supported. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -160,7 +162,7 @@ Checks whether multiple OS accounts are supported. This method uses a promise to isOsAccountActived(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account is activated. This method uses an asynchronous callback to return the result. +Checks whether an OS account is activated. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -188,7 +190,7 @@ Checks whether an OS account is activated. This method uses an asynchronous call isOsAccountActived(localId: number): Promise<boolean> -Checks whether an OS account is activated. This method uses a promise to return the result. +Checks whether an OS account is activated. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -200,7 +202,7 @@ Checks whether an OS account is activated. This method uses a promise to return | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -222,7 +224,7 @@ Checks whether an OS account is activated. This method uses a promise to return isOsAccountConstraintEnable(localId: number, constraint: string, callback: AsyncCallback<boolean>): void -Checks whether the specified constraint is enabled for an OS account. This method uses an asynchronous callback to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -251,7 +253,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isOsAccountConstraintEnable(localId: number, constraint: string): Promise<boolean> -Checks whether the specified constraint is enabled for an OS account. This method uses a promise to return the result. +Checks whether the specified constraint is enabled for an OS account. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -264,7 +266,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho | localId | number | Yes | ID of the target OS account. | | constraint | string | Yes | [Constraint](#constraints) specified.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -286,7 +288,7 @@ Checks whether the specified constraint is enabled for an OS account. This metho isTestOsAccount(callback: AsyncCallback<boolean>): void -Checks whether this OS account is a test account. This method uses an asynchronous callback to return the result. +Checks whether this OS account is a test account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -310,11 +312,11 @@ Checks whether this OS account is a test account. This method uses an asynchrono isTestOsAccount(): Promise<boolean> -Checks whether this OS account is a test account. This method uses a promise to return the result. +Checks whether this OS account is a test account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -335,7 +337,7 @@ Checks whether this OS account is a test account. This method uses a promise to isOsAccountVerified(callback: AsyncCallback<boolean>): void -Checks whether this OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether this OS account has been verified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -359,7 +361,7 @@ Checks whether this OS account has been verified. This method uses an asynchrono isOsAccountVerified(localId: number, callback: AsyncCallback<boolean>): void -Checks whether an OS account has been verified. This method uses an asynchronous callback to return the result. +Checks whether an OS account has been verified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -386,7 +388,7 @@ Checks whether an OS account has been verified. This method uses an asynchronous isOsAccountVerified(localId?: number): Promise<boolean> -Checks whether an OS account has been verified. This method uses a promise to return the result. +Checks whether an OS account has been verified. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -398,7 +400,7 @@ Checks whether an OS account has been verified. This method uses a promise to re | ------- | ------ | ---- | ------------------ | | localId | number | No | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------- | :----------------------------------------------------------- | @@ -419,7 +421,7 @@ Checks whether an OS account has been verified. This method uses a promise to re removeOsAccount(localId: number, callback: AsyncCallback<void>): void -Removes an OS account. This method uses an asynchronous callback to return the result. +Removes an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -451,7 +453,7 @@ This is a system API and cannot be called by third-party applications. removeOsAccount(localId: number): Promise<void> -Removes an OS account. This method uses a promise to return the result. +Removes an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -465,7 +467,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the OS account to remove.| -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -491,7 +493,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. This method uses an asynchronous callback to return the result. +Sets or removes constraints for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -522,7 +524,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. This method uses a promise to return the result. +Sets or removes constraints for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -538,7 +540,7 @@ This is a system API and cannot be called by third-party applications. | constraints | Array<string> | Yes | List of [constraints](#constraints) to set or remove.| | enable | boolean | Yes | Set or remove constraints. The value **true** means to set constraints, and **false** means to remove constraints. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -560,7 +562,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string, callback: AsyncCallback<void>): void -Sets a name for an OS account. This method uses an asynchronous callback to return the result. +Sets a name for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -591,7 +593,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountName(localId: number, localName: string): Promise<void> -Sets a name for an OS account. This method uses a promise to return the result. +Sets a name for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -606,7 +608,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | localName | string | Yes | Account name to set. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -629,7 +631,7 @@ This is a system API and cannot be called by third-party applications. getCreatedOsAccountsCount(callback: AsyncCallback<number>): void -Obtains the number of OS accounts created. This method uses an asynchronous callback to return the result. +Obtains the number of OS accounts created. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -655,13 +657,13 @@ Obtains the number of OS accounts created. This method uses an asynchronous call getCreatedOsAccountsCount(): Promise<number> -Obtains the number of OS accounts created. This method uses a promise to return the result. +Obtains the number of OS accounts created. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -682,7 +684,7 @@ Obtains the number of OS accounts created. This method uses a promise to return getOsAccountLocalIdFromProcess(callback: AsyncCallback<number>): void -Obtains the ID of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -706,11 +708,11 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromProcess(): Promise<number> -Obtains the ID of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the ID of the OS account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -731,7 +733,7 @@ Obtains the ID of the OS account to which the current process belongs. This meth getOsAccountLocalIdFromUid(uid: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the process UID. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the process UID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -757,7 +759,7 @@ Obtains the OS account ID based on the process UID. This method uses an asynchro getOsAccountLocalIdFromUid(uid: number): Promise<number> -Obtains the OS account ID based on the process UID. This method uses a promise to return the result. +Obtains the OS account ID based on the process UID. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -767,7 +769,7 @@ Obtains the OS account ID based on the process UID. This method uses a promise t | ------ | ------ | ---- | --------- | | uid | number | Yes | Process UID.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -789,7 +791,7 @@ Obtains the OS account ID based on the process UID. This method uses a promise t getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo, callback: AsyncCallback<number>): void -Obtains the OS account ID based on domain account information. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on domain account information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -799,7 +801,7 @@ Obtains the OS account ID based on domain account information. This method uses | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | -------------------------------------------- | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| **Example** @@ -817,7 +819,7 @@ Obtains the OS account ID based on domain account information. This method uses getOsAccountLocalIdFromDomain(domainInfo: DomainAccountInfo): Promise<number> -Obtains the OS account ID based on domain account information. This method uses a promise to return the result. +Obtains the OS account ID based on domain account information. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -827,9 +829,9 @@ Obtains the OS account ID based on domain account information. This method uses | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ------------ | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -851,7 +853,7 @@ Obtains the OS account ID based on domain account information. This method uses queryMaxOsAccountNumber(callback: AsyncCallback<number>): void -Obtains the maximum number of OS accounts that can be created. This method uses an asynchronous callback to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -877,13 +879,13 @@ This is a system API and cannot be called by third-party applications. queryMaxOsAccountNumber(): Promise<number> -Obtains the maximum number of OS accounts that can be created. This method uses a promise to return the result. +Obtains the maximum number of OS accounts that can be created. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -904,7 +906,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountAllConstraints(localId: number, callback: AsyncCallback<Array<string>>): void -Obtains all constraints enabled for an OS account. This method uses an asynchronous callback to return the result. +Obtains all constraints enabled for an OS account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -932,7 +934,7 @@ Obtains all constraints enabled for an OS account. This method uses an asynchron getOsAccountAllConstraints(localId: number): Promise<Array<string>> -Obtains all constraints enabled for an OS account. This method uses a promise to return the result. +Obtains all constraints enabled for an OS account. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -944,7 +946,7 @@ Obtains all constraints enabled for an OS account. This method uses a promise to | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -966,12 +968,14 @@ Obtains all constraints enabled for an OS account. This method uses a promise to queryAllCreatedOsAccounts(callback: AsyncCallback<Array<OsAccountInfo>>): void -Obtains information about all the OS accounts created. This method uses an asynchronous callback to return the result. +Obtains information about all the OS accounts created. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + **Parameters** | Name | Type | Mandatory| Description | @@ -992,13 +996,15 @@ This is a system API and cannot be called by third-party applications. queryAllCreatedOsAccounts(): Promise<Array<OsAccountInfo>> -Obtains information about all the OS accounts created. This method uses a promise to return the result. +Obtains information about all the OS accounts created. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + +**Return value** | Type | Description | | :---------------------------------------------------------- | :----------------------------------------------------------- | @@ -1019,7 +1025,7 @@ This is a system API and cannot be called by third-party applications. queryActivatedOsAccountIds(callback: AsyncCallback<Array<number>>): void -Obtains information about all activated OS accounts. This method uses an asynchronous callback to return the result. +Obtains information about all activated OS accounts. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1046,11 +1052,11 @@ Obtains information about all activated OS accounts. This method uses an asynchr queryActivatedOsAccountIds(): Promise<Array<number>> -Obtains information about all activated OS accounts. This method uses a promise to return the result. +Obtains information about all activated OS accounts. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------- | :----------------------------------------------------------- | @@ -1071,7 +1077,7 @@ Obtains information about all activated OS accounts. This method uses a promise createOsAccount(localName: string, type: OsAccountType, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account. This method uses an asynchronous callback to return the result. +Creates an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1101,7 +1107,7 @@ This is a system API and cannot be called by third-party applications. createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInfo> -Creates an OS account. This method uses a promise to return the result. +Creates an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1116,7 +1122,7 @@ This is a system API and cannot be called by third-party applications. | localName | string | Yes | Name of the OS account to create.| | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1137,7 +1143,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo, callback: AsyncCallback<OsAccountInfo>): void -Creates an OS account and associates it with the specified domain account. This method uses an asynchronous callback to return the result. +Creates an OS account and associates it with the specified domain account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1150,7 +1156,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| **Example** @@ -1168,7 +1174,7 @@ This is a system API and cannot be called by third-party applications. createOsAccountForDomain(type: OsAccountType, domainInfo: DomainAccountInfo): Promise<OsAccountInfo> -Creates an OS account and associates it with the specified domain account. This method uses a promise to return the result. +Creates an OS account and associates it with the specified domain account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1181,9 +1187,9 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ---------------------- | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1205,7 +1211,7 @@ This is a system API and cannot be called by third-party applications. queryCurrentOsAccount(callback: AsyncCallback<OsAccountInfo>): void -Obtains information about the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains information about the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1231,13 +1237,13 @@ Obtains information about the OS account to which the current process belongs. T queryCurrentOsAccount(): Promise<OsAccountInfo> -Obtains information about the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains information about the OS account to which the current process belongs. This API uses a promise to return the result. **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1258,7 +1264,7 @@ Obtains information about the OS account to which the current process belongs. T queryOsAccountById(localId: number, callback: AsyncCallback<OsAccountInfo>): void -Obtains information about an OS account. This method uses an asynchronous callback to return the result. +Obtains information about an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1288,7 +1294,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountById(localId: number): Promise<OsAccountInfo> -Obtains information about an OS account. This method uses a promise to return the result. +Obtains information about an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1302,7 +1308,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | -------------------- | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1324,7 +1330,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountTypeFromProcess(callback: AsyncCallback<OsAccountType>): void -Obtains the type of the OS account to which the current process belongs. This method uses an asynchronous callback to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1348,11 +1354,11 @@ Obtains the type of the OS account to which the current process belongs. This me getOsAccountTypeFromProcess(): Promise<OsAccountType> -Obtains the type of the OS account to which the current process belongs. This method uses a promise to return the result. +Obtains the type of the OS account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :--------------------------------------------- | :----------------------------------------------------------- | @@ -1373,7 +1379,7 @@ Obtains the type of the OS account to which the current process belongs. This me getDistributedVirtualDeviceId(callback: AsyncCallback<string>): void -Obtains the ID of this distributed virtual device. This method uses an asynchronous callback to return the result. +Obtains the ID of this distributed virtual device. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -1399,13 +1405,13 @@ Obtains the ID of this distributed virtual device. This method uses an asynchron getDistributedVirtualDeviceId(): Promise<string> -Obtains the ID of this distributed virtual device. This method uses a promise to return the result. +Obtains the ID of this distributed virtual device. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC or ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1426,7 +1432,7 @@ Obtains the ID of this distributed virtual device. This method uses a promise to getOsAccountProfilePhoto(localId: number, callback: AsyncCallback<string>): void -Obtains the profile photo of an OS account. This method uses an asynchronous callback to return the result. +Obtains the profile photo of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1456,7 +1462,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountProfilePhoto(localId: number): Promise<string> -Obtains the profile photo of an OS account. This method uses a promise to return the result. +Obtains the profile photo of an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1470,7 +1476,7 @@ This is a system API and cannot be called by third-party applications. | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1492,7 +1498,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string, callback: AsyncCallback<void>): void -Sets a profile photo for an OS account. This method uses an asynchronous callback to return the result. +Sets a profile photo for an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1526,7 +1532,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountProfilePhoto(localId: number, photo: string): Promise<void> -Sets a profile photo for an OS account. This method uses a promise to return the result. +Sets a profile photo for an OS account. This API uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1541,7 +1547,7 @@ This is a system API and cannot be called by third-party applications. | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -**Return Value** +**Return value** | Type | Description | | :------------------ | :---------------------------------- | @@ -1567,7 +1573,7 @@ This is a system API and cannot be called by third-party applications. getOsAccountLocalIdBySerialNumber(serialNumber: number, callback: AsyncCallback<number>): void -Obtains the OS account ID based on the SN. This method uses an asynchronous callback to return the result. +Obtains the OS account ID based on the SN. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1593,7 +1599,7 @@ Obtains the OS account ID based on the SN. This method uses an asynchronous call getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise<number> -Obtains the OS account ID based on the SN. This method uses a promise to return the result. +Obtains the OS account ID based on the SN. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1603,7 +1609,7 @@ Obtains the OS account ID based on the SN. This method uses a promise to return | ------------ | ------ | ---- | ---------- | | serialNumber | number | Yes | Account SN.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1625,7 +1631,7 @@ Obtains the OS account ID based on the SN. This method uses a promise to return getSerialNumberByOsAccountLocalId(localId: number, callback: AsyncCallback<number>): void -Obtains the SN of an OS account based on the account ID. This method uses an asynchronous callback to return the result. +Obtains the SN of an OS account based on the account ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1651,7 +1657,7 @@ Obtains the SN of an OS account based on the account ID. This method uses an asy getSerialNumberByOsAccountLocalId(localId: number): Promise<number> -Obtains the SN of an OS account based on the account ID. This method uses a promise to return the result. +Obtains the SN of an OS account based on the account ID. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -1661,7 +1667,7 @@ Obtains the SN of an OS account based on the account ID. This method uses a prom | ------- | ------ | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| -**Return Value** +**Return value** | Type | Description | | :-------------------- | :----------------------------------------------------------- | @@ -1683,7 +1689,7 @@ Obtains the SN of an OS account based on the account ID. This method uses a prom on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void -Subscribes to OS account changes. This method uses an asynchronous callback to return the result. +Subscribes to OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1713,7 +1719,7 @@ This is a system API and cannot be called by third-party applications. off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void -Unsubscribes from the OS account changes. This method uses an asynchronous callback to return the result. +Unsubscribes from the OS account changes. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1759,7 +1765,7 @@ Defines information about an 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. | -| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | +| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. | ## DomainAccountInfo8+ diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index ae271f2dca80df5c76b96c0e62e32ad7c8285c7e..dc6ca3d13a9339a9eb7aea05158b08ee8db34160 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,53 +1,51 @@ # Prompt +The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + > **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 prompt from '@ohos.prompt' ``` -## Required Permissions - -None. ## prompt.showToast showToast(options: ShowToastOptions): void -Shows the toast. +Shows a 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, - }); - } - } - ``` + +```js +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. | +| 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 value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | ## prompt.showDialog @@ -58,6 +56,7 @@ 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.| @@ -70,76 +69,68 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **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); - }) +```js +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. +Shows a dialog box. This API uses an asynchronous callback to return the result. **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); + +```js +prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', }, - showDialog() { - prompt.showDialog({ - title: 'showDialog Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ] - }, this.callback); + { + text: 'button2', + color: '#000000', } + ] +}, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; } - ``` + console.info('showDialog success callback, click button: ' + data.index); +}); +``` ## ShowDialogOptions @@ -147,11 +138,11 @@ 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.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string| No | Title of the dialog box. | +| message | string| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up 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 @@ -161,7 +152,7 @@ Describes the dialog box response result. | Name | Type | Description | | ----- | ------ | ------------------- | -| index | number | Index of the selected button in the array.| +| index | number | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -173,6 +164,7 @@ Shows an action menu. This API uses a callback to return the result asynchronous **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------- | | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | @@ -180,87 +172,82 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showActionMenu err: ' + err); - return; - } - console.info('showActionMenu success callback, click button: ' + data.index); + +```js +prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', }, - showActionMenu() { - prompt.showActionMenu({ - title: 'Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }, this.callback) - } + { + text: 'item2', + color: '#000000', + }, + ] +}, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; } - ``` + console.info('showActionMenu success callback, click button: ' + data.index); +}) +``` ## prompt.showActionMenu -showActionMenu(options: ActionMenuOptions): Promise\ +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> 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); - }) - } - } - ``` + +```js +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.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string| No | Title of the text to display. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -270,4 +257,15 @@ Describes the action menu response result. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------------------ | -| index | number | No | Index of the selected button in the array, starting from **0**.| +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string| Yes | Button text.| +| color | string| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 8d8b442bcfdfff03f6b1e4214c1033b1061fb00c..fab6d67613fb848d212884d9e9517beacd6e7c2b 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,6 +1,11 @@ -# Reminder Agent +# reminderAgent -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. + +You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. + +> **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. @@ -23,10 +28,10 @@ Publishes an agent-powered reminder. This API uses an asynchronous callback to r **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.| +| 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** ``` @@ -51,17 +56,18 @@ 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 **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the published reminder's ID.| **Example** ``` @@ -276,7 +282,7 @@ reminderAgent.cancelAllReminders().then(() => { addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void -Adds a reminder notification slot. This API uses an asynchronous callback to return the result. +Adds a notification slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -284,7 +290,7 @@ Adds a reminder notification slot. This API uses an asynchronous callback to ret | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| **Example** @@ -307,7 +313,7 @@ export default { data: { mySlot: { addNotificationSlot(slot: NotificationSlot): Promise<void> -Adds a reminder notification slot. This API uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.ReminderAgent @@ -315,7 +321,7 @@ Adds a reminder notification slot. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| +| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| **Return value** @@ -351,7 +357,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| **Example** @@ -378,7 +384,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index d1c0ffc0d035800ab2a68f419555abde627c3fb6..67a0eaac5a895e671717b939a90cc2b0157a49cd 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -85,7 +85,7 @@ Uploads files. This API uses a promise to return the result. ```js let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; let data = { name: "name123", value: "123" }; - let header = { key1: value1, key2: value2 }; + let header = { key1: "value1", key2: "value2" }; let uploadTask; request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { uploadTask = data; @@ -117,7 +117,7 @@ Uploads files. This API uses an asynchronous callback to return the result. ```js let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; let data = { name: "name123", value: "123" }; - let header = { key1: value1, key2: value2 }; + let header = { key1: "value1", key2: "value2" }; let uploadTask; request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { if (err) { @@ -182,7 +182,7 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **headerReceive** (response header). | +| type | string | Yes | Type of the event to subscribe to. The value is **'headerReceive'** (response header). | | callback | function | Yes | Callback for the HTTP Response Header event. | Parameters of the callback function @@ -215,7 +215,7 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **progress** (upload progress). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (upload progress). | | callback | function | No | Callback for the upload progress event. | Parameters of the callback function @@ -249,7 +249,7 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **headerReceive** (response header). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'headerReceive'** (response header). | | callback | function | No | Callback for the HTTP Response Header event. | Parameters of the callback function @@ -452,7 +452,7 @@ Subscribes to the download progress event. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **progress** (download progress). | +| type | string | Yes | Type of the event to subscribe to. The value is **'progress'** (download progress). | | callback | function | Yes | Callback for the download progress event. | Parameters of the callback function @@ -487,7 +487,7 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **progress** (download progress). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (download progress). | | callback | function | No | Callback for the download progress event. | Parameters of the callback function @@ -522,7 +522,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **complete**: download task completion event.
- **pause**: download task pause event.
- **remove**: download task removal event. | +| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | | callback | function | Yes | Callback used to return the result. | **Example** @@ -550,7 +550,7 @@ Unsubscribes from the download event. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **complete**: download task completion event.
- **pause**: download task pause event.
- **remove**: download task removal event. | +| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | | callback | function | No | Callback used to return the result. | **Example** @@ -578,7 +578,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the subscribed event. The value is **fail** (download failure). | +| type | string | Yes | Type of the subscribed event. The value is **'fail'** (download failure). | | callback | function | Yes | Callback for the download task failure event. | Parameters of the callback function @@ -612,7 +612,7 @@ Unsubscribes from the download task failure event. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **fail** (download failure). | +| type | string | Yes | Type of the event to unsubscribe from. The value is **'fail'** (download failure). | | callback | function | No | Callback for the download task failure event. | Parameters of the callback function @@ -948,7 +948,7 @@ Resumes this download task. This API uses an asynchronous callback to return the | enableMetered | boolean | No | Download allowed in metered connections. | | enableRoaming | boolean | No | Download allowed on a roaming network. | | description | string | No | Description of the download session. | -| filePath7+ | string | No | Download path. (The default path is [ERROR:Invalid link:en-us_topic_0000001135742582.xml#xref8132147102215,link:en-us_topic_0000001127125012.xml#section1856519365229](en-us_topic_0000001127125012.xml#section1856519365229)).
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | +| filePath7+ | string | No | Download path. (The default path is **'internal://cache/'**.
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | | networkType | number | No | Network type allowed for download. | | title | string | No | Title of the download session. | diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 40076077bd258dab549dbcb46e16a7137961c107..d258ac2b76fa3babf53469ee2518291919feb1dc 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -115,7 +115,7 @@ Returns to the previous page or a specified page. **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.| +| 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 no URL is set, the previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.| **Example** ```js @@ -162,7 +162,7 @@ Returns to the previous page or a specified page. // Return to the detail page through router.back(). export default { backToDetail() { - router.back({uri:'pages/detail/detail'}); + router.back({url:'pages/detail/detail'}); } } ``` @@ -263,12 +263,6 @@ Enables the display of a confirm dialog box before returning to the previous pag enableAlertBeforeBackPage() { router.enableAlertBeforeBackPage({ message: 'Message Info', - success: function() { - console.log('success'); - }, - fail: function() { - console.log('fail'); - }, }); } } @@ -334,7 +328,7 @@ Obtains the parameters passed from the page that initiates redirection to the cu // detail page export default { onInit() { - console.info('showData1:' + router.getParams().data1); + console.info('showData1:' + router.getParams()[data1]); } } ``` @@ -434,4 +428,5 @@ Describes the page routing options. > ![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-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 1581838feadc1fc7ee462145b1bcd12ccedc98ac..ba3c595df9a8dfdbd76e1f838b6bfd8037932333 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -1,5 +1,6 @@ # RPC +This module implements communication between processes, including inter-process communication (IPC) on a single device and Remote Procedure Call (RPC) between processes of difference devices. IPC is implemented based on the Binder driver, and RPC is based on the software bus driver. > **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. @@ -872,7 +873,7 @@ Writes a String value to this **MessageParcel** object. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | val | string | Yes| String value to write.| + | val | string | Yes| String value to write. The length of the value must be less than 40960 bytes.| **Return value** | Type| Description| @@ -1621,7 +1622,7 @@ Writes a StringArray to this **MessageParcel** object. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | stringArray | string[] | Yes| StringArray to write.| + | stringArray | string[] | Yes| StringArray to write. The length of a single element in the array must be less than 40960 bytes.| **Return value** | Type| Description| @@ -2397,7 +2398,7 @@ Unmarshals this sequenceable object from a **MessageParcel** object. ## IRemoteBroker -Obtains a remote proxy object. +Provides the holder of a remote proxy object. ### asObject @@ -2503,7 +2504,7 @@ Obtains the interface. ### sendRequest(deprecated) > **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8). +> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8). sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index fa0689478926d241372095e4dcb7dcb2e0177b15..bfd0765efaa9a488349351773cfe3eee2ff0e2a1 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,7 +1,9 @@ # Screen Lock Management +The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **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. @@ -17,17 +19,17 @@ import screenlock from '@ohos.screenLock'; isScreenLocked(callback: AsyncCallback<boolean>): void -Checks whether the screen is locked. This method uses an asynchronous callback to return the result. +Checks whether the screen is locked. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If **true** is returned, the screen is locked. If **false** is returned, the screen is not locked. | +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Returns **true** if the screen is locked; returns **false** otherwise.| + +**Example** -- Example - ```js screenlock.isScreenLocked((err, data)=>{ if (err) { @@ -43,17 +45,17 @@ Checks whether the screen is locked. This method uses an asynchronous callback t isScreenLocked(): Promise<boolean> -Checks whether the screen is locked. This method uses a promise to return the result. +Checks whether the screen is locked. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.isScreenLocked().then((data) => { console.log('isScreenLocked success: data -> ${JSON.stringify(data)}'); @@ -68,19 +70,19 @@ Checks whether the screen is locked. This method uses a promise to return the re isSecureMode(callback: AsyncCallback<boolean>): void -Checks whether a device is in secure mode. This method uses an asynchronous callback to return the result. +Checks whether a device is in secure mode. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If **true** is returned, the device is in secure mode. If **false** is returned, the device is not in secure mode. | +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Returns **true** if the device is in secure mode; returns **false** otherwise.| + +**Example** -- Example - ```js screenlock.isSecureMode((err, data)=>{ if (err) { @@ -96,17 +98,17 @@ Checks whether a device is in secure mode. This method uses an asynchronous call isSecureMode(): Promise<boolean> -Checks whether a device is in secure mode. This method uses a promise to return the result. +Checks whether a device is in secure mode. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.isSecureMode().then((data) => { console.log('isSecureMode success: data->${JSON.stringify(data)}'); @@ -121,21 +123,21 @@ Checks whether a device is in secure mode. This method uses a promise to return unlockScreen(callback: AsyncCallback<void>): void -Unlocks the screen. This method uses an asynchronous callback to return the result. +Unlocks the screen. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | Callback function. If the callback fails, an error message is returned. | +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation failed, an error message is returned.| + +**Example** -- Example - ```js - screenlock.unlockScreen((err)=>{ + screenlock.unlockScreen((err) => { if (err) { console.error('unlockScreen callback error -> ${JSON.stringify(err)}'); return; @@ -149,17 +151,17 @@ Unlocks the screen. This method uses an asynchronous callback to return the resu unlockScreen(): Promise<void> -Unlocks the screen. This method uses a promise to return the result. +Unlocks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -- Return Values - | Type | Description | - | -------- | -------- | - | Promise<void> | Promise used to return the result. | +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** -- Example - ```js screenlock.unlockScreen().then(() => { console.log('unlockScreen success'); diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index d3a129c401e466113cc335cb2ce0e63e9a6ce62f..576cda91e2d236a68dc724d8a9ebc14dd96635e7 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,5 +1,5 @@ # Screenshot -Provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. +The **Screenshot** module provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. > **NOTE** > @@ -57,7 +57,7 @@ Describes the size of the screen region to capture. save(options?: ScreenshotOptions, callback: AsyncCallback<image.PixelMap>): void -Takes a screenshot and saves it as a **PixelMap** object. This method uses a callback to return the result. +Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.| +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | **Example** @@ -98,7 +98,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal save(options?: ScreenshotOptions): Promise<image.PixelMap> -Takes a screenshot and saves it as a **PixelMap** object. This method uses a promise to return the result. +Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -108,7 +108,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro | Name | Type | Mandatory| Description | | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.| +| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-securityLabel.md b/en/application-dev/reference/apis/js-apis-securityLabel.md new file mode 100644 index 0000000000000000000000000000000000000000..64afec7faa064ec921777c0ef01a8084c6afbea2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-securityLabel.md @@ -0,0 +1,184 @@ +# Security Label + +The **secuityLabel** module provides APIs to manage file data security levels, including obtaining and setting file data security levels. + +> **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. + +## Modules to Import + +```js +import securityLabel from '@ohos.securityLabel'; +``` + +## Usage + +Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox as follows: + +```js +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); +let path = ''; +context.getFilesDir().then((data) => { + path = data; +}) +``` + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel):Promise<void> + +Sets the security label for a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | File path. | +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Return value** + + | Type | Description | + | ------------------- | ---------------- | + | Promise<void> | Promise used to return the result. An empty value will be returned.| + +**Example** + + ```js + let type = "s4"; + securityLabel.setSecurityLabel(path, type).then(function(){ + console.info("setSecurityLabel successfully"); + }).catch(function(error){ + console.info("setSecurityLabel failed with error:" + error); + }); + ``` + +## securityLabel.setSecurityLabel + +setSecurityLabel(path:string, type:dataLevel, callback: AsyncCallback<void>):void + +Sets the security label for a file in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------------------------------------- | +| path | string | Yes | File path. | +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + + ```js + let type = "s4"; + securityLabel.setSecurityLabel(path, type, function(error){ + console.info("setSecurityLabel:" + JSON.stringify(error)); + }); + ``` +## securityLabel.setSecurityLabelSync + +setSecurityLabelSync(path:string, type:dataLevel):void + +Sets the security label for a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------------------------------- | +| path | string | Yes | File path. | +| type | dataLevel | Yes | File security level, which can be **s0**, **s1**, **s2**, **s3**, or **s4**.| + +**Example** + +```js +let type = "s4"; +securityLabel.setSecurityLabelSync(path, type); +``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string):Promise<string> + +Obtains the security label of a file in asynchronous mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------- | + | path | string | Yes | File path.| + +**Return value** + + | Type | Description | + | --------------------- | ------------ | + | Promise<string> | Promise used to return the security label obtained.| + +**Example** + + ```js + let type = "s4"; + securityLabel.getSecurityLabel(path).then(function(type){ + console.log("getSecurityLabel successfully:" + type); + }).catch(function(error){ + console.log("getSecurityLabel failed with error:" + error); + }); + ``` + +## securityLabel.getSecurityLabel + +getSecurityLabel(path:string, callback:AsyncCallback<string>): void + +Obtains the security label of a file in asynchronous mode. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | -------------------------- | + | path | string | Yes | File path. | + | callback | AsyncCallback<string> | Yes | Callback used to return the security label obtained.| + +**Example** + + ```js + let type = "s4"; + securityLabel.getSecurityLabel(path,function(error, type){ + console.log("getSecurityLabel successfully:" + type); + }); + ``` +## securityLabel.getSecurityLabelSync + +getSecurityLabelSync(path:string):string + +Obtains the security label of a file in synchronous mode. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| path | string | Yes | File path.| + +**Return value** + +| Type | Description | +| ------ | ------------ | +| string | Security label obtained.| + +**Example** + +```js +let result = securityLabel.getSecurityLabelSync(path); +console.log("getSecurityLabel successfully:" + result); +``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index aab544f7f78bd2b755ab24443aa1d0acd5d683c1..d9278e34142be1721540537d4d879c95806f49c4 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -23,8 +23,8 @@ 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**.| @@ -1350,8 +1350,6 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityRes Unsubscribes from sensor data changes. -**Required permission**: ohos.permission.READ_HEALTH_DATA (a system permission) - **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1404,8 +1402,6 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); Unsubscribes from sensor data changes. -**Required permissions**: ohos.permission.ACCELEROMETER (a system permission) - **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1487,6 +1483,8 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerR Unsubscribes from sensor data changes. +**Required permissions**: ohos.permission.ACTIVITY_MOTION + **System capability**: SystemCapability.Sensors.Sensor **Parameters** @@ -1717,7 +1715,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000 console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); return; } - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); }); @@ -1739,7 +1737,7 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| **Example** ```js @@ -1899,7 +1897,6 @@ Obtains the angle change between two rotation matrices. This API uses a callback err.message); return; } - console.info("SensorJsAPI--->Successed to get getAngleModifiy interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -1967,7 +1964,6 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r err.message); return; } - console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -2034,7 +2030,6 @@ Converts a rotation vector into a quaternion. This API uses a callback to return err.message); return; } - console.info("SensorJsAPI--->Successed to get createQuaternion interface get data: " + data.x); for (var i=0; i < data.length; i++) { console.info("data[" + i + "]: " + data[i]); } @@ -2101,7 +2096,6 @@ Obtains the device direction based on the rotation matrix. This API uses a callb err.message); return; } - console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); for (var i = 1; i < data.length; i++) { console.info("sensor_getDirection_callback" + data[i]); } @@ -2169,8 +2163,7 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th err.message); return; } - console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x); - for (var i=0; i < data.length; i++) { + for (var i=0; i < data.rotation.length; i++) { console.info("data[" + i + "]: " + data[i]) } }) @@ -2204,7 +2197,7 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { console.info('createRotationMatrix_promise successed'); - for (var i=0; i < data.length; i++) { + for (var i=0; i < data.rotation.length; i++) { console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { @@ -2418,9 +2411,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 does not exist, and a value greater than **0** means the opposite.| ## MagneticFieldResponse @@ -2430,11 +2423,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 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 f8152d89445f0ef226c3949b4078a30ddf520972..f488e8ce2216dd9f40ea60478f626ae56a70dc8b 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,6 +1,7 @@ # ServiceExtensionContext -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -30,7 +31,7 @@ Starts an ability. This API uses a callback to return the result. "abilityName": "com.example.myapp.MyAbility" }; this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringfy(err)); + console.log('startAbility result:' + JSON.stringify(err)); }); ``` @@ -63,9 +64,9 @@ Starts an ability. This API uses a promise to return the result. "abilityName": "com.example.myapp.MyAbility" }; this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); + console.log('success:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` @@ -88,7 +89,7 @@ Terminates this ability. This API uses a callback to return the result. ```js this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); + console.log('terminateSelf result:' + JSON.stringify(err)); }); ``` @@ -111,9 +112,9 @@ Terminates this ability. This API uses a promise to return the result. ```js this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); + console.log('success:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` @@ -174,7 +175,7 @@ Disconnects this ability from the Service ability. This API uses a callback to r ```js this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. - console.log('terminateSelf result:' + JSON.stringfy(err)); + console.log('terminateSelf result:' + JSON.stringify(err)); }); ``` @@ -203,9 +204,9 @@ Disconnects this ability from the Service ability. This API uses a promise to re ```js this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. - console.log('success:' + JSON.stringfy(data)); + console.log('success:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md b/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md index c45388554dee3107ee10ffcdaa3a5a8c22ad60c6..9993b93f7956278baca3973d6eb85a6b1e94cf67 100644 --- a/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md @@ -239,7 +239,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re ```js this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); + console.log('terminateSelf result:' + JSON.stringify(err)); }); ``` @@ -261,9 +261,9 @@ Terminates this ability. This API uses a promise to return the result. ```js this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); + console.log('success:' + JSON.stringify(data)); }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); + console.log('failed:' + JSON.stringify(error)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 83b3ac3920ac5fe6bca78974f664174157da86b0..4026b305b254548a1b3ce815b4298cf6e858129f 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -21,7 +21,7 @@ getUriSync(name: string): string Obtains the URI of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** @@ -49,7 +49,7 @@ getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: strin Obtains the value of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** | Name| Type| Mandatory| Description| @@ -87,7 +87,7 @@ If the specified data item exists in the database, the **setValueSync** method u **Required permissions**: ohos.permission.WRITE_SYSTEM_SETTING -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index f95061b6337585954abacae035e0b1554376b9bd..fc9109b25611afe452ea32255267b036e71a45b0 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -1,9 +1,9 @@ # statfs -> **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 statfs module provides APIs for obtaining file system information, including the total number of bytes and the number of idle bytes of the file system. -Obtains file system information, including the total number of bytes and the number of idle bytes of the file system. +> **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 @@ -63,7 +63,7 @@ Obtains the number of free bytes of the specified file system in asynchronous mo let context = featureAbility.getContext(); context.getFilesDir().then(function (path) { statfs.getFreeBytes(path, function(err, number){ - console.info("getFreeBytes callback successfully:"+ number); + console.info("Got free bytes successfully:"+ number); }); }); ``` @@ -121,7 +121,7 @@ Obtains the total number of bytes of the specified file system in asynchronous m let context = featureAbility.getContext(); context.getFilesDir().then(function (path) { statfs.getTotalBytes(path, function(err, number){ - console.info("getTotalBytes callback successfully:"+ number); + console.info("Got total bytes successfully:"+ number); }); }); ``` 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 d1b3546f0badde016281ccde39197c2bbad72477..658082d2690c0ab00d76959a1a7ce1c97574ce5d 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,102 +1,117 @@ # App Storage Statistics +The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. + > **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. > - API version 9 is a canary version for trial use. The APIs of this version may be unstable. -> - The APIs of this module are system APIs and cannot be called by third-party applications. - -This module provides functions to obtain storage statistics, including the space of built-in and plug-in memory cards, statistics of application data by type, and application data. ## Modules to Import ```js -import storagestatistics from "@ohos.storageStatistics"; +import storageStatistics from "@ohos.storageStatistics"; ``` -## storagestatistics.getTotalSizeOfVolume +## storageStatistics.getTotalSizeOfVolume getTotalSizeOfVolume(volumeUuid: string): Promise<number> -Asynchronously obtains the total space of the specified volume. This API uses a promise to return the result. +Asynchronously obtains the total size of the specified volume. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | | volumeUuid | string | Yes | UUID of the volume.| -- Return value +**Return value** | Type | Description | | --------------------- | ---------------- | - | Promise<number> | Promise used to return the total space of the volume.| + | Promise<number> | Promise used to return the total size of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getTotalSizeOfVolume(uuid).then(function(number){ + storageStatistics.getTotalSizeOfVolume(uuid).then(function(number){ console.info("getTotalSizeOfVolume successfully:"+ number); }).catch(function(err){ console.info("getTotalSizeOfVolume failed with error:"+ err); }); ``` -## storagestatistics.getTotalSizeOfVolume +## storageStatistics.getTotalSizeOfVolume getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void -Asynchronously obtains the total space of the specified volume. This API uses a callback to return the result. +Asynchronously obtains the total size of the specified volume. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | -------------------------- | | volumeUuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the volume.| + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total size of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getTotalSizeOfVolume(uuid, function(error, number){ + storageStatistics.getTotalSizeOfVolume(uuid, function(error, number){ // Do something. console.info("getTotalSizeOfVolume successfully:"+ number); }); ``` - - -## storagestatistics.getFreeSizeOfVolume +## storageStatistics.getFreeSizeOfVolume getFreeSizeOfVolume(volumeUuid: string): Promise<number> Asynchronously obtains the available space of the specified volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description| | ---------- | ------ | ---- | ---- | | volumeUuid | string | Yes | UUID of the volume.| -- Return value +**Return value** | Type | Description | | --------------------- | ------------------ | | Promise<number> | Promise used to return the available space of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getFreeSizeOfVolume(uuid).then(function(number){ + storageStatistics.getFreeSizeOfVolume(uuid).then(function(number){ console.info("getFreeSizeOfVolume successfully:"+ number); }).catch(function(err){ console.info("getFreeSizeOfVolume failed with error:"+ err); @@ -104,95 +119,421 @@ Asynchronously obtains the available space of the specified volume. This API use ``` -## storagestatistics.getFreeSizeOfVolume +## storageStatistics.getFreeSizeOfVolume getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | ---------------------------- | | volumeUuid | string | Yes | UUID of the volume. | | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the volume.| -- Example +**Example** ```js let uuid = ""; - storagestatistics.getFreeSizeOfVolume(uuid, function(error, number){ + storageStatistics.getFreeSizeOfVolume(uuid, function(error, number){ // Do something. console.info("getFreeSizeOfVolume successfully:"+ number); }); ``` -## storagestatistics.getBundleStats9+ +## storageStatistics.getBundleStats9+ getBundleStats(packageName: string): Promise<BundleStats> -Asynchronously obtains application information. This API uses a promise to return the result. +Asynchronously obtains space information of an application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | -------- | | packageName | string | Yes | Bundle name of the application.| - -- Return value + +**Return value** | Type | Description | | ------------------------------------------ | -------------------------- | - | Promise<[Bundlestats](#bundlestats)> | Promise used to return the application data obtained.| + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained.| -- Example +**Example** ```js let packageName = ""; - storagestatistics.getBundleStats(packageName).then(function(BundleStats){ + storageStatistics.getBundleStats(packageName).then(function(BundleStats){ console.info("getBundleStats successfully:"+ JSON.stringify(BundleStats)); }).catch(function(err){ console.info("getBundleStats failed with error:"+ err); }); ``` -## storagestatistics.getBundleStats9+ +## storageStatistics.getBundleStats9+ getBundleStats(packageName: string, callback: AsyncCallback<BundleStats>): void -Asynchronously obtains application information. This API uses a callback to return the result. +Asynchronously obtains space information of an application. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -- Parameters + +This is a system API and cannot be called by third-party applications. + + +**Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | | packageName | string | Yes | Bundle name of the application.| - | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback used to return the application information obtained.| - -- Example + | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | Yes | Callback invoked to return the space information obtained.| + +**Example** ```js let packageName = ""; - storagestatistics.getBundleStats(packageName, function(error, BundleStats){ + storageStatistics.getBundleStats(packageName, function(error, BundleStats){ // Do something. console.info("getBundleStats successfully:"+ JSON.stringify(BundleStats)); }); ``` +## storageStatistics.getCurrentBundleStats9+ + +getCurrentBundleStats(): Promise<BundleStats> + +Asynchronously obtains space information of the current third-party application. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**Return value** + + | Type | Description | + | ------------------------------------------ | -------------------------- | + | Promise<[Bundlestats](#bundlestats)> | Promise used to return the space information obtained. | + +**Example** + + ```js + let bundleStats = storageStatistics.getCurrentBundleStats(); + console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); + ``` + +## storageStatistics.getCurrentBundleStats9+ + +getCurrentBundleStats(callback: AsyncCallback<BundleStats>): void + +Asynchronously obtains space information of the current third-party application. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + +**Parameters** + + | Name | Type | Mandatory | Description | + | -------- | --------------------------------------------------------- | ---- | ------------------------------------ | + | callback | callback:AsyncCallback<[BundleStats](#bundlestats)> | Yes | Callback invoked to return the space information obtained. | + +**Example** + + ```js + storageStatistics.getCurrentBundleStats(function(error, bundleStats){ + // Do something. + console.info("getCurrentBundleStats successfully:"+ JSON.stringify(bundleStats)); + }); + ``` + ## BundleStats9+ +### Attributes + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + +| Name | Type | Description | +| --------- | ------ | -------------- | +| appSize | number | Size of the application. | +| cacheSize | number | Cache size of the application. | +| dataSize | number | Total data size of the application.| + + +## storageStatistics.getTotalSize9+ + +getTotalSize(): Promise<number> + +Obtains the total space of the built-in memory card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics -### Attribute + +This is a system API and cannot be called by third-party applications. + + +**Return value** + + | Type | Description | + | --------------------- | ------------------ | + | Promise<number> | Promise used to return the total space of the built-in memory card. | + +**Example** + + ```js + let number = storageStatistics.getTotalSize(); + console.info("getTotalSize successfully:"+ JSON.stringify(number)); + ``` + +## storageStatistics.getTotalSize9+ + +getTotalSize(callback: AsyncCallback<number>): void + +Obtains the total space of the built-in memory card. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Parameters** + + | Name | Type | Mandatory | Description | + | -------- | ------------------------------------ | ---- | ------------------------ | + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the total space of the built-in memory card.| + +**Example** + + ```js + storageStatistics.getTotalSize(function(error, number){ + // Do something. + console.info("getTotalSize successfully:"+ JSON.stringify(number)); + }); + ``` + + +## storageStatistics.getFreeSize9+ + +getFreeSize(): Promise<number> + +Obtains the available space of the built-in memory card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Return value** + + | Type | Description | + | --------------------- | ------------------ | + | Promise<number> | Promise used to return the available space of the built-in memory card.| + +**Example** + + ```js + let number = storageStatistics.getFreeSize(); + console.info("getFreeSize successfully:"+ JSON.stringify(number)); + ``` + + +## storageStatistics.getFreeSize9+ + +getFreeSize(callback: AsyncCallback<number>): void + +Obtains the available space of the built-in memory card. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------ | ---- | ------------------------- | + | callback | callback:AsyncCallback<number> | Yes | Callback invoked to return the available space of the built-in memory card.| + +**Example** + + ```js + storageStatistics.getFreeSize(function(error, number){ + // Do something. + console.info("getFreeSize successfully:"+ JSON.stringify(number)); + }); + ``` + +## storageStatistics.getSystemSize9+ + +getSystemSize(): Promise<number> + +Asynchronously obtains the system space. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Return value** + + | Type | Description | + | --------------------- | ---------------- | + | Promise<number> | Promise used to return the system space obtained.| + +**Example** + + ```js + storageStatistics.getSystemSize().then(function(number){ + console.info("getSystemSize successfully:"+ number); + }).catch(function(err){ + console.info("getSystemSize failed with error:"+ err); + }); + ``` + +## storageStatistics.getSystemSize9+ + +getSystemSize(callback:AsyncCallback<number>):void + +Asynchronously obtains the system space. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | callback | callback:AsyncCallback<number> | Yes | Callback used to return the system space obtained.| + +**Example** + + ```js + storageStatistics.getSystemSize(function(error, number){ + // Do something. + console.info("getSystemSize successfully:"+ number); + }); + ``` + +## storageStatistics.getUserStorageStats9+ + +getUserStorageStats(userId? : number): Promise<StorageStats> + +Asynchronously obtains the space occupied by each type of user data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Parameters** + + | Name | Type | Mandatory| Description| + | ---------- | ------ | ---- | ---- | + | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried.| + +**Return value** + + | Type | Description | + | --------------------- | ---------------- | + | Promise<[StorageStats](#StorageStats)> | Promise used to return the information obtained.| + +**Example** + + ```js + let userId = 1; + storageStatistics.getUserStorageStats(userId).then(function(StorageStats){ + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }).catch(function(err){ + console.info("getUserStorageStats failed with error:"+ err); + }); + ``` + +## storageStatistics.getUserStorageStats9+ + +getUserStorageStats(userId: number, callback:AsyncCallback<StorageStats>):void + +Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. + + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | userId | number | No | User ID.
Value:
-  Set this parameter to the ID of the user to be queried.
-  If no value is specified, information about the current user is queried. | + | callback | callback:AsyncCallback<[StorageStats](#StorageStats)> | Yes | Callback invoked to return the information obtained.| + +**Example** + + ```js + let userId = 1; + storageStatistics.getUserStorageStats(userId, function(error, StorageStats){ + // Do something. + console.info("getUserStorageStats successfully:"+ JSON.stringify(StorageStats)); + }); + ``` + + +## StorageStats9+ + +### Attributes + +**System capability**: SystemCapability.FileManagement.StorageService.SpatialStatistics + + +This is a system API and cannot be called by third-party applications. | Name | Type | Description | | --------- | ------ | -------------- | -| appSize9+ | number | Size of the application. | -| cacheSize9+ | number | Cache size of the application. | -| dataSize9+ | number | Total data size of the application.| +| total | number | Total space of the built-in memory card. | +| audio | number | Space occupied by audio data. | +| video | number | Space occupied by video data.| +| image | number | Space occupied by image data. | +| file | number | Space occupied by files. | +| app | number | Space occupied by application data.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 7b577c8ee81c733cdb1aa1f2ccfcced87829f304..5ec8dacc2ed7a88010e2156b6f82be3a4f9557e2 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,7 +1,7 @@ # 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. +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.batteryInfo`](js-apis-battery-info.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -22,20 +22,13 @@ Obtains the current charging state and battery level. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| 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. | +| success | (data: [BatteryResponse](#batteryresponse)) => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| **Example** @@ -52,4 +45,11 @@ export default { }); }, } -``` \ No newline at end of file +``` + +## BatteryResponse + +| Name| Type| Description| +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged.| +| level | number | Current battery level, which ranges from **0.00** to **1.00**.| diff --git a/en/application-dev/reference/apis/js-apis-system-bluetooth.md b/en/application-dev/reference/apis/js-apis-system-bluetooth.md index 22aeb61ce6a2a1184c3e9b978073f504953534c3..a8c77cd86a20c0401d01ce1e54a61c58c7aace17 100644 --- a/en/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -120,19 +120,12 @@ Subscribes to the newly detected BLE device. If this API is called multiple time **Example** ``` - bluetooth.startBLEScan({ - success() { - bluetooth.subscribeBLEFound({ - success(data) { - const [device] = data.devices; - if (!!device) { - bluetooth.stopBLEScan(); - } - } - }); + bluetooth.subscribeBLEFound({ + success(data) { + console.log('Called bluetooth.subscribeBLEFound successsully, data: ${data}.'); }, - fail(code, data) { - console.log('Failed to start BLE device scan, code: ${code}, data: ${data}'); + fail(data, code) { + console.log('Failed to call bluetooth.startBLEScan, data: ${data}, code: ${code}.'); } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 3b1731b865d28bab4708e8613e6969529ed21cb9..9efb0b0a3b3a4aa3103204b1b41b273bae8398f3 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,7 +1,7 @@ # 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. +> **NOTE** +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.brightness`](js-apis-brightness.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -24,34 +24,35 @@ Obtains the current screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| 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 | +| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| -The following values will be returned when the operation is successful. +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| value | number | Screen brightness, which ranges from 1 to 255. | +| value | number | Screen brightness. The value is an integer ranging from **1** to **255**.| + **Example** -```js -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); - }, - }); - }, -} -``` + ```js + 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 @@ -64,30 +65,30 @@ Sets the screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| 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. | +| 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 | () => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| **Example** -```js -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); - }, - }); - }, -} -``` + ```js + 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 @@ -100,34 +101,34 @@ Obtains the screen brightness adjustment mode. **Parameters** -| Name | Type | Mandatory | Description | +| 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 | +| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| -The following values will be returned when the operation is successful. +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| mode | number | The value can be **0** or **1**.
- **0**: manual adjustment
- **1**: automatic adjustment| **Example** -```js -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); - }, - }); - }, -} -``` + ```js + 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 @@ -139,31 +140,30 @@ Sets the screen brightness adjustment mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** - -| Name | Type | Mandatory | Description | +| 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. | +| mode | number | Yes| The value can be **0** or **1**.
- **0**: manual adjustment
- **1**: automatic adjustment| +| success | () => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| **Example** -```js -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); - }, - }); - }, -} -``` + ```js + 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 @@ -175,28 +175,40 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. **System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** - -| Name | Type | Mandatory | Description | +| 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. | +| keepScreenOn | boolean | Yes| Whether to keep the screen on.| +| success | () => void | No| Called when API call is successful.| +| fail | (data: string, code: number) => void | No| Called when API call has failed.| +| complete | () => void | No| Called when API call is complete.| **Example** -```js -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 + ```js + 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); + }, + }); + }, + } + ``` +## + +## BrightnessResponse + +| Name| Type | Description| +| -------- | -------- | -------- | +| value | number | Screen brightness. The value is an integer ranging from **1** to **255**.| + +## BrightnessModeResponse + +| Name| Type | Description| +| -------- | -------- | -------- | +| mode | number | The value can be **0** or **1**.
- **0**: manual adjustment
- **0**: manual adjustment| diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index b29842197c897d8dcb50d120f9f6c5a8a8ecce17..cd4100d455e6f47f6d2600562a4d0522c885284a 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -25,8 +25,8 @@ Encrypts or decrypts data using RSA. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| | transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | success | Function | No| Called when data is encrypted or decrypted successfully.| @@ -44,48 +44,53 @@ export default { // Text 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}`); - } + key: + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx414QSP3RsYWYzf9mkBMiBAXo\n' + + '6S7Lpva1fKlcuVxjoFC1iMnzD4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ\n' + + '+Enz0RzmVFh/4yk6lmqRzuEFQqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBw\n' + + 'jBpApTJ3TeneOo6Z5QIDAQAB', + success: function(data) { + console.log(`Handling successful:${data.text}`); + }, + fail: function(data, code) { + console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + }, + complete: function() { + console.log(`operation complete!`); + } }); cipher.rsa({ // Decrypt data. action: 'decrypt', // Text to be decrypted, which is binary text encoded in Base64. The decrypted text is "hello". text: - 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + - 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + - 'S/ZWNI4Q8Q0suNjNkGU=', + 'EPeCFPib6ayKbA0M6oSywARvFZ8dFYfjQv3nY8ikZGtS9UHq2sLPvAfpeIzggSiCxqbWeCftP1XQ\n' + + 'Sa+jEpzFlT1qoSTunBbrYzugPTajIJDTg6R1IRsF/J+mmakn0POVPvi4jCo9wqavB324Bx0Wipnc\n' + + 'EU5WO0oBHo5l4x6dTpU=', // Base64-encoded private key used for decryption. 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}`); - }, + 'MIICXgIBAAKBgQCx414QSP3RsYWYzf9mkBMiBAXo6S7Lpva1fKlcuVxjoFC1iMnz\n' + + 'D4mC0uiL4k5MNi43J64c7dbqi3qAJjdAtuwQ6NZJ+Enz0RzmVFh/4yk6lmqRzuEF\n' + + 'QqhQqSZzaLq6sq2N2G0Sv2Xl3sLvqAfe2HNm2oBwjBpApTJ3TeneOo6Z5QIDAQAB\n' + + 'AoGBAKPNtoRQcklxqo+2wQP0j2m3Qqnib1DggjVEgb/8f/LNYQSI3U2QdROemryU\n' + + 'u3y6N3xacZ359PktTrRKfH5+8ohmHGhIuPAnefp6bLvAFUcl4t1xm74Cow62Kyw3\n' + + 'aSbmuTG98dxPA1sXD0jiprdtsq2wQ9CoKNyY7/d/pKoqxNuBAkEA4GytZ60NCTj9\n' + + 'w24jACFeko5YqCFY/TTLoc4SQvWtFMnimRPclLZhtUIK0P8dib71UFedx+AxklgL\n' + + 'A5gjcfo+2QJBAMrqiwyCh3OQ5DhyRPDwt87x1/jg5fy4hhete2ufSf2FoQCVqO+w\n' + + 'PKoljdXmJeS6rGgzGibstuHLrP3tcIho4+0CQD3ZFWzF/xq0jxKlrpWhnJuNCRfE\n' + + 'oO6e9yNvVA8J/5oEDSOcmqSNIp4+RhbUx8InUxnCG6Ryv5aSFu71pYcKrPkCQQCL\n' + + 'RUGcm3ZGTnslduB0knNF+V2ndwzDUQ7P74UXT+PjurTPhujFYiuxCEd6ORVnEOzG\n' + + 'M9TORIgdH8MjIbWsGnndAkEAw9yURDaorE8IYPLF2IEn09g1uzvWPs3phDb6smVx\n' + + '8GfqIdUNf+aCG5TZK/kXBF1sqcsi7jXMAf4jBlejVbSVZg==', + success: function(data) { + console.log(`Handling successful:${data.text}`); + }, + fail: function(data, code) { + console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + }, + complete: function() { + console.log(`operation complete!`); + } }); } } @@ -104,13 +109,13 @@ Encrypts or decrypts data using AES. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| | transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| | iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| -| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**.| -| ivLen | string | No| Length of the IV for AES-based encryption and decryption, in bytes. The default value is **16**.| +| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported.| +| ivLen | string | No| Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.| | 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.| @@ -125,38 +130,41 @@ export default { action: 'encrypt', // Text to be encrypted. text: 'hello', - // Base64-encoded key used for encryption. + // Base64-encoded key. 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}`); - } + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`Handling successful:${data.text}`); + }, + fail: function(data, code) { + console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + }, + complete: function() { + console.log(`operation complete!`); + } }); cipher.aes({ // Decrypt data. action: 'decrypt', // Text to be decrypted, which is binary text encoded in Base64. - text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + - 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + - 'S/ZWNI4Q8Q0suNjNkGU=', - // Base64-encoded key used for decryption. + text: '1o0kf2HXwLxHkSh5W5NhzA==', + // Base64-encoded key. 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}`) - }) - }, + ivOffset: '0', + ivLen: '16', + success: function(data) { + console.log(`Handling successful:${data.text}`); + }, + fail: function(data, code) { + console.log(`### Failed to decrypt cipher.rsa ### ${code}:${data}`); + }, + complete: function() { + console.log(`operation complete!`); + } + }); }); } } diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md index f2057a86685a5d212e84caf27e69468b8169c267..920005544cbe9f696cccbdffe2acea56f2021533 100644 --- a/en/application-dev/reference/apis/js-apis-system-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -1,7 +1,8 @@ # Media Query -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + +> **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. @@ -38,11 +39,7 @@ Creates a **MediaQueryList** object based on the query condition. **Example** ``` -export default { - matchMedia() { - var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); - }, -} +var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); ``` ## MediaQueryEvent @@ -95,11 +92,16 @@ Adds a listener for this **MediaQueryList** object. The listener must be added b | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(){ + if(e.mathes){ + // do something + } +} mMediaQueryList.addListener(maxWidthMatch); ``` @@ -108,7 +110,7 @@ mMediaQueryList.addListener(maxWidthMatch); removeListener(callback: (event: MediaQueryEvent) => void): void -Removes the listener for this **MediaQueryList** object. +Removes the listener for this **MediaQueryList** object. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -116,10 +118,15 @@ Removes the listener for this **MediaQueryList** object. | Name | Type | Mandatory | Description | | -------- | --------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(){ + if(e.mathes){ + // do something + } +} mMediaQueryList.removeListener(maxWidthMatch); ``` diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index 0f1f932efe54af1337ce19354d19343b6f637687..c94547dba319f8660ceea73e5f7a5ecfb79fb3b4 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -66,6 +66,7 @@ export default { ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> > The page routing stack supports a maximum of 32 pages. @@ -182,6 +183,7 @@ export default { ``` > ![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 @@ -375,8 +377,8 @@ Defines the **EnableAlertBeforeBackPage** parameters. | 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.| +| success | (errMsg: string) => void | No | Called when the **OK** button in the confirm dialog box is clicked. **errMsg** indicates the returned information. | +| cancel | (errMsg: string) => void | No | Called when the **Cancel** button in the confirm dialog box is clicked. **errMsg** indicates the returned information. | | complete | () => void | No | Called when the API call is complete. | ## DisableAlertBeforeBackPageOptions6+ @@ -387,8 +389,8 @@ Define the **DisableAlertBeforeBackPage** parameters. | 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.| +| success | (errMsg: string) => void | No | Called when the dialog box is closed. **errMsg** indicates the returned information. | +| cancel | (errMsg: string) => void | No | Called when the dialog box fails to be closed. **errMsg** indicates the returned information. | | complete | () => void | No | Called when the API call is complete. | ## ParamsInterface diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index d144a95db8f59ca0605fd228b351380afe6feac8..cf8ca596bd72517835c6bd277c0bf29ebf2b7213 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -1,19 +1,19 @@ # Timer +The **Timer** module provides basic timer capabilities. You can use the APIs of this module to execute functions at the specified time. -## setTimeout - -## Modules to Import +> **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. - -``` -import Time from '@ohos.Time'; -``` +## setTimeout setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -30,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off. **Example** -```js -export default { - setTimeOut() { - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); + ```js + export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); + } } -} -``` + ``` ## clearTimeout @@ -47,6 +47,8 @@ clearTimeout(timeoutID: number): void Cancels the timer created via **setTimeout()**. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -55,16 +57,16 @@ Cancels the timer created via **setTimeout()**. **Example** -```js -export default { - clearTimeOut() { - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - clearTimeout(timeoutID); + ```js + export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); + } } -} -``` + ``` ## setInterval @@ -73,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -89,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i **Example** -```js -export default { - setInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); + ```js + export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + } } -} -``` + ``` ## clearInterval @@ -106,6 +110,8 @@ clearInterval(intervalID: number): void Cancels the repeating timer set via **setInterval()**. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -114,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**. **Example** -```js -export default { - clearInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - clearInterval(intervalID); + ```js + export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); + } } -} -``` \ No newline at end of file + ``` diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index 971d25f95d622ee681abff44ffb97ff9b3524572..147cbb7c36120e4ffca27ac710915d683bee1ee4 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,7 +1,16 @@ # 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. +The **UiTest** module provides APIs that you can use to simulate UI actions during testing, such as clicks, double-clicks, long-clicks, and swipes. + +This module provides the following functions: + +- [By](#by): provides UI component feature description APIs for component filtering and matching. +- [UiComponent](#uicomponent): 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. +- [UiDriver](#uidriver): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. + +>**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 @@ -12,14 +21,14 @@ 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 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:
1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [By.isBefore](#byisbefore) and [By.isAfter](#byisafter) 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. ```js BY.text('123').type('button') ``` -### By.text +### text text(txt: string, pattern?: MatchPattern): By @@ -128,11 +137,11 @@ let by = BY.type('button') // Use the static constructor BY to create a By objec ``` -### By.clickable +### clickable clickable(b?: bool): By -Specifies the clickable attribute of the target component. +Specifies the clickable status of the target component. **System capability**: SystemCapability.Test.UiTest @@ -151,7 +160,7 @@ Specifies the clickable attribute of the target component. **Example** ```js -let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable status attribute of the target component. +let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable status of the target component. ``` @@ -159,7 +168,7 @@ let by = BY.clickable(true) // Use the static constructor BY to create a By obje scrollable(b?: bool): By -Specifies the scrollable status attribute of the target component. +Specifies the scrollable status of the target component. **System capability**: SystemCapability.Test.UiTest @@ -178,14 +187,14 @@ Specifies the scrollable status attribute of the target component. **Example** ```js -let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable status attribute of the target component. +let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable status of the target component. ``` ### By.enabled enabled(b?: bool): By -Specifies the enabled status attribute of the target component. +Specifies the enabled status of the target component. **System capability**: SystemCapability.Test.UiTest @@ -204,14 +213,14 @@ Specifies the enabled status attribute of the target component. **Example** ```js -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enabled status attribute of the target component. +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enabled status of the target component. ``` ### By.focused focused(b?: bool): By -Specifies the focused status attribute of the target component. +Specifies the focused status of the target component. **System capability**: SystemCapability.Test.UiTest @@ -230,14 +239,14 @@ Specifies the focused status attribute of the target component. **Example** ```js -let by = BY.focused(true) // Use the static constructor BY to create a By object and specify the focused status attribute of the target component. +let by = BY.focused(true) // Use the static constructor BY to create a By object and specify the focused status of the target component. ``` ### By.selected selected(b?: bool): By -Specifies the selected status attribute of the target component. +Specifies the selected status of the target component. **System capability**: SystemCapability.Test.UiTest @@ -256,7 +265,7 @@ Specifies the selected status attribute of the target component. **Example** ```js -let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected status attribute of the target component. +let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected status of the target component. ``` ### By.isBefore @@ -316,6 +325,7 @@ let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a 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 in this class use a promise to return the result and must be invoked using **await**. + ### UiComponent.click click(): Promise\ @@ -639,7 +649,7 @@ async function demo() { ### UiComponent.scrollSearch -scrollSearch(by: By): Promise\ +scrollSearch(by:By): Promise\ Scrolls on this component to search for the target component (applicable to component that support scrolling, such as **\**). @@ -667,12 +677,14 @@ async function demo() { } ``` + + ## 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. +The **UiDriver** class is the main entry to the UiTest 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 +### create static create(): UiDriver @@ -746,7 +758,7 @@ async function demo() { } ``` -### UiDriver.findComponents +### findComponents findComponents(by: By): Promise\> @@ -850,8 +862,8 @@ Clicks a specific point of this **UiDriver** object based on the given coordinat | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| **Example** @@ -874,8 +886,8 @@ Double-clicks a specific point of this **UiDriver** object based on the given co | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| **Example** @@ -886,7 +898,7 @@ async function demo() { } ``` -### UiDriver.longClick +### longClick longClick(x: number, y: number): Promise\ @@ -898,8 +910,8 @@ Long-clicks a specific point of this **UiDriver** object based on the given coor | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| **Example** @@ -912,7 +924,7 @@ async function demo() { ### UiDriver.swipe -swipe(startx: number, starty: number, endx: number, endy: number): Promise\ +swipe(startx: number, starty: number, endx: number, endy: number, speed: number): Promise\ Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. @@ -920,12 +932,13 @@ Swipes on this **UiDriver** object from the start point to the end point based o **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------------- | -| startx | number | Yes | X coordinate of the start point.| -| starty | number | Yes | Y coordinate of the start point.| -| endx | number | Yes | X coordinate of the end point.| -| endy | number | Yes | Y coordinate of the end point.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| startx | number | Yes | X-coordinate of the start point. | +| starty | number | Yes | Y-coordinate of the start point. | +| endx | number | Yes | X-coordinate of the end point. | +| endy | number | Yes | Y-coordinate of the end point. | +| speed | number | No | Scroll speed, in pixels/s. The default value is **600**.| **Example** @@ -965,6 +978,7 @@ async function demo() { } ``` + ## MatchPattern Enumerates the match patterns supported for component attributes. @@ -977,5 +991,3 @@ Enumerates the match patterns supported for component attributes. | CONTAINS | 1 | Containing the given value. | | STARTS_WITH | 2 | Starting from the given value.| | ENDS_WITH | 3 | Ending with the given value.| - -### diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 5f8c2b898204cbddd2c78ee2f50d17afa7af67a6..71b0490ea8c610dc0169222042ec7770c19d0a83 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,6 +1,9 @@ # USB -> **NOTE**
+This module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. + +> **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 @@ -126,8 +129,8 @@ Checks whether the application has the permission to access the device. - **Example** ```js - let divicesName="1-1"; - let bool = usb.hasRight(divicesName); + let devicesName="1-1"; + let bool = usb.hasRight(devicesName); console.log(bool); ``` @@ -152,8 +155,8 @@ Requests the temporary permission for the application to access the USB device. - **Example** ```js - let divicesName="1-1"; - usb.requestRight(divicesName).then((ret) => { + let devicesName="1-1"; + usb.requestRight(devicesName).then((ret) => { console.log(`requestRight = ${JSON.stringify(ret)}`); }); ``` @@ -248,7 +251,7 @@ setInterface(pipe: USBDevicePipe, iface: USBInterface): number Sets a USB interface. -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface.. +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim a USB interface.. **System capability**: SystemCapability.USB.USBManager @@ -358,7 +361,7 @@ bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, tim Performs bulk transfer. -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim a USB interface. **System capability**: SystemCapability.USB.USBManager @@ -379,7 +382,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi ```js // Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. - // Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. + // Call usb.claimInterface to claim a USB interface. After that, call usb.bulkTransfer to start bulk transfer. usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { console.log(`bulkTransfer = ${JSON.stringify(ret)}`); }); diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index fbe459992c0eff76a99d15ad8116913f761ad892..87cfad2f83ba3c25d4ab90a874777d86bb2cd473 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -1,13 +1,13 @@ # Volume Management +The volumeManager module provides APIs for volume and disk management, including obtaining volume information, mounting or unmounting volumes, partitioning disks, and formatting volumes. + > **NOTE**
> > - The initial APIs of this module are supported since API version 9. > - API version 9 is a canary version for trial use. The APIs of this version may be unstable. > - The APIs of this module are system APIs and cannot be called by third-party applications. -Performs volume and disk management, including obtaining volume information, mounting and unmounting volumes, partitioning disks, and formatting volumes. - ## Modules to Import ```js @@ -20,19 +20,21 @@ getAllVolumes(): Promise<Array<Volume>> Asynchronously obtains information about all available volumes. This API uses a promise to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Return value +**Return value** | Type | Description | | ---------------------------------- | -------------------------- | | Promise<[Volume](#volume)[]> | Promise used to return the execution result.| -- Example +**Example** ```js volumemanager.getAllVolumes().then(function(volumes){ - // do something + // Do something. }); ``` @@ -42,20 +44,22 @@ getAllVolumes(callback: AsyncCallback<Array<Volume>>): void Asynchronously obtains information about all available volumes. This API uses a callback to return the result. +**Required permissions**: ohos.permission.STORAGE_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | | callback | callback:AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| - -- Example + +**Example** ```js let uuid = ""; volumemanager.getAllVolumes(function(error, volumes){ - // do something + // Do something }); ``` @@ -66,26 +70,28 @@ mount(volumeId: string): Promise<boolean> Asynchronously mounts a volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description| | -------- | ------ | ---- | ---- | | volumeId | string | Yes | Volume ID.| -- Return value +**Return value** | Type | Description | | ---------------------- | ---------- | | Promise<boolean> | Promise used to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.mount(volumeId).then(function(flag){ - // do something + // Do something }); ``` @@ -95,21 +101,23 @@ mount(volumeId: string, callback:AsyncCallback<boolean>):void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.mount(volumeId, function(error, flag){ - // do something + // Do something }); ``` @@ -119,26 +127,28 @@ unmount(volumeId: string): Promise<boolean> Asynchronously unmounts a volume. This API uses a promise to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description| | -------- | ------ | ---- | ---- | | volumeId | string | Yes | Volume ID.| -- Return value +**Return value** | Type | Description | | ---------------------- | ---------- | | Promise<boolean> | Promise used to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.unmount(volumeId).then(function(flag){ - // do something + // Do something }); ``` @@ -148,21 +158,330 @@ unmount(volumeId: string, callback:AsyncCallback<boolean>):void Asynchronously unmounts a volume. This API uses a callback to return the result. +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + **System capability**: SystemCapability.FileManagement.StorageService.Volume -- Parameters +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| -- Example +**Example** ```js let volumeId = ""; volumemanager.unmount(volumeId, function(error, flag){ - // do something + // Do something + }); + ``` + +## volumemanager.getVolumeByUuid + +getVolumeByUuid(uuid: string): Promise<Volume> + +Asynchronously obtains volume information based on the universally unique identifier (UUID). This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | -------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + +**Return value** + + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Example** + + ```js + let uuid = ""; + volumemanager.getVolumeByUuid(uuid).then(function(volume) { + console.info("getVolumeByUuid successfully:" + JSON.stringify(volume)); + }).catch(function(error){ + console.info("getVolumeByUuid failed with error:"+ error); + }); + ``` + +## volumemanager.getVolumeByUuid + +getVolumeByUuid(uuid: string, callback: AsyncCallback<Volume>): void + +Asynchronously obtains volume information based on the UUID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------------------ | ---- | -------------------- | + | uuid | string | Yes | UUID of the volume. | + | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + +**Example** + + ```js + let uuid = ""; + volumemanager.getVolumeByUuid(uuid, (error, volume) => { + // Do something. + }); + ``` + +## volumemanager.getVolumeById + +getVolumeById(volumeId: string): Promise<Volume> + +Asynchronously obtains volume information based on the volume ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory | Description| + | -------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| + +**Return value** + + | Type | Description | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)> | Promise used to return the volume information obtained.| + +**Example** + + ```js + let volumeId = ""; + volumemanager.getVolumeById(volumeId).then(function(volume) { + console.info("getVolumeById successfully:" + JSON.stringify(volume)); + }).catch(function(error){ + console.info("getVolumeById failed with error:"+ error); + }); + ``` + +## volumemanager.getVolumeById + +getVolumeById(volumeId: string, callback: AsyncCallback<Volume>): void + +Asynchronously obtains volume information based on the volume ID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.STORAGE_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained. | + +**Example** + + ```js + let volumeId = ""; + volumemanager.getVolumeById(volumeId, (error, volume) => { + // Do something. + }); + ``` + +## volumemanager.setVolumeDescription + +setVolumeDescription(uuid: string, description: string): Promise<void> + +Asynchronously sets the volume description based on the UUID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | --------- | ------ | ---- | ---- | + | uuid | string | Yes | UUID of the volume.| + | description | string | Yes | Volume description.| + +**Return value** + + | Type | Description | + | ---------------------- | -------------------------- | + | Promise<void> | Promise used to return the result. | + +**Example** + + ```js + let uuid = ""; + let description = ""; + volumemanager.setVolumeDescription(uuid, description).then(function() { + console.info("setVolumeDescription successfully"); + }).catch(function(error){ + console.info("setVolumeDescription failed with error:"+ error); + }); + ``` + +## volumemanager.setVolumeDescription + +setVolumeDescription(uuid: string, description: string, callback: AsyncCallback<void>): void + +Asynchronously sets the volume description based on the UUID. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_UNMOUNT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | --------------------------------------- | ---- | ---------------- | + | uuid | string | Yes | UUID of the volume. | + | description | string | Yes | Volume description. | + | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + + ```js + let uuid = ""; + let description = ""; + volumemanager.setVolumeDescription(uuid, description, (error, bool) => { + // Do something. + }); + ``` + +## volumemanager.format + +format(volumeId: string, fsType: string): Promise<void> + +Asynchronously formats a volume. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | volumeId | string | Yes | Volume ID.| + | fsType | string | Yes | File system type.| + +**Return value** + + | Type | Description | + | ---------------------- | ---------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```js + let volumeId = ""; + let fsType = ""; + volumemanager.format(volumeId, fsType).then(function() { + console.info("format successfully"); + }).catch(function(error){ + console.info("format failed with error:"+ error); + }); + ``` + +## volumemanager.format + +format(volumeId: string, fsType: string, callback: AsyncCallback<void>): void + +Asynchronously formats a volume. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------- | ---- | ----------------------------- | + | volumeId | string | Yes | Volume ID. | + | fsType | string | Yes | File system type.| + | callback | callback:AsyncCallback<void> | Yes | Called after the volume is formatted. | + +**Example** + + ```js + let volumeId = ""; + let fsType = ""; + volumemanager.format(volumeId, fsType, (error, bool) => { + // Do something. + }); + ``` + +## volumemanager.partition + +partition(diskId: string, type: number): Promise<void> + +Asynchronously partitions a disk. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | ------ | ---- | ---- | + | diskId | string | Yes | ID of the disk to which the volume belongs.| + | type | number | Yes | Partition type. | + +**Return value** + + | Type | Description | + | --------------------- | ----------------------- | + | Promise<void> | Promise used to return the result. | + +**Example** + + ```js + let diskId = ""; + let type = 0; + volumemanager.partition(diskId, type).then(function() { + console.info("partition successfully"); + }).catch(function(error){ + console.info("partition failed with error:"+ error); + }); + ``` + +## volumemanager.partition + +partition(diskId: string, type: number, callback: AsyncCallback<void>): void + +Asynchronously partitions a disk. This API uses a callback to return the result. + +**Required permissions**: ohos.permission.MOUNT_FORMAT_MANAGER + +**System capability**: SystemCapability.FileManagement.StorageService.Volume + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | --------------------------------------- | ---- | ---------------- | + | diskId | string | Yes | ID of the disk to which the volume belongs. | + | type | number | Yes | Partition type. | + | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + + ```js + let diskId = ""; + let type = 0; + volumemanager.partition(diskId, type, (error, bool) => { + // Do something. }); ``` @@ -172,11 +491,12 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. ### Attributes -| Name | Type | Description | +| Name | Type | Description | | ----------- | ------- | -------------------- | -| id | number | Volume ID. | -| uuid | string | Universally unique identifier (UUID) of the volume. | +| id | string | Volume ID. | +| uuid | string | UUID of the volume. | +| diskId | string | ID of the disk to which the volume belongs. | | description | string | Description of the volume. | -| removable | boolean | Whether the volume is a removable storage device.| -| state | int | Current volume status. | +| removable | boolean | Whether the volume is a removable storage device.| +| state | number | Volume state. | | path | string | Mount address of the volume. | diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 75dda908af3e32140bf7c94b92ff73117be0ad7e..15fd2c4fcdeb681b4ace2dc49d521f54e08014f5 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,7 +1,9 @@ # Wallpaper -> **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. +> **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 @@ -465,7 +467,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a }).catch((error) => { console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); }); - ``` +``` ## wallpaper.setWallpaper @@ -520,7 +522,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr }).catch((error) => { console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); }); - ``` +``` ## wallpaper.getFile8+ @@ -528,7 +530,7 @@ getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): vo Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER and ohos.permission.READ_USER_STORAGE +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE **System capability**: SystemCapability.MiscServices.Wallpaper @@ -557,7 +559,7 @@ getFile(wallpaperType: WallpaperType): Promise<number> Obtains the wallpaper of the specified type. This API uses a promise to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER and ohos.permission.READ_USER_STORAGE +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE **System capability**: SystemCapability.MiscServices.Wallpaper @@ -636,7 +638,7 @@ Obtains the pixel image for the wallpaper of the specified type. This API uses a **Example** ```js - wallpaper.getPixelMap(WALLPAPER_SYSTEM).then((data) => { + wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); }).catch((err) => { @@ -695,9 +697,9 @@ Unsubscribes from the wallpaper color change event. wallpaper.on('colorChange', listener); // Unsubscribe from the listener. wallpaper.off('colorChange', listener); -//Unsubscribe from all subscriptions of the colorChange type. +// Unsubscribe from all subscriptions of the colorChange type. wallpaper.off('colorChange'); -``` + ``` ## RgbaColor diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index 785b49c7236a6b65d30299478c3da1959bb290f2..a205de94d8080753ed0305f56fb6fc5ce8534707 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -1,12 +1,15 @@ -# webgl - -> **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. +# WebGL +The **WebGL** module provides the graphics drawing capability, such as processing the graphics position and color. This module provides WebGL APIs that correspond to the OpenGL ES 2.0 feature set. For more information, see [WebGL™](https://www.khronos.org/registry/webgl/specs/latest/1.0/). +> **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. +> +> WebGL complies with the OpenGL protocol and does not support multi-thread calling. + ## Invoking Method @@ -38,7 +41,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **System capability**: SystemCapability.Graphic.Graphic2D.WebGL - **Table 1** Type +**Table 1** Type | Name| Type| | -------- | -------- | @@ -62,11 +65,11 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | WebGLPowerPreference | string | -## Interface +## APIs **System capability**: SystemCapability.Graphic.Graphic2D.WebGL - **Table 2** Interface +**Table 2** APIs | Name| | -------- | @@ -427,7 +430,7 @@ WebGLRenderingContextBase | CONTEXT_LOST_WEBGL | GLenum | Yes| | UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| | BROWSER_DEFAULT_WEBGL | GLenum | Yes| -| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| +| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| | drawingBufferWidth | GLsizei | Yes| | drawingBufferHeight | GLsizei | Yes| @@ -436,124 +439,124 @@ WebGLRenderingContextBase | Method| Return Value Type| | -------- | -------- | -| getContextAttributes() | WebGLContextAttributes \| null | +| getContextAttributes() | WebGLContextAttributes \| null | | isContextLost() | boolean | -| getSupportedExtensions() | string[] \| null | -| getExtension(name: string) | any | -| activeTexture(texture: GLenum) | void | -| attachShader(program: WebGLProgram, shader: WebGLShader) | void | -| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | -| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | -| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | -| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | -| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| blendEquation(mode: GLenum) | void | -| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | -| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | -| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | -| checkFramebufferStatus(target: GLenum) | GLenum | -| clear(mask: GLbitfield) | void | -| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| clearDepth(depth: GLclampf) | void | -| clearStencil(s: GLint) | void | -| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | -| compileShader(shader: WebGLShader) | void | -| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | -| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| createBuffer() | WebGLBuffer \| null | -| createFramebuffer() | WebGLFramebuffer \| null | -| createProgram() | WebGLProgram \| null | -| createRenderbuffer() | WebGLRenderbuffer \| null | -| createShader(type: GLenum) | WebGLShader \| null | -| createTexture() | WebGLTexture \| null | -| cullFace(mode: GLenum) | void | -| deleteBuffer(buffer: WebGLBuffer \| null) | void | -| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | -| deleteProgram(program: WebGLProgram \| null) | void | -| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | -| deleteShader(shader: WebGLShader \| null) | void | -| deleteTexture(texture: WebGLTexture \| null) | void | -| depthFunc(func: GLenum) | void | -| depthMask(flag: GLboolean) | void | -| depthRange(zNear: GLclampf, zFar: GLclampf) | void | -| detachShader(program: WebGLProgram, shader: WebGLShader) | void | -| disable(cap: GLenum) | void | -| disableVertexAttribArray(index: GLuint) | void | -| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | -| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| enable(cap: GLenum) | void | -| enableVertexAttribArray(index: GLuint) | void | +| getSupportedExtensions() | string[] \| null | +| getExtension(name: string) | any | +| activeTexture(texture: GLenum) | void | +| attachShader(program: WebGLProgram, shader: WebGLShader) | void | +| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | +| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | +| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | +| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | +| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| blendEquation(mode: GLenum) | void | +| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | +| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | +| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | +| checkFramebufferStatus(target: GLenum) | GLenum | +| clear(mask: GLbitfield) | void | +| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| clearDepth(depth: GLclampf) | void | +| clearStencil(s: GLint) | void | +| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | +| compileShader(shader: WebGLShader) | void | +| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | +| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| createBuffer() | WebGLBuffer \| null | +| createFramebuffer() | WebGLFramebuffer \| null | +| createProgram() | WebGLProgram \| null | +| createRenderbuffer() | WebGLRenderbuffer \| null | +| createShader(type: GLenum) | WebGLShader \| null | +| createTexture() | WebGLTexture \| null | +| cullFace(mode: GLenum) | void | +| deleteBuffer(buffer: WebGLBuffer \| null) | void | +| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | +| deleteProgram(program: WebGLProgram \| null) | void | +| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | +| deleteShader(shader: WebGLShader \| null) | void | +| deleteTexture(texture: WebGLTexture \| null) | void | +| depthFunc(func: GLenum) | void | +| depthMask(flag: GLboolean) | void | +| depthRange(zNear: GLclampf, zFar: GLclampf) | void | +| detachShader(program: WebGLProgram, shader: WebGLShader) | void | +| disable(cap: GLenum) | void | +| disableVertexAttribArray(index: GLuint) | void | +| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | +| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| enable(cap: GLenum) | void | +| enableVertexAttribArray(index: GLuint) | void | | finish() | void | | flush() | void | -| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | -| frontFace(mode: GLenum) | void | -| generateMipmap(target: GLenum) | void | -| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | -| getAttribLocation(program: WebGLProgram, name: string) | GLint | -| getBufferParameter(target: GLenum, pname: GLenum) | any | -| getParameter(pname: GLenum) | any | +| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | +| frontFace(mode: GLenum) | void | +| generateMipmap(target: GLenum) | void | +| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | +| getAttribLocation(program: WebGLProgram, name: string) | GLint | +| getBufferParameter(target: GLenum, pname: GLenum) | any | +| getParameter(pname: GLenum) | any | | getError() | GLenum | -| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | -| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | -| getProgramInfoLog(program: WebGLProgram) | string \| null | -| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | -| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | -| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | -| getShaderInfoLog(shader: WebGLShader) | string \| null | -| getShaderSource(shader: WebGLShader) | string \| null | -| getTexParameter(target: GLenum, pname: GLenum) | any | -| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | -| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | -| getVertexAttrib(index: GLuint, pname: GLenum) | any | -| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | -| hint(target: GLenum, mode: GLenum) | void | -| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | -| isEnabled(cap: GLenum) | GLboolean | -| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | -| isProgram(program: WebGLProgram \| null) | GLboolean | -| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | -| isShader(shader: WebGLShader \| null) | GLboolean | -| isTexture(texture: WebGLTexture \| null) | GLboolean | -| lineWidth(width: GLfloat) | void | -| linkProgram(program: WebGLProgram) | void | -| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | -| polygonOffset(factor: GLfloat, units: GLfloat) | void | -| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| sampleCoverage(value: GLclampf, invert: GLboolean) | void | -| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| shaderSource(shader: WebGLShader, source: string) | void | -| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilMask(mask: GLuint) | void | -| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | -| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | -| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | -| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | -| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | -| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | -| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | -| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | -| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| useProgram(program: WebGLProgram \| null) | void | -| validateProgram(program: WebGLProgram) | void | -| vertexAttrib1f(index: GLuint, x: GLfloat) | void | -| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | -| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| vertexAttrib1fv(index: GLuint, values: Float32List) | void | -| vertexAttrib2fv(index: GLuint, values: Float32List) | void | -| vertexAttrib3fv(index: GLuint, values: Float32List) | void | -| vertexAttrib4fv(index: GLuint, values: Float32List) | void | -| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | -| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | +| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | +| getProgramInfoLog(program: WebGLProgram) | string \| null | +| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | +| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | +| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | +| getShaderInfoLog(shader: WebGLShader) | string \| null | +| getShaderSource(shader: WebGLShader) | string \| null | +| getTexParameter(target: GLenum, pname: GLenum) | any | +| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | +| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | +| getVertexAttrib(index: GLuint, pname: GLenum) | any | +| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | +| hint(target: GLenum, mode: GLenum) | void | +| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | +| isEnabled(cap: GLenum) | GLboolean | +| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | +| isProgram(program: WebGLProgram \| null) | GLboolean | +| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | +| isShader(shader: WebGLShader \| null) | GLboolean | +| isTexture(texture: WebGLTexture \| null) | GLboolean | +| lineWidth(width: GLfloat) | void | +| linkProgram(program: WebGLProgram) | void | +| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | +| polygonOffset(factor: GLfloat, units: GLfloat) | void | +| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| sampleCoverage(value: GLclampf, invert: GLboolean) | void | +| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| shaderSource(shader: WebGLShader, source: string) | void | +| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilMask(mask: GLuint) | void | +| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | +| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | +| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | +| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | +| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | +| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | +| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | +| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | +| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| useProgram(program: WebGLProgram \| null) | void | +| validateProgram(program: WebGLProgram) | void | +| vertexAttrib1f(index: GLuint, x: GLfloat) | void | +| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | +| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| vertexAttrib1fv(index: GLuint, values: Float32List) | void | +| vertexAttrib2fv(index: GLuint, values: Float32List) | void | +| vertexAttrib3fv(index: GLuint, values: Float32List) | void | +| vertexAttrib4fv(index: GLuint, values: Float32List) | void | +| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | +| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | ## WebGLRenderingContextOverloads @@ -562,24 +565,24 @@ WebGLRenderingContextOverloads | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void; | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index cd0894fa90f7165c05bfe0ecf6fd406dd8fd32eb..6fc36366d38b7d65484822911e8acdf926b8e931 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -1,12 +1,15 @@ -# webgl2 - -> **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. +# WebGL2 +The **WebGL2** module supports graphics drawing, such as processing the graphics position and color. WebGL2 provides enhanced capabilities in the rendering pipeline and shader language than WebGL. This module provides WebGL APIs that correspond to the OpenGL ES 3.0 feature set. For more information, see [WebGL™](https://www.khronos.org/registry/webgl/specs/latest/2.0/). +> **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. +> +> WebGL2 complies with the OpenGL protocol and does not support multi-thread calling. + ## Invoking Method @@ -38,7 +41,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **System capability**: SystemCapability.Graphic.Graphic2D.WebGL2 - **Table 1** Type +**Table 1** Type | Name| Type| | -------- | -------- | @@ -48,11 +51,11 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | Uint32List | array | -## Interface +## APIs **System capability**: SystemCapability.Graphic.Graphic2D.WebGL2 - **Table 2** Interface +**Table 2** APIs | Name| | -------- | @@ -342,101 +345,101 @@ WebGL2RenderingContextBase | Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | | endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | | pauseTransformFeedback() | void | | resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads @@ -445,36 +448,36 @@ WebGL2RenderingContextOverloads | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index c4d8d105f13c4214912120eb9fc1659276ba07be..dd45a019584f96e4d7434303c6cbd38228420596 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,6 +1,6 @@ # WLAN -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -16,13 +16,13 @@ isWifiActive(): boolean Checks whether the WLAN is activated. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the WLAN is activated; returns **false** otherwise.| @@ -34,31 +34,31 @@ scan(): boolean Starts a scan for WLAN. -- Required permissions: +- **Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | - | boolean | Returns **true** if the scan is successful; returns **false** otherwise.| + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getScanInfos getScanInfos(): Promise<Array<WifiScanInfo>> -Obtains the scan result. This method uses a promise to return the result. +Obtains the scan result. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, or ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the scan result, which is a list of hotspots detected.| @@ -68,20 +68,20 @@ Obtains the scan result. This method uses a promise to return the result. getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void -Obtains the scan result. This method uses an asynchronous callback to return the result. +Obtains the scan result. This API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, or ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result, which is a list of hotspots detected.| -- Example +- **Example** ```js import wifi from '@ohos.wifi'; @@ -130,14 +130,14 @@ Represents WLAN hotspot information. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| +| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| | bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| | capabilities | string | Read only| Hotspot capabilities.| | securityType | [WifiSecurityType](#WifiSecurityType) | Read only| WLAN security type.| -| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN access point (AP).| | frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Bandwidth of the WLAN AP.| +| channelWidth | number | Read only| Channel width of the WLAN AP.| | timestamp | number | Read only| Timestamp.| @@ -158,23 +158,24 @@ Enumerates the WLAN security types. addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> -Adds untrusted WLAN configuration. This method uses a promise to return the result. +Adds untrusted WLAN configuration. This API uses a promise to return the result. +- **NOTE**
This API is not supported by OpenHarmony 3.1 Release. -- Required permissions: +- **Required permissions**: ohos.permission.SET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | Promise<boolean> | Promise used to return the operation result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## WifiDeviceConfig @@ -182,111 +183,113 @@ Represents the WLAN configuration. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| +| ssid | string | Read only| SSID of the hotspot, 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| +| preSharedKey | string | Read only| PSK of the hotspot.| +| isHiddenSsid | boolean | Read only| Whether the network is hidden.| +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type.| ## wifi.addUntrustedConfig7+ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Adds untrusted WLAN configuration. This method uses an asynchronous callback to return the result. +Adds untrusted WLAN configuration. This API uses an asynchronous callback to return the result. -- Required permissions: +- **NOTE**
This API is not supported by OpenHarmony 3.1 Release. + +- **Required permissions**: ohos.permission.SET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> -Removes untrusted WLAN configuration. This method uses a promise to return the result. +Removes untrusted WLAN configuration. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.SET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Removes untrusted WLAN configuration. This method uses an asynchronous callback to return the result. +Removes untrusted WLAN configuration. This API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.SET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove.| - | callback | AsyncCallback<boolean> | Yes| Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.getSignalLevel getSignalLevel(rssi: number, band: number): number -Obtains the WLAN signal strength. +Obtains the WLAN signal level. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA - **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | - | rssi | number | Yes| Signal strength of the hotspot, in dBm.| + | rssi | number | Yes| RSSI of the hotspot, in dBm.| | band | number | Yes| Frequency band of the WLAN AP.| -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | - | number | Signal strength obtained. The value range is [0, 4].| + | number | Signal level obtained. The value range is [0, 4].| ## wifi.getLinkedInfo getLinkedInfo(): Promise<WifiLinkedInfo> -Obtains WLAN connection information. This method uses a promise to return the result. +Obtains WLAN connection information. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<[WifiLinkedInfo](#WifiLinkedInfo)> | Promise used to return the WLAN connection information obtained.| @@ -296,20 +299,20 @@ Obtains WLAN connection information. This method uses a promise to return the re getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void -Obtains WLAN connection information. This method uses a callback to return the result. +Obtains WLAN connection information. This API uses a callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiLinkedInfo](#WifiLinkedInfo)> | Yes| Callback invoked to return the WLAN connection information obtained.| -- Example +- **Example** ```js import wifi from '@ohos.wifi'; @@ -335,9 +338,9 @@ Represents the WLAN connection information. | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| -| rssi | number | Read only| Signal strength of the hotspot, in dBm.| +| rssi | number | Read only| RSSI of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN AP.| | linkSpeed | number | Read only| Speed of the WLAN AP.| | frequency | number | Read only| Frequency of the WLAN AP.| @@ -361,7 +364,7 @@ Enumerates the WLAN connection states. | CONNECTED | 4 | A WLAN connection is established.| | DISCONNECTING | 5 | The WLAN connection is being disconnected.| | DISCONNECTED | 6 | The WLAN connection is disconnected.| -| UNKNOWN | 7 | Failed to set up a WLAN connection.| +| UNKNOWN | 7 | Failed to set up the WLAN connection.| ## wifi.isConnected7+ @@ -370,13 +373,13 @@ isConnected(): boolean Checks whether the WLAN is connected. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| @@ -388,10 +391,10 @@ isFeatureSupported(featureId: number): boolean Checks whether the device supports the specified WLAN feature. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.Core - **Parameters** @@ -399,7 +402,7 @@ Checks whether the device supports the specified WLAN feature. | -------- | -------- | -------- | -------- | | featureId | number | Yes| Feature ID.| -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| @@ -408,14 +411,14 @@ Checks whether the device supports the specified WLAN feature. | Value| Description| | -------- | -------- | | 0x0001 | WLAN infrastructure mode| - | 0x0002 | 5 GHz bandwidth| + | 0x0002 | 5 GHz feature| | 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| | 0x0008 | Wi-Fi Direct| | 0x0010 | SoftAP| | 0x0040 | Wi-Fi AWare| | 0x8000 | WLAN AP/STA concurrency| | 0x8000000 | WPA3 Personal (WPA-3 SAE)| - | 0x10000000 | WPA3-Enterprise Suite-B | + | 0x10000000 | WPA3-Enterprise Suite B | | 0x20000000 | Enhanced open feature| @@ -425,13 +428,13 @@ getIpInfo(): IpInfo Obtains IP information. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | [IpInfo](#IpInfo) | IP information obtained.| @@ -443,13 +446,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+ @@ -458,13 +461,13 @@ getCountryCode(): string Obtains the country code. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.Core -- Return value +- **Return value** | **Type**| **Description**| | -------- | -------- | | string | Country code obtained.| @@ -474,15 +477,15 @@ Obtains the country code. getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> -Obtains peer-to-peer (P2P) connection information. This method uses a promise to return the result. +Obtains peer-to-peer (P2P) connection information. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise used to return the P2P connection information obtained.| @@ -492,18 +495,18 @@ Obtains peer-to-peer (P2P) connection information. This method uses a promise to getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void -Obtains P2P connection information. This method uses a callback to return the result. +Obtains P2P connection information. This API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback used to return the P2P connection information obtained.| + | callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback invoked to return the P2P connection information obtained.| ## WifiP2pLinkedInfo8+ @@ -531,15 +534,15 @@ Enumerates the P2P connection states. getCurrentGroup(): Promise<WifiP2pGroupInfo> -Obtains the current P2P group information. This method uses a promise to return the result. +Obtains the current P2P group information. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Promise used to return the P2P group information obtained.| @@ -549,18 +552,18 @@ Obtains the current P2P group information. This method uses a promise to return getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void -Obtains the P2P group information. This method uses an asynchronous callback to return the result. +Obtains the P2P group information. This API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback used to return the P2P group information obtained.| + | callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback invoked to return the P2P group information obtained.| ## WifiP2pGroupInfo8+ @@ -571,7 +574,7 @@ Represents the P2P group information. | -------- | -------- | -------- | -------- | | isP2pGo | boolean | Read only| Whether it is a group.| | ownerInfo | [WifiP2pDevice](#WifiP2pDevice) | Read only| Device information of the group.| -| passphrase | string | Read only| Private key of the group.| +| passphrase | string | Read only| Passphrase of the group.| | interface | string | Read only| Interface name.| | groupName | string | Read only| Group name.| | networkId | number | Read only| Network ID.| @@ -593,7 +596,7 @@ Represents the P2P device information. ## P2pDeviceStatus8+ -Enumerates the device states. +Enumerates the P2P device states. | Name| Default Value| Description| | -------- | -------- | -------- | @@ -608,15 +611,15 @@ Enumerates the device states. getP2pPeerDevices(): Promise<WifiP2pDevice[]> -Obtains the list of peer devices in a P2P connection. This method uses a promise to return the result. +Obtains the list of peer devices in the P2P connection. This API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise used to return the peer device list obtained.| @@ -626,18 +629,18 @@ Obtains the list of peer devices in a P2P connection. This method uses a promise getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void -Obtains the list of peer devices in a P2P connection. This method uses an asynchronous callback to return the result. +Obtains the list of peer devices in the P2P connection. This API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback used to return the peer device list obtained.| + | callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback involed to return the peer device list obtained.| ## wifi.createGroup8+ @@ -646,10 +649,10 @@ createGroup(config: WifiP2PConfig): boolean; Creates a P2P group. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P - **Parameters** @@ -657,27 +660,27 @@ Creates a P2P group. | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Group configuration.| -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## WifiP2PConfig8+ -Represents P2P configuration. +Represents P2P group configuration. | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | | deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates that a temporary group, and **-2** indicates that a persistent group.| -| passphrase | string | Read only| Private key of the group.| +| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Read only| Passphrase of the group.| | groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#GroupOwnerBand) | Read only| Bandwidth of the group.| +| goBand | [GroupOwnerBand](#GroupOwnerBand) | Read only| Frequency band of the group.| ## GroupOwnerBand8+ -Enumerates the P2P group bandwidths. +Enumerates the P2P group frequency bands. | Name| Default Value| Description| | -------- | -------- | -------- | @@ -689,15 +692,15 @@ Enumerates the P2P group bandwidths. removeGroup(): boolean; -Removes a P2P group. +Removes this P2P group. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -709,24 +712,24 @@ p2pConnect(config: WifiP2PConfig): boolean; Sets up a P2P connection. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P - **Parameters** | **Name**| **Type**| Mandatory| **Description**| | -------- | -------- | -------- | -------- | - | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Connection configuration.| + | config | [WifiP2PConfig](#WifiP2PConfig) | Yes| P2P group configuration.| -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +- **Example** ```js import wifi from '@ohos.wifi'; @@ -799,13 +802,13 @@ p2pCancelConnect(): boolean; Cancels this P2P connection. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -817,13 +820,13 @@ startDiscoverDevices(): boolean; Starts to discover devices. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -835,13 +838,13 @@ stopDiscoverDevices(): boolean; Stops discovering devices. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Return value +- **Return value** | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -853,13 +856,13 @@ on(type: "wifiStateChange", callback: Callback<number>): void Registers the WLAN state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| @@ -880,19 +883,19 @@ off(type: "wifiStateChange", callback?: Callback<number>): void Unregisters the WLAN state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| -- Example +- **Example** ```js import wifi from '@ohos.wifi'; @@ -901,10 +904,10 @@ Unregisters the WLAN state change events. console.info("Receive power state change event: " + result); } - // Register event + // Register an event. wifi.on(WIFI_POWER_STATE, recvPowerNotifyFunc); - // Unregister event + // Unregister an event. wifi.off(WIFI_POWER_STATE, recvPowerNotifyFunc); ``` @@ -915,13 +918,13 @@ on(type: "wifiConnectionChange", callback: Callback<number>): void Registers the WLAN connection state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| @@ -930,8 +933,8 @@ Registers the WLAN connection state change events. - Enumerates the WLAN connection states. | **Value**| **Description**| | -------- | -------- | - | 0 | Disconnected| - | 1 | Connected| + | 0 | Disconnected.| + | 1 | Connected.| ## wifi.off('wifiConnectionChange')7+ @@ -940,17 +943,17 @@ off(type: "wifiConnectionChange", callback?: Callback<number>): void Unregisters the WLAN connection state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| - | callback | Callback<number> | No| Callback used to report the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -959,13 +962,13 @@ on(type: "wifiScanStateChange", callback: Callback<number>): void Registers the WLAN scan state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| @@ -974,8 +977,8 @@ Registers the WLAN scan state change events. - Enumerates the WLAN scan states. | **Value**| **Description**| | -------- | -------- | - | 0 | Scan failed| - | 1 | Scan successful| + | 0 | Scan failed.| + | 1 | Scan successful.| ## wifi.off('wifiScanStateChange')7+ @@ -984,13 +987,13 @@ off(type: "wifiScanStateChange", callback?: Callback<number>): void Unregisters the WLAN scan state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | @@ -1002,15 +1005,15 @@ Unregisters the WLAN scan state change events. on(type: "wifiRssiChange", callback: Callback<number>): void -Registers the RSSI state change events. +Registers the RSSI change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| @@ -1021,19 +1024,19 @@ Registers the RSSI state change events. off(type: "wifiRssiChange", callback?: Callback<number>): void -Unregisters the RSSI state change events. +Unregisters the RSSI change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.STA -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| - | callback | Callback<number> | No| Callback used to return the RSSI, in dBm. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -1042,13 +1045,13 @@ on(type: "hotspotStateChange", callback: Callback<number>): void Registers the hotspot state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Core -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| @@ -1069,13 +1072,13 @@ off(type: "hotspotStateChange", callback?: Callback<number>): void Unregisters the hotspot state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Core -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| @@ -1086,15 +1089,15 @@ Unregisters the hotspot state change events. on(type: "p2pStateChange", callback: Callback<number>): void -Registers the P2P status change events. +Registers the P2P state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| @@ -1115,13 +1118,13 @@ off(type: "p2pStateChange", callback?: Callback<number>): void Unregisters the P2P state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| @@ -1134,13 +1137,13 @@ on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): vo Registers the P2P connection state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| @@ -1153,13 +1156,13 @@ off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): Unregisters the P2P connection state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| @@ -1172,13 +1175,13 @@ on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void Registers the P2P device state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| @@ -1191,17 +1194,17 @@ off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void Unregisters the P2P device state change events. -- Required permissions: +- **Required permissions**: ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| - | callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | No| Callback used to return the P2P 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('p2pPeerDeviceChange')8+ @@ -1210,17 +1213,17 @@ on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void Registers the P2P peer device state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P peer device state.| + | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the peer device state.| ## wifi.off('p2pPeerDeviceChange')8+ @@ -1229,13 +1232,13 @@ off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): vo Unregisters the P2P peer device state change events. -- Required permissions: +- **Required permissions**: ohos.permission.LOCATION -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| @@ -1248,13 +1251,13 @@ on(type: "p2pPersistentGroupChange", callback: Callback<void>): void Registers the P2P persistent group state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| @@ -1267,13 +1270,13 @@ off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void Unregisters the P2P persistent group state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| @@ -1284,21 +1287,21 @@ Unregisters the P2P persistent group state change events. on(type: "p2pDiscoveryChange", callback: Callback<number>): void -Registers the P2P discovered device state change events. +Registers the P2P device discovery state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | Yes| Callback invoked to return the state of the P2P discovered device.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| -- Enumerates the states of P2P discovered devices. +- Enumerates the P2P device discovery states. | **Value**| **Description**| | -------- | -------- | | 0 | Initial state| @@ -1309,16 +1312,16 @@ Registers the P2P discovered device state change events. off(type: "p2pDiscoveryChange", callback?: Callback<number>): void -Unregisters the P2P discovered device state change events. +Unregisters the P2P device discovery state change events. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.P2P -- Parameters +- **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| - | callback | Callback<number> | No| Callback used to return the state of the P2P discovered device. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 2e2e9394b2a4361fa8adad332c459d4ff33a4e4d..028b396ebb4244ce80eb4a4754bf8d2445474ce3 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,8 +1,9 @@ # WLAN -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. +The APIs of this module are not supported by OpenHarmony 3.1 Release. ## Modules to Import @@ -17,13 +18,13 @@ enableHotspot(): boolean; Enables the WLAN hotspot. -- Required permissions: +- **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +- **Return value**: | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -35,13 +36,13 @@ disableHotspot(): boolean; Disables the WLAN hotspot. -- Required permissions: +- **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +- **Return value**: | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -51,15 +52,15 @@ Disables the WLAN hotspot. getSupportedPowerModel(): Promise<Array<PowerModel>> -Obtains the supported power models. The method uses a promise to return the result. +Obtains the supported power models. The API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +- **Return value**: | Type| Description| | -------- | -------- | | Promise<Array<[PowerModel](#PowerModel)>> | Promise used to return the power models obtained.| @@ -67,7 +68,7 @@ Obtains the supported power models. The method uses a promise to return the resu ## PowerModel -Enumerates of the power models. +Enumerates the power models. | Name| Default Value| Description| | -------- | -------- | -------- | @@ -80,33 +81,33 @@ Enumerates of the power models. getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void -Obtains the supported power models. The method uses an asynchronous callback to return the result. +Obtains the supported power models. The API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback used to return the power models obtained.| + | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback invoked to return the power models obtained.| ## wifiext.getPowerModel getPowerModel(): Promise<PowerModel> -Obtains the power model. The method uses a promise to return the result. +Obtains the power model. The API uses a promise to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +- **Return value**: | Type| Description| | -------- | -------- | | Promise<[PowerModel](#PowerModel)> | Promise used to return the power model obtained.| @@ -116,15 +117,15 @@ Obtains the power model. The method uses a promise to return the result. getPowerModel(callback: AsyncCallback<PowerModel>): void -Obtains the power model. The method uses an asynchronous callback to return the result. +Obtains the power model. The API uses an asynchronous callback to return the result. -- Required permissions: +- **Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback invoked to return the power mode obtained.| @@ -136,18 +137,18 @@ setPowerModel(model: PowerModel) : boolean; Sets the power model. -- Required permissions: +- **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: +- **System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | model | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Power model to set.| -- Return value +- **Return value**: | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index b3db77cfbac7a3c195a6f2d88cf88977332457ca..cf1052ae97ef878030e348cea83f8388092fbde2 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,17 +1,14 @@ # Window -The `Window` module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. +The `Window` module provides basic window management capabilities, such as creating and destroying the current window and setting properties for the current window. This module provides the following common window-related functions: -- [Window](#window): the current window instance, which is the basic unit managed by the window manager. -- [WindowStage](#windowstage9): window manager that manages windows. +[Window](#window): the current window instance, which is the basic unit managed by the window manager. > **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. -> -> API version 9 is a canary version for trial use. The APIs of this version may be unstable. ## Modules to Import @@ -37,16 +34,16 @@ Enumerates the types of the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -| ----------- | ---- | ------------------ | -| TYPE_SYSTEM | 0 | Default area of the system.| -| TYPE_CUTOUT | 1 | Notch. | +| Name | Value | Description | +|----------------------------------|-----| ----------------- | +| TYPE_SYSTEM | 0 | Default area of the system.| +| TYPE_CUTOUT | 1 | Notch. | ## WindowMode7+ Enumerates the window modes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -66,41 +63,41 @@ Describes the properties of the status bar and navigation bar. | Name | Type| Readable| Writable| Description | | -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | isStatusBarLightIcon7+ | boolean | No | Yes | Whether any icon on the status bar is highlighted. | | statusBarContentColor8+ | string | No | Yes | Color of the text on the status bar. | -| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isNavigationBarLightIcon7+ | boolean | No | No | Whether any icon on the navigation bar is highlighted. | +| navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| isNavigationBarLightIcon7+ | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. | | navigationBarContentColor8+ | string | No | Yes | Color of the text on the navigation bar. | ## SystemBarRegionTint8+ Describes the callback for a single system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name | Type | Readable| Writable| Description | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| type | [WindowType](#windowtype) | Yes | Yes | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| -| isEnable | boolean | Yes | Yes | Whether the system bar is displayed. | -| region | [Rect](#rect) | Yes | Yes | Current position and size of the system bar. | -| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| contentColor | string | Yes | Yes | Color of the text on the system bar. | +| type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| +| isEnable | boolean | Yes | No | Whether the system bar is displayed. | +| region | [Rect](#rect) | Yes | No | Current position and size of the system bar. | +| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| contentColor | string | Yes | No | Color of the text on the system bar. | ## SystemBarTintState8+ Describes the callback for the current system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name | Type | Readable| Writable| Description | | ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- | | displayId | number | Yes | No | ID of the current physical screen. | -| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information that has been changed.| +| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | No | All system bar information that has been changed.| ## Rect7+ @@ -128,6 +125,7 @@ Describes the area where the window cannot be displayed. | rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| | bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.| + ## Size7+ Describes the window size. @@ -145,20 +143,20 @@ Describes the window properties. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | -| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | -| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | -| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | -| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | -| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | -| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
This attribute is supported since API version 7 and deprecated since API version 9.
| -| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | -| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | -| isRoundCorner7+ | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | -| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | +| Name | Type | Readable| Writable| Description | +| ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | +| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | +| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | +| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | +| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | +| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | +| dimBehindValue7+ | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness. | +| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | +| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | +| isRoundCorner7+ | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | ## ColorSpace8+ @@ -191,13 +189,14 @@ Creates a subwindow. This API uses an asynchronous callback to return the result ```js var windowClass = null; - let promise = window.create("first", window.WindowType.TYPE_APP); - promise.then((data)=> { - windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - }); +window.create("first", window.WindowType.TYPE_APP,(err,data) => { + if(err.code){ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); +}); ``` ## window.create7+ @@ -228,7 +227,7 @@ var windowClass = null; let promise = window.create("first", window.WindowType.TYPE_APP); promise.then((data)=> { windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)); + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); }); @@ -238,7 +237,7 @@ promise.then((data)=> { create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. +Creates a subwindow. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -246,10 +245,10 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| +| ctx | [Context](js-apis-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 window created. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | **Example** @@ -257,11 +256,11 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). var windowClass = null; window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { if (err.code) { - console.error('Failed to create the Window. Cause: ' + JSON.stringify(err)); + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); return; } windowClass = data; - console.info('Window created. Data: ' + JSON.stringify(data)); + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); windowClass.resetSize(500, 1000); }); ``` @@ -270,7 +269,8 @@ var windowClass = null; create(ctx: Context, id: string, type: WindowType): Promise<Window> -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. +Creates a subwindow. This API uses a promise to return the result. + **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -278,7 +278,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| +| ctx | [Context](js-apis-Context.md) | Yes | Current application context.| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | @@ -286,7 +286,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Type | Description | | -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window created.| +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** @@ -295,9 +295,9 @@ var windowClass = null; let promise = window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT); promise.then((data)=> { windowClass = data; - console.info('Window created. Data:' + JSON.stringify(data)); + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); + console.error('Failed to create the window. Cause:' + JSON.stringify(err)); }); ``` @@ -322,11 +322,11 @@ Finds a window based on the ID. This API uses an asynchronous callback to return var windowClass = null; window.find("alertWindow", (err, data) => { if (err.code) { - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); + console.error('Failed to find the window. Cause: ' + JSON.stringify(err)); return; } windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }); ``` @@ -357,9 +357,9 @@ var windowClass = null; let promise = window.find("alertWindow"); promise.then((data)=> { windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); + console.error('Failed to find the window. Cause: ' + JSON.stringify(err)); }); ``` @@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| +| ctx | [Context](js-apis-Context.md) | Yes | Current application context.| | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** @@ -459,7 +459,7 @@ Obtains the top window of the current application. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| +| ctx | [Context](js-apis-Context.md) | Yes | Current application context.| **Return value** @@ -486,7 +486,7 @@ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): v Enables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -494,7 +494,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | Yes | Callback used to return the properties of the status bar and navigation bar. | **Example** @@ -511,7 +511,7 @@ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >) Disables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -519,7 +519,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | No | Callback used to return the properties of the status bar and navigation bar. | **Example** @@ -540,7 +540,7 @@ hide (callback: AsyncCallback<void>): void Hides this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -558,7 +558,7 @@ windowClass.hide((err, data) => { console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('window hidden. data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); }) ``` @@ -568,7 +568,7 @@ hide(): Promise<void> Hides this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -583,7 +583,7 @@ This is a system API and cannot be called by third-party applications. ```js let promise = windowClass.hide(); promise.then((data)=> { - console.info('window hidden. Data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); }) @@ -715,7 +715,7 @@ windowClass.moveTo(300, 300, (err, data)=>{ console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }); ``` @@ -746,7 +746,7 @@ Moves this window. This API uses a promise to return the result. ```js let promise = windowClass.moveTo(300, 300); promise.then((data)=> { - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); }) @@ -776,7 +776,7 @@ windowClass.resetSize(500, 1000, (err, data) => { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }); ``` @@ -806,7 +806,7 @@ Changes the size of this window. This API uses a promise to return the result. ```js let promise = windowClass.resetSize(500, 1000); promise.then((data)=> { - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); }); @@ -818,7 +818,7 @@ setWindowType(type: WindowType, callback: AsyncCallback<void>): void Sets the type of this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -848,7 +848,7 @@ setWindowType(type: WindowType): Promise<void> Sets the type of this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -937,8 +937,8 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| | callback | AsyncCallback<[AvoidArea](#avoidarea)> | Yes | Callback used to return the area. | @@ -965,20 +965,21 @@ Obtains the area where this window cannot be displayed, for example, the system **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------- | ---- | ------------------------------------------------------------ | +| Name| Type | Mandatory| Description | +| ------ |----------------------------------| ---- | ------------------------------------------------------------ | | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| **Return value** -| Type | Description | -| -------------------------------------- | ----------------------------------- | +| Type | Description | +|-----------------------------------------| ----------------------------------- | | Promise<[AvoidArea](#avoidarea)> | Promise used to return the area.| **Example** ```js -let promise = windowClass.getAvoidArea(); +var type = window.AvoidAreaType.TYPE_SYSTEM; +let promise = windowClass.getAvoidArea(type); promise.then((data)=> { console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); }).catch((err)=>{ @@ -1124,13 +1125,14 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; windowClass.setSystemBarEnable(names, (err, data) => { if (err.code) { - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }); ``` @@ -1157,12 +1159,13 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; let promise = windowClass.setSystemBarEnable(names); promise.then((data)=> { - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); }); ``` @@ -1313,7 +1316,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| **Example** @@ -1339,7 +1342,7 @@ Checks whether this window is displayed. This API uses a promise to return the r | Type | Description | | ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| +| Promise<boolean> | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| **Example** @@ -1364,7 +1367,7 @@ Enables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------ | ---- | -------------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| | callback | Callback<[Size](#size7)> | Yes | Callback used to return the window size. | **Example** @@ -1387,7 +1390,7 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| | callback | Callback<[Size](#size)> | No | Callback used to return the window size. | **Example** @@ -1406,9 +1409,9 @@ Enables listening for changes to the area where the window cannot be displayed. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| | callback | Callback<[AvoidArea](#avoidarea)> | Yes | Callback used to return the area. | **Example** @@ -1429,10 +1432,10 @@ Disables listening for changes to the area where the window cannot be displayed. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea)> | No | Callback used to return the area. | +| Name | Type | Mandatory| Description | +| -------- |------------------------------------------| ---- | ------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| callback | Callback<[AvoidArea](#avoidarea)> | No | Callback used to return the area. | **Example** @@ -1452,7 +1455,7 @@ Enables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| +| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| | callback | Callback { console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); }).catch((err)=>{ @@ -1656,7 +1659,7 @@ Sets the background color for this window. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -1684,7 +1687,7 @@ Sets the background color for this window. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| **Return value** @@ -1764,15 +1767,15 @@ promise.then((data)=> { }); ``` -### setDimBehind(deprecated) +### setDimBehind7+ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +> +> This API cannot be used. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1795,15 +1798,15 @@ windowClass.setDimBehind(0.5, (err, data) => { }); ``` -### setDimBehind(deprecated) +### setDimBehind7+ setDimBehind(dimBehindValue: number): Promise<void> Sets the dimness of the window that is not on top. This API uses a promise to return the result. > **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +> +> This API cannot be used. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1950,15 +1953,15 @@ promise.then((data) => { }); ``` -### setOutsideTouchable(deprecated) +### setOutsideTouchable7+ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +> +> This API cannot be used. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1981,7 +1984,7 @@ windowClass.setOutsideTouchable(true, (err, data) => { }) ``` -### setOutsideTouchable(deprecated) +### setOutsideTouchable7+ setOutsideTouchable(touchable: boolean): Promise<void> @@ -1989,9 +1992,7 @@ Sets whether the area outside the subwindow is touchable. This API uses a promis > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 9. -> -> +> This API cannot be used. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2022,7 +2023,7 @@ promise.then((data)=> { setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void -Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2051,7 +2052,7 @@ windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { setPrivacyMode(isPrivacyMode: boolean): Promise<void> -Sets whether this window is in privacy mode. This API uses a promise to return the result. +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2139,314 +2140,3 @@ promise.then((data)=> { console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); }); ``` - -## WindowStageEventType9+ - -Describes the lifecycle of a window stage. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -| Name | Default Value | Description | -| ---------- | ------ | ---------- | -| FOREGROUND | 1 | The window stage is running in the foreground.| -| ACTIVE | 2 | The window stage gains focus.| -| INACTIVE | 3 | The window stage loses focus.| -| BACKGROUND | 4 | The window stage is running in the background.| - -## WindowStage9+ - -Implements a window manager, which manages each basic window unit, that is, [Window](#window) instance. - -Before calling any of the following APIs, you must use `[onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate)` to create a `WindowStage` instance. - -### getMainWindow9+ - -getMainWindow(callback: AsyncCallback<Window>): void - -Obtains the main window of this window stage. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.getMainWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - }); - } -} -``` -### getMainWindow9+ - -getMainWindow(): Promise<Window> - -Obtains the main window of this window stage. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the main window.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.getMainWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); - }); - } -} -``` -### createSubWindow9+ - -createSubWindow(name: string, callback: AsyncCallback<Window>): void - -Creates a subwindow for this window stage. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| name | String | Yes | Name of the subwindow. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.createSubWindow("mySubWindow", (err, data) => { - if (err.code) { - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); - }); - } -} -``` -### createSubWindow9+ - -createSubWindow(name: string): Promise<Window> - -Creates a subwindow for this window stage. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | String | Yes | Name of the subwindow.| - -**Return value** - -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the subwindow.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.createSubWindow("mySubWindow"); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - }) - } -} -``` -### getSubWindow9+ - -getSubWindow(callback: AsyncCallback<Array<Window>>): void - -Obtains all the subwindows of this window stage. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------------- | -| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - windowStage.getSubWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); - }); - } -} -``` -### getSubWindow9+ - -getSubWindow(): Promise<Array<Window>> - -Obtains all the subwindows of this window stage. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - -| Type | Description | -| --------------------------------------------- | ---------------------------------------------------- | -| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - var windowClass = null; - let promise = windowStage.getSubWindow(); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); - }) - } -} -``` -### loadContent9+ - -loadContent(path: string, callback: AsyncCallback<void>): void - -Loads content from a page to this window stage. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - windowStage.loadContent("pages/page2", (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }); - } -} -``` - -### on('windowStageEvent')9+ - -on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType>): void - -Enables listening for window stage lifecycle changes. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + JSON.stringify(data)); - }); - } -} -``` - -### off('windowStageEvent')9+ - -off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType>): void - -Disables listening for window stage lifecycle changes. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Type of event to listen for. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | - -**Example** - -```ts -import Ability from '@ohos.application.Ability'; -class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - windowStage.off('windowStageEvent'); - } -} -``` diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 1192097ac4b6daa8b88331ae09fb98d6c8697384..aaaad457f25d19f50735576c44f13aa011cbef58 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,6 +1,11 @@ # Zip +> **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. + ## Constraints + None ## Modules to Import @@ -9,18 +14,19 @@ import zlib from '@ohos.zlib'; ``` ## zlib.zipFile -zipFile(inFile:string, outFile:string, options: Options): Promise\ +zipFile(inFile:string, outFile:string, options: Options): Promise<void> + Zips a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ------------------------------------------- | -| inFile | string | Yes | Path of the folder or file to zip. | -| outFile | string | Yes | Path of the zipped file. The file name extension is .zip.| -| options | [Options](#options)| No | Optional parameters for the zip operation. | +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) and [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | +| options | [Options](#options) | No | Optional parameters for the zip operation. | **Return value** @@ -36,17 +42,14 @@ Zips a file. This API uses a promise to return the result. import zlib from '@ohos.zlib' var inFile = "/xxx/filename.xxx"; var outFile = "/xxx/xxx.zip"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; zlib.zipFile(inFile, outFile, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("zipFile OK"); - } else { - console.log("zipFile NG"); - } + console.log("zipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }); @@ -60,17 +63,14 @@ zlib.zipFile(inFile, outFile, options).then((data) => { import zlib from '@ohos.zlib' var inFile = "/xxx/xxx"; var outFile = "/xxx/xxx.zip"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; - -zlib.zipFile(inFile , unzipDir, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("zipFile OK"); - } else { - console.log("zipFile NG"); - } +var options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +zlib.zipFile(inFile , outFile, options).then((data) => { + console.log("zipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }); @@ -78,7 +78,7 @@ zlib.zipFile(inFile , unzipDir, options).then((data) => { ## zlib.unzipFile -unzipFile(inFile:string, outFile:string, options: Options): Promise\ +unzipFile(inFile:string, outFile:string, options: Options): Promise<void> Unzips a file. This API uses a promise to return the result. @@ -86,11 +86,11 @@ Unzips a file. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------- | ---- | ----------------------------------- | -| inFile | string | Yes | Path of the file to unzip. The file name extension is .zip.| -| outFile | string | Yes | Path of the unzipped file. | -| options | [Options](#options)| No | Optional parameters for the unzip operation. | +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) and [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the unzipped file. | +| options | [Options](#options) | No | Optional parameters for the unzip operation. | **Return value** @@ -106,61 +106,67 @@ import zlib from '@ohos.zlib' var inFile = "/xx/xxx.zip"; var outFile = "/xxx"; -var options = {}; -options.level = zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION; -options.memLevel = zlib.MemLevel.MEM_LEVEL_DEFAULT; -options.strategy = zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY; - +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; zlib.unzipFile(inFile, outFile, options).then((data) => { - if (data == zlib.ErrorCode.ERROR_CODE_OK) { - console.log("unzipFile OK"); - } else { - console.log("unzipFile NG"); - } + console.log("unzipFile result: " + data); }).catch((err)=>{ console.log("catch((err)=>" + err); }) ``` -## options +## Options -| Name | Description | -| --------------------------- | ------------------------------------------------------------ | -| level?: CompressLeve | See [zip.CompressLevel](#zipcompresslevel). | -| memLevel?: MemLevel | See [zip.MemLevel](#zipmemlevel) | -| strategy?: CompressStrategy | See [zip.CompressStrategy](#zipcompressstrategy) | +**System capability**: SystemCapability.BundleManager.Zlib + +| Name | Type | Mandatory| Description | +| -------- | ---------------- | ---- | --------------------------------------------------------- | +| level | CompressLeve | No | See [zip.CompressLevel](#zipcompresslevel). | +| memLevel | MemLevel | No | See [zip.MemLevel](#zipmemlevel). | +| strategy | CompressStrategy | No | See [zip.CompressStrategy](#zipcompressstrategy).| ## zip.MemLevel -| 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.| +**System capability**: SystemCapability.BundleManager.Zlib + +| Name | Value | Description | +| ----------------- | ---- | -------------------------------- | +| MEM_LEVEL_MIN | 1 | Minimum memory used by the **zip** API during compression.| +| MEM_LEVEL_MAX | 9 | Maximum memory used by the **zip** API during compression.| +| MEM_LEVEL_DEFAULT | 8 | Default memory used by the **zip** API during compression.| + +## zip.CompressLevel -## Zip.CompressLevel +**System capability**: SystemCapability.BundleManager.Zlib -| Name | Description | -| --------------------------------------- | ----------------- | -| COMPRESS_LEVEL_NO_COMPRESSION : 0 | Compress level 0 that indicates uncompressed.| -| COMPRESS_LEVEL_BEST_SPEED : 1 | Compression level 1 that gives the best speed. | -| COMPRESS_LEVEL_BEST_COMPRESSION :9 | Compression level 9 that gives the best compression. | -| COMPRESS_LEVEL_DEFAULT_COMPRESSION : -1| Default compression level. | +| Name | Value | Description | +| ---------------------------------- | ---- | ----------------- | +| COMPRESS_LEVEL_NO_COMPRESSION | 0 | Compress level 0 that indicates uncompressed.| +| COMPRESS_LEVEL_BEST_SPEED | 1 | Compression level 1 that gives the best speed. | +| COMPRESS_LEVEL_BEST_COMPRESSION | 9 | Compression level 9 that gives the best compression. | +| COMPRESS_LEVEL_DEFAULT_COMPRESSION | -1 | Default compression level. | -## Zip.CompressStrategy +## zip.CompressStrategy -| Name | Description | -| -------------------------------------- | ------------------------ | -| COMPRESS_STRATEGY_DEFAULT_STRATEGY : 0 | Default compression strategy. | -| COMPRESS_STRATEGY_FILTERED : 1 | Filtered compression strategy.| -| COMPRESS_STRATEGY_HUFFMAN_ONLY : 2 | Huffman coding compression strategy. | -| COMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | -| COMPRESS_STRATEGY_FIXED : 4 | Fixed compression strategy. | +**System capability**: SystemCapability.BundleManager.Zlib + +| Name | Value | Description | +| ---------------------------------- | ---- | ------------------------ | +| COMPRESS_STRATEGY_DEFAULT_STRATEGY | 0 | Default compression strategy. | +| COMPRESS_STRATEGY_FILTERED | 1 | Filtered compression strategy.| +| COMPRESS_STRATEGY_HUFFMAN_ONLY | 2 | Huffman coding compression strategy. | +| COMPRESS_STRATEGY_RLE | 3 | RLE compression strategy. | +| COMPRESS_STRATEGY_FIXED | 4 | Fixed compression strategy. | ## zip.ErrorCode -| Name | Description | -| -------------------- | ------------ | -| ERROR_CODE_OK: 0 | The API is successfully called.| -| ERROR_CODE_ERRNO:- 1 | Failed to call the API.| +**System capability**: SystemCapability.BundleManager.Zlib + +| Name | Value | Description | +| ---------------- | ---- | ------------ | +| ERROR_CODE_OK | 0 | The API is successfully called.| +| ERROR_CODE_ERRNO | -1 | Failed to call the API.| diff --git a/en/application-dev/reference/arkui-js/Readme-EN.md b/en/application-dev/reference/arkui-js/Readme-EN.md index f0b0e7b6c9d76f3380dd78f21c92108c969f9e77..a34f071f9db1d0b438bfad4ac0461ef2ef7e0b25 100644 --- a/en/application-dev/reference/arkui-js/Readme-EN.md +++ b/en/application-dev/reference/arkui-js/Readme-EN.md @@ -1,110 +1,103 @@ # JavaScript-based Web-like Development Paradigm -- Components - - Common - - [Universal Attributes](js-components-common-attributes.md) - - [Universal Styles](js-components-common-styles.md) - - [Universal Events](js-components-common-events.md) - - [Universal Methods](js-components-common-methods.md) - - [Animation Styles](js-components-common-animation.md) - - [Gradient Styles](js-components-common-gradient.md) - - [Transition Styles](js-components-common-transition.md) - - [Media Query](js-components-common-mediaquery.md) - - [Custom Font Styles](js-components-common-customizing-font.md) - - [Atomic Layout](js-components-common-atomic-layout.md) +- Universal Component Information + - [Universal Attributes](js-components-common-attributes.md) + - [Universal Styles](js-components-common-styles.md) + - [Universal Events](js-components-common-events.md) + - [Universal Methods](js-components-common-methods.md) + - [Animation Styles](js-components-common-animation.md) + - [Gradient Styles](js-components-common-gradient.md) + - [Transition Styles](js-components-common-transition.md) + - [Media Query](js-components-common-mediaquery.md) + - [Custom Font Styles](js-components-common-customizing-font.md) + - [Atomic Layout](js-components-common-atomic-layout.md) +- Container Components + - [badge](js-components-container-badge.md) + - [dialog](js-components-container-dialog.md) + - [div](js-components-container-div.md) + - [form](js-components-container-form.md) + - [list](js-components-container-list.md) + - [list-item](js-components-container-list-item.md) + - [list-item-group](js-components-container-list-item-group.md) + - [panel](js-components-container-panel.md) + - [popup](js-components-container-popup.md) + - [refresh](js-components-container-refresh.md) + - [stack](js-components-container-stack.md) + - [stepper](js-components-container-stepper.md) + - [stepper-item](js-components-container-stepper-item.md) + - [swiper](js-components-container-swiper.md) + - [tabs](js-components-container-tabs.md) + - [tab-bar](js-components-container-tab-bar.md) + - [tab-content](js-components-container-tab-content.md) +- Basic Components + - [button](js-components-basic-button.md) + - [chart](js-components-basic-chart.md) + - [divider](js-components-basic-divider.md) + - [image](js-components-basic-image.md) + - [image-animator](js-components-basic-image-animator.md) + - [input](js-components-basic-input.md) + - [label](js-components-basic-label.md) + - [marquee](js-components-basic-marquee.md) + - [menu](js-components-basic-menu.md) + - [option](js-components-basic-option.md) + - [picker](js-components-basic-picker.md) + - [picker-view](js-components-basic-picker-view.md) + - [piece](js-components-basic-piece.md) + - [progress](js-components-basic-progress.md) + - [qrcode](js-components-basic-qrcode.md) + - [rating](js-components-basic-rating.md) + - [richtext](js-components-basic-richtext.md) + - [search](js-components-basic-search.md) + - [select](js-components-basic-select.md) + - [slider](js-components-basic-slider.md) + - [span](js-components-basic-span.md) + - [switch](js-components-basic-switch.md) + - [text](js-components-basic-text.md) + - [textarea](js-components-basic-textarea.md) + - [toolbar](js-components-basic-toolbar.md) + - [toolbar-item](js-components-basic-toolbar-item.md) + - [toggle](js-components-basic-toggle.md) + - [web](js-components-basic-web.md) +- Media Components + - [video](js-components-media-video.md) +- Canvas Components + - [canvas](js-components-canvas-canvas.md) + - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) + - [Image](js-components-canvas-image.md) + - [CanvasGradient](js-components-canvas-canvasgradient.md) + - [ImageData](js-components-canvas-imagedata.md) + - [Path2D](js-components-canvas-path2d.md) + - [ImageBitmap](js-components-canvas-imagebitmap.md) + - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) + - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) +- Grid Components + - [Basic Concepts](js-components-grid-basic-concepts.md) + - [grid-container](js-components-grid-container.md) + - [grid-row](js-components-grid-row.md) + - [grid-col](js-components-grid-col.md) +- SVG Components + - [Universal Attributes](js-components-svg-common-attributes.md) + - [svg](js-components-svg.md) + - [rect](js-components-svg-rect.md) + - [circle](js-components-svg-circle.md) + - [ellipse](js-components-svg-ellipse.md) + - [path](js-components-svg-path.md) + - [line](js-components-svg-line.md) + - [polyline](js-components-svg-polyline.md) + - [polygon](js-components-svg-polygon.md) + - [text](js-components-svg-text.md) + - [tspan](js-components-svg-tspan.md) + - [textPath](js-components-svg-textpath.md) + - [animate](js-components-svg-animate.md) + - [animateMotion](js-components-svg-animatemotion.md) + - [animateTransform](js-components-svg-animatetransform.md) - - Container Component - - [badge](js-components-container-badge.md) - - [dialog](js-components-container-dialog.md) - - [div](js-components-container-div.md) - - [form](js-components-container-form.md) - - [list](js-components-container-list.md) - - [list-item](js-components-container-list-item.md) - - [list-item-group](js-components-container-list-item-group.md) - - [panel](js-components-container-panel.md) - - [popup](js-components-container-popup.md) - - [refresh](js-components-container-refresh.md) - - [stack](js-components-container-stack.md) - - [stepper](js-components-container-stepper.md) - - [stepper-item](js-components-container-stepper-item.md) - - [swiper](js-components-container-swiper.md) - - [tabs](js-components-container-tabs.md) - - [tab-bar](js-components-container-tab-bar.md) - - [tab-content](js-components-container-tab-content.md) - - - Basic Components - - [button](js-components-basic-button.md) - - [chart](js-components-basic-chart.md) - - [divider](js-components-basic-divider.md) - - [image](js-components-basic-image.md) - - [image-animator](js-components-basic-image-animator.md) - - [input](js-components-basic-input.md) - - [label](js-components-basic-label.md) - - [marquee](js-components-basic-marquee.md) - - [menu](js-components-basic-menu.md) - - [option](js-components-basic-option.md) - - [picker](js-components-basic-picker.md) - - [picker-view](js-components-basic-picker-view.md) - - [piece](js-components-basic-piece.md) - - [progress](js-components-basic-progress.md) - - [qrcode](js-components-basic-qrcode.md) - - [rating](js-components-basic-rating.md) - - [richtext](js-components-basic-richtext.md) - - [search](js-components-basic-search.md) - - [select](js-components-basic-select.md) - - [slider](js-components-basic-slider.md) - - [span](js-components-basic-span.md) - - [switch](js-components-basic-switch.md) - - [text](js-components-basic-text.md) - - [textarea](js-components-basic-textarea.md) - - [toolbar](js-components-basic-toolbar.md) - - [toolbar-item](js-components-basic-toolbar-item.md) - - [toggle](js-components-basic-toggle.md) - - [web](js-components-basic-web.md) - - - Media Components - - [video](js-components-media-video.md) - - - Canvas Components - - [canvas](js-components-canvas-canvas.md) - - [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md) - - [Image](js-components-canvas-image.md) - - [CanvasGradient](js-components-canvas-canvasgradient.md) - - [ImageData](js-components-canvas-imagedata.md) - - [Path2D](js-components-canvas-path2d.md) - - [ImageBitmap](js-components-canvas-imagebitmap.md) - - [OffscreenCanvas](js-components-canvas-offscreencanvas.md) - - [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md) - - - Grid - - [Basic Concepts](js-components-grid-basic-concepts.md) - - [grid-container](js-components-grid-container.md) - - [grid-row](js-components-grid-row.md) - - [grid-col](js-components-grid-col.md) - - - SVG Components - - [Universal Attributes](js-components-svg-common-attributes.md) - - [svg](js-components-svg.md) - - [rect](js-components-svg-rect.md) - - [circle](js-components-svg-circle.md) - - [ellipse](js-components-svg-ellipse.md) - - [path](js-components-svg-path.md) - - [line](js-components-svg-line.md) - - [polyline](js-components-svg-polyline.md) - - [polygon](js-components-svg-polygon.md) - - [text](js-components-svg-text.md) - - [tspan](js-components-svg-tspan.md) - - [textPath](js-components-svg-textpath.md) - - [animate](js-components-svg-animate.md) - - [animateMotion](js-components-svg-animatemotion.md) - - [animateTransform](js-components-svg-animatetransform.md) - Custom Components - - [Basic Usage](js-components-custom-basic-usage.md) - - [Custom Events](js-components-custom-events.md) - - [props](js-components-custom-props.md) - - [Event Parameter](js-components-custom-event-parameter.md) - - [slot](js-components-custom-slot.md) - - [Lifecycle Definition](js-components-custom-lifecycle.md) -- [Type Attributes](js-appendix-types.md) - + - [Basic Usage](js-components-custom-basic-usage.md) + - [Custom Events](js-components-custom-events.md) + - [props](js-components-custom-props.md) + - [Event Parameter](js-components-custom-event-parameter.md) + - [slot](js-components-custom-slot.md) + - [Lifecycle Definition](js-components-custom-lifecycle.md) +- [Data Type Attributes](js-appendix-types.md) diff --git a/en/application-dev/reference/arkui-js/js-appendix-types.md b/en/application-dev/reference/arkui-js/js-appendix-types.md index 66b9939d938719f5b5178d347309e58c9dd5c764..335bb726f6a1e9d3cd86adf0b5d54c493f4eb15e 100644 --- a/en/application-dev/reference/arkui-js/js-appendix-types.md +++ b/en/application-dev/reference/arkui-js/js-appendix-types.md @@ -1,169 +1,167 @@ -# Type Attributes +# Data Type Attributes ## Length Type -| Name | Type | Description | -| ---------- | ---------------- | ------------------------------------------------------------ | -| length | string \| number | Size unit. When the type is **number**, the unit is px. When the type is **string**, the pixel unit needs to be explicitly specified. Currently, the following pixel units are supported:
- **px**: logical size unit.
- **fp**6+: font size unit, which varies according to the system font size. Only text components support the setting of the font size. | -| percentage | string | Unit in percentage, for example, **50%**. | +| Name | Type | Description | +| ---------- | -------------------------- | ---------------------------------------- | +| length | string \| number | Size unit. When the type is **number**, the unit is px. When the type is **string**, the pixel unit needs to be explicitly specified. Currently, the following pixel units are supported:
- **px**: logical size unit.
- **fp**6+: font size unit, which varies with the system font size. This unit is only available for text components.| +| percentage | string | Unit in percentage, for example, **50%**. | -## Color Type - -| Name | Type | Description | -| ----- | ---------------------------------- | ------------------------------------------------------------ | -| color | string \| Color enumeration values | Color information.
The String format is as follows:
- 'rgb(255, 255, 255)'
- 'rgba(255, 255, 255, 1.0)'
- HEX formats: #rrggbb and #aarrggbb
- Enumeration format: 'black' and 'white'
NOTE:
The enumeration format is not supported in the JS script. | -**Table 1** Currently supported colors - -| Name | Hexadecimal Code | Color | -| -------------------- | ---------------- | ------------------------------------------------------------ | -| aliceblue | \#f0f8ff | ![en-us_image_0000001173324803](figures/en-us_image_0000001173324803.png) | -| antiquewhite | \#faebd7 | ![en-us_image_0000001127285014](figures/en-us_image_0000001127285014.png) | -| aqua | \#00ffff | ![en-us_image_0000001127285050](figures/en-us_image_0000001127285050.png) | -| aquamarine | \#7fffd4 | ![en-us_image_0000001173324729](figures/en-us_image_0000001173324729.png) | -| azure | \#f0ffff | ![en-us_image_0000001127285040](figures/en-us_image_0000001127285040.png) | -| beige | \#f5f5dc | ![en-us_image_0000001173324773](figures/en-us_image_0000001173324773.png) | -| bisque | \#ffe4c4 | ![en-us_image_0000001173164895](figures/en-us_image_0000001173164895.png) | -| black | \#000000 | ![en-us_image_0000001173324735](figures/en-us_image_0000001173324735.png) | -| blanchedalmond | \#ffebcd | ![en-us_image_0000001173164889](figures/en-us_image_0000001173164889.png) | -| blue | \#0000ff | ![en-us_image_0000001127125194](figures/en-us_image_0000001127125194.png) | -| blueviolet | \#8a2be2 | ![en-us_image_0000001127285046](figures/en-us_image_0000001127285046.png) | -| brown | \#a52a2a | ![en-us_image_0000001173324833](figures/en-us_image_0000001173324833.png) | -| burlywood | \#deB887 | ![en-us_image_0000001127285026](figures/en-us_image_0000001127285026.png) | -| cadetblue | \#5f9ea0 | ![en-us_image_0000001127125210](figures/en-us_image_0000001127125210.png) | -| chartreuse | \#7fff00 | ![en-us_image_0000001173324811](figures/en-us_image_0000001173324811.png) | -| chocolate | \#d2691e | ![en-us_image_0000001127125256](figures/en-us_image_0000001127125256.png) | -| coral | \#ff7f50 | ![en-us_image_0000001173164877](figures/en-us_image_0000001173164877.png) | -| cornflowerblue | \#6495ed | ![en-us_image_0000001173324781](figures/en-us_image_0000001173324781.png) | -| cornsilk | \#fff8dc | ![en-us_image_0000001127285048](figures/en-us_image_0000001127285048.png) | -| crimson | \#dc143c | ![en-us_image_0000001127285066](figures/en-us_image_0000001127285066.png) | -| cyan | \#00ffff | ![en-us_image_0000001173324789](figures/en-us_image_0000001173324789.png) | -| darkblue | \#00008b | ![en-us_image_0000001173164841](figures/en-us_image_0000001173164841.png) | -| darkcyan | \#008b8b | ![en-us_image_0000001173324745](figures/en-us_image_0000001173324745.png) | -| darkgoldenrod | \#b8860b | ![en-us_image_0000001173324835](figures/en-us_image_0000001173324835.png) | -| darkgray | \#a9a9a9 | ![en-us_image_0000001127285028](figures/en-us_image_0000001127285028.png) | -| darkgreen | \#006400 | ![en-us_image_0000001127284990](figures/en-us_image_0000001127284990.png) | -| darkgrey | \#a9a9a9 | ![en-us_image_0000001127125174](figures/en-us_image_0000001127125174.png) | -| darkkhaki | \#bdb76b | ![en-us_image_0000001127285070](figures/en-us_image_0000001127285070.png) | -| darkmagenta | \#8b008b | ![en-us_image_0000001173164875](figures/en-us_image_0000001173164875.png) | -| darkolivegreen | \#556b2f | ![en-us_image_0000001173164835](figures/en-us_image_0000001173164835.png) | -| darkorange | \#ff8c00 | ![en-us_image_0000001127125178](figures/en-us_image_0000001127125178.png) | -| darkorchid | \#9932cc | ![en-us_image_0000001173324829](figures/en-us_image_0000001173324829.png) | -| darkred | \#8b0000 | ![en-us_image_0000001173164851](figures/en-us_image_0000001173164851.png) | -| darksalmon | \#e9967a | ![en-us_image_0000001127284998](figures/en-us_image_0000001127284998.png) | -| darkseagreen | \#8fbc8f | ![en-us_image_0000001173324755](figures/en-us_image_0000001173324755.png) | -| darkslateblue | \#483d8b | ![en-us_image_0000001127125246](figures/en-us_image_0000001127125246.png) | -| darkslategray | \#2f4f4f | ![en-us_image_0000001127125190](figures/en-us_image_0000001127125190.png) | -| darkslategrey | \#2f4f4f | ![en-us_image_0000001173324759](figures/en-us_image_0000001173324759.png) | -| darkturquoise | \#00ced1 | ![en-us_image_0000001127284980](figures/en-us_image_0000001127284980.png) | -| darkviolet | \#9400d3 | ![en-us_image_0000001127285058](figures/en-us_image_0000001127285058.png) | -| deeppink | \#ff1493 | ![en-us_image_0000001173324767](figures/en-us_image_0000001173324767.png) | -| deepskyblue | \#00bfff | ![en-us_image_0000001173164897](figures/en-us_image_0000001173164897.png) | -| dimgray | \#696969 | ![en-us_image_0000001127285022](figures/en-us_image_0000001127285022.png) | -| dimgrey | \#696969 | ![en-us_image_0000001173164911](figures/en-us_image_0000001173164911.png) | -| dodgerblue | \#1e90ff | ![en-us_image_0000001173164855](figures/en-us_image_0000001173164855.png) | -| firebrick | \#b22222 | ![en-us_image_0000001127125234](figures/en-us_image_0000001127125234.png) | -| floralwhite | \#fffaf0 | ![en-us_image_0000001173324771](figures/en-us_image_0000001173324771.png) | -| forestgreen | \#228b22 | ![en-us_image_0000001173324825](figures/en-us_image_0000001173324825.png) | -| fuchsia | \#ff00ff | ![en-us_image_0000001127285052](figures/en-us_image_0000001127285052.png) | -| gainsboro | \#dcdcdc | ![en-us_image_0000001173164901](figures/en-us_image_0000001173164901.png) | -| ghostwhite | \#f8f8ff | ![en-us_image_0000001127285012](figures/en-us_image_0000001127285012.png) | -| gold | \#ffd700 | ![en-us_image_0000001173324761](figures/en-us_image_0000001173324761.png) | -| goldenrod | \#daa520 | ![en-us_image_0000001173324817](figures/en-us_image_0000001173324817.png) | -| gray | \#808080 | ![en-us_image_0000001127125238](figures/en-us_image_0000001127125238.png) | -| green | \#008000 | ![en-us_image_0000001173164865](figures/en-us_image_0000001173164865.png) | -| greenyellow | \#adff2f | ![en-us_image_0000001127285000](figures/en-us_image_0000001127285000.png) | -| grey | \#808080 | ![en-us_image_0000001127285054](figures/en-us_image_0000001127285054.png) | -| honeydew | \#f0fff0 | ![en-us_image_0000001173324813](figures/en-us_image_0000001173324813.png) | -| hotpink | \#ff69b4 | ![en-us_image_0000001127285016](figures/en-us_image_0000001127285016.png) | -| indianred | \#cd5c5c | ![en-us_image_0000001173164849](figures/en-us_image_0000001173164849.png) | -| indigo | \#4b0082 | ![en-us_image_0000001173324821](figures/en-us_image_0000001173324821.png) | -| ivory | \#fffff0 | ![en-us_image_0000001173164887](figures/en-us_image_0000001173164887.png) | -| khaki | \#f0e68c | ![en-us_image_0000001173324801](figures/en-us_image_0000001173324801.png) | -| lavender | \#e6e6fa | ![en-us_image_0000001127125188](figures/en-us_image_0000001127125188.png) | -| lavenderblush | \#fff0f5 | ![en-us_image_0000001173324809](figures/en-us_image_0000001173324809.png) | -| lawngreen | \#7cfc00 | ![en-us_image_0000001127125224](figures/en-us_image_0000001127125224.png) | -| lemonchiffon | \#fffacd | ![en-us_image_0000001173164879](figures/en-us_image_0000001173164879.png) | -| lightblue | \#add8e6 | ![en-us_image_0000001127125180](figures/en-us_image_0000001127125180.png) | -| lightcoral | \#f08080 | ![en-us_image_0000001127125228](figures/en-us_image_0000001127125228.png) | -| lightcyan | \#e0ffff | ![en-us_image_0000001173324799](figures/en-us_image_0000001173324799.png) | -| lightgoldenrodyellow | \#fafad2 | ![en-us_image_0000001127125218](figures/en-us_image_0000001127125218.png) | -| lightgray | \#d3d3d3 | ![en-us_image_0000001127284974](figures/en-us_image_0000001127284974.png) | -| lightgreen | \#90ee90 | ![en-us_image_0000001173324805](figures/en-us_image_0000001173324805.png) | -| lightpink | \#ffb6c1 | ![en-us_image_0000001127285038](figures/en-us_image_0000001127285038.png) | -| lightsalmon | \#ffa07a | ![en-us_image_0000001173324795](figures/en-us_image_0000001173324795.png) | -| lightseagreen | \#20b2aa | ![en-us_image_0000001173324737](figures/en-us_image_0000001173324737.png) | -| lightskyblue | \#87cefa | ![en-us_image_0000001127285042](figures/en-us_image_0000001127285042.png) | -| lightslategray | \#778899 | ![en-us_image_0000001127125226](figures/en-us_image_0000001127125226.png) | -| lightslategrey | \#778899 | ![en-us_image_0000001127125222](figures/en-us_image_0000001127125222.png) | -| lightsteelblue | \#b0c4de | ![en-us_image_0000001127284976](figures/en-us_image_0000001127284976.png) | -| lightyellow | \#ffffe0 | ![en-us_image_0000001173324807](figures/en-us_image_0000001173324807.png) | -| lime | \#00ff00 | ![en-us_image_0000001127285020](figures/en-us_image_0000001127285020.png) | -| limegreen | \#32cd32 | ![en-us_image_0000001127125236](figures/en-us_image_0000001127125236.png) | -| linen | \#faf0e6 | ![en-us_image_0000001173324739](figures/en-us_image_0000001173324739.png) | -| magenta | \#ff00ff | ![en-us_image_0000001127285044](figures/en-us_image_0000001127285044.png) | -| maroon | \#800000 | ![en-us_image_0000001127285018](figures/en-us_image_0000001127285018.png) | -| mediumaquamarine | \#66cdaa | ![en-us_image_0000001173164899](figures/en-us_image_0000001173164899.png) | -| mediumblue | \#0000cd | ![en-us_image_0000001127284968](figures/en-us_image_0000001127284968.png) | -| mediumorchid | \#ba55d3 | ![en-us_image_0000001127125216](figures/en-us_image_0000001127125216.png) | -| mediumpurple | \#9370db | ![en-us_image_0000001173324779](figures/en-us_image_0000001173324779.png) | -| mediumseagreen | \#3cb371 | ![en-us_image_0000001127125230](figures/en-us_image_0000001127125230.png) | -| mediumslateblue | \#7b68ee | ![en-us_image_0000001173164921](figures/en-us_image_0000001173164921.png) | -| mediumspringgreen | \#00fa9a | ![en-us_image_0000001173324793](figures/en-us_image_0000001173324793.png) | -| mediumturquoise | \#48d1cc | ![en-us_image_0000001127125214](figures/en-us_image_0000001127125214.png) | -| mediumvioletred | \#c71585 | ![en-us_image_0000001173164893](figures/en-us_image_0000001173164893.png) | -| midnightblue | \#191970 | ![en-us_image_0000001127125260](figures/en-us_image_0000001127125260.png) | -| mintcream | \#f5fffa | ![en-us_image_0000001127285030](figures/en-us_image_0000001127285030.png) | -| mistyrose | \#ffe4e1 | ![en-us_image_0000001173324785](figures/en-us_image_0000001173324785.png) | -| moccasin | \#ffe4b5 | ![en-us_image_0000001127125232](figures/en-us_image_0000001127125232.png) | -| navajowhite | \#ffdead | ![en-us_image_0000001173164925](figures/en-us_image_0000001173164925.png) | -| navy | \#000080 | ![en-us_image_0000001127285032](figures/en-us_image_0000001127285032.png) | -| oldlace | \#fdf5e6 | ![en-us_image_0000001127125184](figures/en-us_image_0000001127125184.png) | -| olive | \#808000 | ![en-us_image_0000001127125244](figures/en-us_image_0000001127125244.png) | -| olivedrab | \#6b8e23 | ![en-us_image_0000001173324839](figures/en-us_image_0000001173324839.png) | -| orange | \#ffa500 | ![en-us_image_0000001173164885](figures/en-us_image_0000001173164885.png) | -| orangered | \#ff4500 | ![en-us_image_0000001127284996](figures/en-us_image_0000001127284996.png) | -| orchid | \#da70d6 | ![en-us_image_0000001127285056](figures/en-us_image_0000001127285056.png) | -| palegoldenrod | \#eee8aa | ![en-us_image_0000001127125262](figures/en-us_image_0000001127125262.png) | -| palegreen | \#98fb98 | ![en-us_image_0000001127285006](figures/en-us_image_0000001127285006.png) | -| paleturquoise | \#afeeee | ![en-us_image_0000001173324757](figures/en-us_image_0000001173324757.png) | -| palevioletred | \#db7093 | ![en-us_image_0000001173164905](figures/en-us_image_0000001173164905.png) | -| papayawhip | \#ffefd5 | ![en-us_image_0000001127125248](figures/en-us_image_0000001127125248.png) | -| peachpuff | \#ffdab9 | ![en-us_image_0000001173324769](figures/en-us_image_0000001173324769.png) | -| peru | \#cd853f | ![en-us_image_0000001173164843](figures/en-us_image_0000001173164843.png) | -| pink | \#ffc0cb | ![en-us_image_0000001127125242](figures/en-us_image_0000001127125242.png) | -| plum | \#dda0dd | ![en-us_image_0000001173324831](figures/en-us_image_0000001173324831.png) | -| powderblue | \#b0e0e6 | ![en-us_image_0000001127285010](figures/en-us_image_0000001127285010.png) | -| purple | \#800080 | ![en-us_image_0000001127285002](figures/en-us_image_0000001127285002.png) | -| rebeccapurple | \#663399 | ![en-us_image_0000001173164907](figures/en-us_image_0000001173164907.png) | -| red | \#ff0000 | ![en-us_image_0000001127125254](figures/en-us_image_0000001127125254.png) | -| rosybrown | \#bc8f8f | ![en-us_image_0000001173324775](figures/en-us_image_0000001173324775.png) | -| royalblue | \#4169e1 | ![en-us_image_0000001127284972](figures/en-us_image_0000001127284972.png) | -| saddlebrown | \#8b4513 | ![en-us_image_0000001127125250](figures/en-us_image_0000001127125250.png) | -| salmon | \#fa8072 | ![en-us_image_0000001127285064](figures/en-us_image_0000001127285064.png) | -| sandybrown | \#f4a460 | ![en-us_image_0000001173324777](figures/en-us_image_0000001173324777.png) | -| seagreen | \#2e8b57 | ![en-us_image_0000001173324733](figures/en-us_image_0000001173324733.png) | -| seashell | \#fff5ee | ![en-us_image_0000001127285062](figures/en-us_image_0000001127285062.png) | -| sienna | \#a0522d | ![en-us_image_0000001173164917](figures/en-us_image_0000001173164917.png) | -| silver | \#c0c0c0 | ![en-us_image_0000001173324743](figures/en-us_image_0000001173324743.png) | -| skyblue | \#87ceeb | ![en-us_image_0000001127284970](figures/en-us_image_0000001127284970.png) | -| slateblue | \#6a5acd | ![en-us_image_0000001173164915](figures/en-us_image_0000001173164915.png) | -| slategray | \#708090 | ![en-us_image_0000001173324815](figures/en-us_image_0000001173324815.png) | -| slategrey | \#708090 | ![en-us_image_0000001127284982](figures/en-us_image_0000001127284982.png) | -| snow | \#fffafa | ![en-us_image_0000001173324731](figures/en-us_image_0000001173324731.png) | -| springgreen | \#00ff7f | ![en-us_image_0000001127285060](figures/en-us_image_0000001127285060.png) | -| steelblue | \#4682b4 | ![en-us_image_0000001127125240](figures/en-us_image_0000001127125240.png) | -| tan | \#d2b48c | ![en-us_image_0000001173324747](figures/en-us_image_0000001173324747.png) | -| teal | \#008080 | ![en-us_image_0000001173324741](figures/en-us_image_0000001173324741.png) | -| thistle | \#d8Bfd8 | ![en-us_image_0000001173164913](figures/en-us_image_0000001173164913.png) | -| tomato | \#ff6347 | ![en-us_image_0000001173164909](figures/en-us_image_0000001173164909.png) | -| turquoise | \#40e0d0 | ![en-us_image_0000001173164837](figures/en-us_image_0000001173164837.png) | -| violet | \#ee82ee | ![en-us_image_0000001127125258](figures/en-us_image_0000001127125258.png) | -| wheat | \#f5deb3 | ![en-us_image_0000001127285068](figures/en-us_image_0000001127285068.png) | -| white | \#ffffff | ![en-us_image_0000001173324823](figures/en-us_image_0000001173324823.png) | -| whitesmoke | \#f5f5f5 | ![en-us_image_0000001127284992](figures/en-us_image_0000001127284992.png) | -| yellow | \#ffff00 | ![en-us_image_0000001173324837](figures/en-us_image_0000001173324837.png) | -| yellowgreen | \#9acd32 | ![en-us_image_0000001173164923](figures/en-us_image_0000001173164923.png) | +## Color Type +| Name | Type | Description | +| ----- | --------------------- | ---------------------------------------- | +| color | string \|  color enums| Color information. The color enums are not supported in JavaScript scripts.
Available string formats are as follows:
- 'rgb(255, 255, 255)'
- 'rgba(255, 255, 255, 1.0)'
- HEX format: '\#rrggbb', '\#aarrggbb'
- Enumeration format: 'black','white'.| +**Table 1** Color enums +| Name | Hexadecimal Code | Color | +| -------------------- | -------- | ---------------------------------------- | +| aliceblue | \#f0f8ff | ![en-us_image_0000001173324803](figures/en-us_image_0000001173324803.png) | +| antiquewhite | \#faebd7 | ![en-us_image_0000001127285014](figures/en-us_image_0000001127285014.png) | +| aqua | \#00ffff | ![en-us_image_0000001127285050](figures/en-us_image_0000001127285050.png) | +| aquamarine | \#7fffd4 | ![en-us_image_0000001173324729](figures/en-us_image_0000001173324729.png) | +| azure | \#f0ffff | ![en-us_image_0000001127285040](figures/en-us_image_0000001127285040.png) | +| beige | \#f5f5dc | ![en-us_image_0000001173324773](figures/en-us_image_0000001173324773.png) | +| bisque | \#ffe4c4 | ![en-us_image_0000001173164895](figures/en-us_image_0000001173164895.png) | +| black | \#000000 | ![en-us_image_0000001173324735](figures/en-us_image_0000001173324735.png) | +| blanchedalmond | \#ffebcd | ![en-us_image_0000001173164889](figures/en-us_image_0000001173164889.png) | +| blue | \#0000ff | ![en-us_image_0000001127125194](figures/en-us_image_0000001127125194.png) | +| blueviolet | \#8a2be2 | ![en-us_image_0000001127285046](figures/en-us_image_0000001127285046.png) | +| brown | \#a52a2a | ![en-us_image_0000001173324833](figures/en-us_image_0000001173324833.png) | +| burlywood | \#deB887 | ![en-us_image_0000001127285026](figures/en-us_image_0000001127285026.png) | +| cadetblue | \#5f9ea0 | ![en-us_image_0000001127125210](figures/en-us_image_0000001127125210.png) | +| chartreuse | \#7fff00 | ![en-us_image_0000001173324811](figures/en-us_image_0000001173324811.png) | +| chocolate | \#d2691e | ![en-us_image_0000001127125256](figures/en-us_image_0000001127125256.png) | +| coral | \#ff7f50 | ![en-us_image_0000001173164877](figures/en-us_image_0000001173164877.png) | +| cornflowerblue | \#6495ed | ![en-us_image_0000001173324781](figures/en-us_image_0000001173324781.png) | +| cornsilk | \#fff8dc | ![en-us_image_0000001127285048](figures/en-us_image_0000001127285048.png) | +| crimson | \#dc143c | ![en-us_image_0000001127285066](figures/en-us_image_0000001127285066.png) | +| cyan | \#00ffff | ![en-us_image_0000001173324789](figures/en-us_image_0000001173324789.png) | +| darkblue | \#00008b | ![en-us_image_0000001173164841](figures/en-us_image_0000001173164841.png) | +| darkcyan | \#008b8b | ![en-us_image_0000001173324745](figures/en-us_image_0000001173324745.png) | +| darkgoldenrod | \#b8860b | ![en-us_image_0000001173324835](figures/en-us_image_0000001173324835.png) | +| darkgray | \#a9a9a9 | ![en-us_image_0000001127285028](figures/en-us_image_0000001127285028.png) | +| darkgreen | \#006400 | ![en-us_image_0000001127284990](figures/en-us_image_0000001127284990.png) | +| darkgrey | \#a9a9a9 | ![en-us_image_0000001127125174](figures/en-us_image_0000001127125174.png) | +| darkkhaki | \#bdb76b | ![en-us_image_0000001127285070](figures/en-us_image_0000001127285070.png) | +| darkmagenta | \#8b008b | ![en-us_image_0000001173164875](figures/en-us_image_0000001173164875.png) | +| darkolivegreen | \#556b2f | ![en-us_image_0000001173164835](figures/en-us_image_0000001173164835.png) | +| darkorange | \#ff8c00 | ![en-us_image_0000001127125178](figures/en-us_image_0000001127125178.png) | +| darkorchid | \#9932cc | ![en-us_image_0000001173324829](figures/en-us_image_0000001173324829.png) | +| darkred | \#8b0000 | ![en-us_image_0000001173164851](figures/en-us_image_0000001173164851.png) | +| darksalmon | \#e9967a | ![en-us_image_0000001127284998](figures/en-us_image_0000001127284998.png) | +| darkseagreen | \#8fbc8f | ![en-us_image_0000001173324755](figures/en-us_image_0000001173324755.png) | +| darkslateblue | \#483d8b | ![en-us_image_0000001127125246](figures/en-us_image_0000001127125246.png) | +| darkslategray | \#2f4f4f | ![en-us_image_0000001127125190](figures/en-us_image_0000001127125190.png) | +| darkslategrey | \#2f4f4f | ![en-us_image_0000001173324759](figures/en-us_image_0000001173324759.png) | +| darkturquoise | \#00ced1 | ![en-us_image_0000001127284980](figures/en-us_image_0000001127284980.png) | +| darkviolet | \#9400d3 | ![en-us_image_0000001127285058](figures/en-us_image_0000001127285058.png) | +| deeppink | \#ff1493 | ![en-us_image_0000001173324767](figures/en-us_image_0000001173324767.png) | +| deepskyblue | \#00bfff | ![en-us_image_0000001173164897](figures/en-us_image_0000001173164897.png) | +| dimgray | \#696969 | ![en-us_image_0000001127285022](figures/en-us_image_0000001127285022.png) | +| dimgrey | \#696969 | ![en-us_image_0000001173164911](figures/en-us_image_0000001173164911.png) | +| dodgerblue | \#1e90ff | ![en-us_image_0000001173164855](figures/en-us_image_0000001173164855.png) | +| firebrick | \#b22222 | ![en-us_image_0000001127125234](figures/en-us_image_0000001127125234.png) | +| floralwhite | \#fffaf0 | ![en-us_image_0000001173324771](figures/en-us_image_0000001173324771.png) | +| forestgreen | \#228b22 | ![en-us_image_0000001173324825](figures/en-us_image_0000001173324825.png) | +| fuchsia | \#ff00ff | ![en-us_image_0000001127285052](figures/en-us_image_0000001127285052.png) | +| gainsboro | \#dcdcdc | ![en-us_image_0000001173164901](figures/en-us_image_0000001173164901.png) | +| ghostwhite | \#f8f8ff | ![en-us_image_0000001127285012](figures/en-us_image_0000001127285012.png) | +| gold | \#ffd700 | ![en-us_image_0000001173324761](figures/en-us_image_0000001173324761.png) | +| goldenrod | \#daa520 | ![en-us_image_0000001173324817](figures/en-us_image_0000001173324817.png) | +| gray | \#808080 | ![en-us_image_0000001127125238](figures/en-us_image_0000001127125238.png) | +| green | \#008000 | ![en-us_image_0000001173164865](figures/en-us_image_0000001173164865.png) | +| greenyellow | \#adff2f | ![en-us_image_0000001127285000](figures/en-us_image_0000001127285000.png) | +| grey | \#808080 | ![en-us_image_0000001127285054](figures/en-us_image_0000001127285054.png) | +| honeydew | \#f0fff0 | ![en-us_image_0000001173324813](figures/en-us_image_0000001173324813.png) | +| hotpink | \#ff69b4 | ![en-us_image_0000001127285016](figures/en-us_image_0000001127285016.png) | +| indianred | \#cd5c5c | ![en-us_image_0000001173164849](figures/en-us_image_0000001173164849.png) | +| indigo | \#4b0082 | ![en-us_image_0000001173324821](figures/en-us_image_0000001173324821.png) | +| ivory | \#fffff0 | ![en-us_image_0000001173164887](figures/en-us_image_0000001173164887.png) | +| khaki | \#f0e68c | ![en-us_image_0000001173324801](figures/en-us_image_0000001173324801.png) | +| lavender | \#e6e6fa | ![en-us_image_0000001127125188](figures/en-us_image_0000001127125188.png) | +| lavenderblush | \#fff0f5 | ![en-us_image_0000001173324809](figures/en-us_image_0000001173324809.png) | +| lawngreen | \#7cfc00 | ![en-us_image_0000001127125224](figures/en-us_image_0000001127125224.png) | +| lemonchiffon | \#fffacd | ![en-us_image_0000001173164879](figures/en-us_image_0000001173164879.png) | +| lightblue | \#add8e6 | ![en-us_image_0000001127125180](figures/en-us_image_0000001127125180.png) | +| lightcoral | \#f08080 | ![en-us_image_0000001127125228](figures/en-us_image_0000001127125228.png) | +| lightcyan | \#e0ffff | ![en-us_image_0000001173324799](figures/en-us_image_0000001173324799.png) | +| lightgoldenrodyellow | \#fafad2 | ![en-us_image_0000001127125218](figures/en-us_image_0000001127125218.png) | +| lightgray | \#d3d3d3 | ![en-us_image_0000001127284974](figures/en-us_image_0000001127284974.png) | +| lightgreen | \#90ee90 | ![en-us_image_0000001173324805](figures/en-us_image_0000001173324805.png) | +| lightpink | \#ffb6c1 | ![en-us_image_0000001127285038](figures/en-us_image_0000001127285038.png) | +| lightsalmon | \#ffa07a | ![en-us_image_0000001173324795](figures/en-us_image_0000001173324795.png) | +| lightseagreen | \#20b2aa | ![en-us_image_0000001173324737](figures/en-us_image_0000001173324737.png) | +| lightskyblue | \#87cefa | ![en-us_image_0000001127285042](figures/en-us_image_0000001127285042.png) | +| lightslategray | \#778899 | ![en-us_image_0000001127125226](figures/en-us_image_0000001127125226.png) | +| lightslategrey | \#778899 | ![en-us_image_0000001127125222](figures/en-us_image_0000001127125222.png) | +| lightsteelblue | \#b0c4de | ![en-us_image_0000001127284976](figures/en-us_image_0000001127284976.png) | +| lightyellow | \#ffffe0 | ![en-us_image_0000001173324807](figures/en-us_image_0000001173324807.png) | +| lime | \#00ff00 | ![en-us_image_0000001127285020](figures/en-us_image_0000001127285020.png) | +| limegreen | \#32cd32 | ![en-us_image_0000001127125236](figures/en-us_image_0000001127125236.png) | +| linen | \#faf0e6 | ![en-us_image_0000001173324739](figures/en-us_image_0000001173324739.png) | +| magenta | \#ff00ff | ![en-us_image_0000001127285044](figures/en-us_image_0000001127285044.png) | +| maroon | \#800000 | ![en-us_image_0000001127285018](figures/en-us_image_0000001127285018.png) | +| mediumaquamarine | \#66cdaa | ![en-us_image_0000001173164899](figures/en-us_image_0000001173164899.png) | +| mediumblue | \#0000cd | ![en-us_image_0000001127284968](figures/en-us_image_0000001127284968.png) | +| mediumorchid | \#ba55d3 | ![en-us_image_0000001127125216](figures/en-us_image_0000001127125216.png) | +| mediumpurple | \#9370db | ![en-us_image_0000001173324779](figures/en-us_image_0000001173324779.png) | +| mediumseagreen | \#3cb371 | ![en-us_image_0000001127125230](figures/en-us_image_0000001127125230.png) | +| mediumslateblue | \#7b68ee | ![en-us_image_0000001173164921](figures/en-us_image_0000001173164921.png) | +| mediumspringgreen | \#00fa9a | ![en-us_image_0000001173324793](figures/en-us_image_0000001173324793.png) | +| mediumturquoise | \#48d1cc | ![en-us_image_0000001127125214](figures/en-us_image_0000001127125214.png) | +| mediumvioletred | \#c71585 | ![en-us_image_0000001173164893](figures/en-us_image_0000001173164893.png) | +| midnightblue | \#191970 | ![en-us_image_0000001127125260](figures/en-us_image_0000001127125260.png) | +| mintcream | \#f5fffa | ![en-us_image_0000001127285030](figures/en-us_image_0000001127285030.png) | +| mistyrose | \#ffe4e1 | ![en-us_image_0000001173324785](figures/en-us_image_0000001173324785.png) | +| moccasin | \#ffe4b5 | ![en-us_image_0000001127125232](figures/en-us_image_0000001127125232.png) | +| navajowhite | \#ffdead | ![en-us_image_0000001173164925](figures/en-us_image_0000001173164925.png) | +| navy | \#000080 | ![en-us_image_0000001127285032](figures/en-us_image_0000001127285032.png) | +| oldlace | \#fdf5e6 | ![en-us_image_0000001127125184](figures/en-us_image_0000001127125184.png) | +| olive | \#808000 | ![en-us_image_0000001127125244](figures/en-us_image_0000001127125244.png) | +| olivedrab | \#6b8e23 | ![en-us_image_0000001173324839](figures/en-us_image_0000001173324839.png) | +| orange | \#ffa500 | ![en-us_image_0000001173164885](figures/en-us_image_0000001173164885.png) | +| orangered | \#ff4500 | ![en-us_image_0000001127284996](figures/en-us_image_0000001127284996.png) | +| orchid | \#da70d6 | ![en-us_image_0000001127285056](figures/en-us_image_0000001127285056.png) | +| palegoldenrod | \#eee8aa | ![en-us_image_0000001127125262](figures/en-us_image_0000001127125262.png) | +| palegreen | \#98fb98 | ![en-us_image_0000001127285006](figures/en-us_image_0000001127285006.png) | +| paleturquoise | \#afeeee | ![en-us_image_0000001173324757](figures/en-us_image_0000001173324757.png) | +| palevioletred | \#db7093 | ![en-us_image_0000001173164905](figures/en-us_image_0000001173164905.png) | +| papayawhip | \#ffefd5 | ![en-us_image_0000001127125248](figures/en-us_image_0000001127125248.png) | +| peachpuff | \#ffdab9 | ![en-us_image_0000001173324769](figures/en-us_image_0000001173324769.png) | +| peru | \#cd853f | ![en-us_image_0000001173164843](figures/en-us_image_0000001173164843.png) | +| pink | \#ffc0cb | ![en-us_image_0000001127125242](figures/en-us_image_0000001127125242.png) | +| plum | \#dda0dd | ![en-us_image_0000001173324831](figures/en-us_image_0000001173324831.png) | +| powderblue | \#b0e0e6 | ![en-us_image_0000001127285010](figures/en-us_image_0000001127285010.png) | +| purple | \#800080 | ![en-us_image_0000001127285002](figures/en-us_image_0000001127285002.png) | +| rebeccapurple | \#663399 | ![en-us_image_0000001173164907](figures/en-us_image_0000001173164907.png) | +| red | \#ff0000 | ![en-us_image_0000001127125254](figures/en-us_image_0000001127125254.png) | +| rosybrown | \#bc8f8f | ![en-us_image_0000001173324775](figures/en-us_image_0000001173324775.png) | +| royalblue | \#4169e1 | ![en-us_image_0000001127284972](figures/en-us_image_0000001127284972.png) | +| saddlebrown | \#8b4513 | ![en-us_image_0000001127125250](figures/en-us_image_0000001127125250.png) | +| salmon | \#fa8072 | ![en-us_image_0000001127285064](figures/en-us_image_0000001127285064.png) | +| sandybrown | \#f4a460 | ![en-us_image_0000001173324777](figures/en-us_image_0000001173324777.png) | +| seagreen | \#2e8b57 | ![en-us_image_0000001173324733](figures/en-us_image_0000001173324733.png) | +| seashell | \#fff5ee | ![en-us_image_0000001127285062](figures/en-us_image_0000001127285062.png) | +| sienna | \#a0522d | ![en-us_image_0000001173164917](figures/en-us_image_0000001173164917.png) | +| silver | \#c0c0c0 | ![en-us_image_0000001173324743](figures/en-us_image_0000001173324743.png) | +| skyblue | \#87ceeb | ![en-us_image_0000001127284970](figures/en-us_image_0000001127284970.png) | +| slateblue | \#6a5acd | ![en-us_image_0000001173164915](figures/en-us_image_0000001173164915.png) | +| slategray | \#708090 | ![en-us_image_0000001173324815](figures/en-us_image_0000001173324815.png) | +| slategrey | \#708090 | ![en-us_image_0000001127284982](figures/en-us_image_0000001127284982.png) | +| snow | \#fffafa | ![en-us_image_0000001173324731](figures/en-us_image_0000001173324731.png) | +| springgreen | \#00ff7f | ![en-us_image_0000001127285060](figures/en-us_image_0000001127285060.png) | +| steelblue | \#4682b4 | ![en-us_image_0000001127125240](figures/en-us_image_0000001127125240.png) | +| tan | \#d2b48c | ![en-us_image_0000001173324747](figures/en-us_image_0000001173324747.png) | +| teal | \#008080 | ![en-us_image_0000001173324741](figures/en-us_image_0000001173324741.png) | +| thistle | \#d8Bfd8 | ![en-us_image_0000001173164913](figures/en-us_image_0000001173164913.png) | +| tomato | \#ff6347 | ![en-us_image_0000001173164909](figures/en-us_image_0000001173164909.png) | +| turquoise | \#40e0d0 | ![en-us_image_0000001173164837](figures/en-us_image_0000001173164837.png) | +| violet | \#ee82ee | ![en-us_image_0000001127125258](figures/en-us_image_0000001127125258.png) | +| wheat | \#f5deb3 | ![en-us_image_0000001127285068](figures/en-us_image_0000001127285068.png) | +| white | \#ffffff | ![en-us_image_0000001173324823](figures/en-us_image_0000001173324823.png) | +| whitesmoke | \#f5f5f5 | ![en-us_image_0000001127284992](figures/en-us_image_0000001127284992.png) | +| yellow | \#ffff00 | ![en-us_image_0000001173324837](figures/en-us_image_0000001173324837.png) | +| yellowgreen | \#9acd32 | ![en-us_image_0000001173164923](figures/en-us_image_0000001173164923.png) | diff --git a/en/application-dev/reference/arkui-js/js-components-basic-chart.md b/en/application-dev/reference/arkui-js/js-components-basic-chart.md index ebab10a944e177004cc4e3cac1b24cbb0eed802e..d0d8ff99685cca3766232092038aeea999faba12 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-chart.md @@ -273,7 +273,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324843.png) + ![img](figures/en-us_image_0000001173324843.png) 2. Bar chart @@ -342,7 +342,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164929.png) + ![img](figures/en-us_image_0000001173164929.png) 3. Gauge chart @@ -372,4 +372,4 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125264.png) \ No newline at end of file + ![img](figures/en-us_image_0000001127125264.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md b/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md index c17bef00354066d929d50f9e44b55041e3d6c2cf..bbe50bce7e633eabb300e1895800d7b45c7a92ef 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image-animator.md @@ -183,4 +183,4 @@ export default { }; ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/image-animator.gif) \ No newline at end of file +![img](figures/image-animator.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-image.md b/en/application-dev/reference/arkui-js/js-components-basic-image.md index 6b73c08eac64d40a6884af868ea8a72aa0c96864..f908d7c39c9cc714e11ea2a13c654da99648faf4 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-image.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-image.md @@ -103,4 +103,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/example.gif) \ No newline at end of file +![img](figures/example.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index aebb55dea7cb9aac7eb1bf801d49c908db639c36..1f10982593566d8ad21467a9613d260ab6e6a3ec 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -1,106 +1,99 @@ # input +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. + The **\** component provides an interactive interface to receive user input. It can be a radio button, check box, button, single-line text box, and more. ## Required Permissions None -## Child Component - -Not supported - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Child Components +Not supported -| Name | Type | Default Value | Mandatory | Triggered when | -| --------------------- | -------------------------------------------------- | ------------- | --------- | ------------------------------------------------------------ | -| type | string | text | No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.The **button**, **checkbox**, and **radio** types cannot be dynamically modified. Available values include:
-**button**: a button that can be clicked
-**checkbox**: a check box
-**radio**: a radio button that allows users to select one from multiple others with the same name
-**text**: a single-line text field
-**email**: a field used for an email address
-**date**: date control, including the year, month, and day, but excluding time
-**time**: time control, without the time zone
-**number**: field for entering digits
-**password**: password field, in which characters will be shieldedNOTE:For wearables, only **button**, **radio**, and **checkbox** types are supported. | -| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | -| name | string | - | No | Name of the input component. | -| value | string | - | No | Value of the input component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. | -| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. | -| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. If no value is specified, the number of characters is not limited. | -| enterkeytype | string | default | No | Dynamic modification is not supported.Available values include:
-default
-next
-go
-done
-send
-Search
NOTE:The soft keyboard is automatically collapsed after you click the **Enter** button, except when **next** is displayed for the button. | -| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. | -| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | -| menuoptions5+ | Array\<[MenuOption](js-components-basic-input.md)> | - | No | Menu options displayed after users touch the **More** button. | -| autofocus6+ | boolean | false | No | Whether to automatically obtain the focus.NOTE:This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. | -| selectedstart6+ | number | -1 | No | Start position for text selection. | -| selectedend6+ | number | -1 | No | End position for text selection. | -| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | -| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. The setting is valid only when **type** is set to **password**. | - -**Table 1** MenuOption5+ +## Attributes +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory| Description | +| -------------------------------- | ----------------------- | --------- | ---- | ------------------------------------------------------------ | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit.| +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MeunOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | + +**Table 1** MenuOption5+ + +| Name | Type | Description | +| ------- | ------ | ----------- | +| icon | string | Path of the icon for a menu option.| +| content | string | Text content of a menu option.| -| Name | Type | Triggered when | -| ------- | ------ | ----------------------------------- | -| icon | string | Path of the icon for a menu option. | -| content | string | Text content of a menu option. | ## Styles -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. +| Name | Type | Default Value | Mandatory| Description | +| ------------------------ | -------------------------- | ---------- | ---- | ------------------------------------------------------------ | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md).| +| caret-color6+ | <color> | - | No | Color of the input cursor. | -| Name | Type | Default Value | Mandatory | Triggered when | -| ----------------- | ---------------- | ------------- | --------- | ------------------------------------------------------------ | -| color | \ | #e6000000 | No | Font color of the single-line text box or button. | -| font-size | \ | 16px | No | Font size of the single-line text box or button. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.NOTE:If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | -| placeholder-color | \ | #99000000 | No | Color of the hint text in the single-line text box. This attribute is available when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. | -| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see [font-weight](js-components-basic-text.md) of the **text** component. | -| caret-color6+ | \ | - | No | Color of the input cursor. | ## Events -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - -- When the input component type is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - - +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - | Name | Parameter | Triggered when | - | -------------- | ------------------------------------------ | ------------------------------------------------------------ | - | change | { value:inputValue } | Triggered when the content entered in the text box changes. The most recent text entered by the user is returned.NOTE:If you change the **value** attribute directly, this event will not be triggered. | - | enterkeyclick | { value:enterKey } | Triggered when the **Enter** key on a soft keyboard is pressed. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
-**2**: returned if **enterkeytype** is **go**.
-**3**: returned if **enterkeytype** is **search**.
-**4**: returned if **enterkeytype** is **send**.
-**5**: returned if **enterkeytype** is **next**.
-**6**: returned if **enterkeytype** is **default**, **done**, or is not set.
| - | translate5+ | { value: selectedText } | Triggered when users click the translate button in the pop menu displayed after they select a text segment. The selected text content is returned. | - | share5+ | { value: selectedText } | Triggered when users click the share button in the pop menu displayed after they select a text segment. The selected text content is returned. | - | search5+ | { value: selectedText } | Triggered when users click the search button in the pop menu displayed after they select a text segment. The selected text content is returned. | - | optionselect5+ | { index:optionIndex, value: selectedText } | Triggered when users click a menu option in the pop menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. | - | selectchange6+ | { start: number, end: number } | Triggered when the text selection changes. | +- When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. + | Name | Parameter | Description | + | ------------------------- | ---------------------------------------- | ---------------------------------------- | + | change | {
 value: inputValue
 } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| + | enterkeyclick | {
 value: enterKey
 } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| + | translate5+ | {
 value: selectedText
 } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| + | share5+ | {
 value: selectedText
 } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| + | search5+ | {
 value: selectedText
 } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| + | optionselect5+ | {
 index: optionIndex,
 value: selectedText
 } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| + | selectchange6+ | {
start: number,
end: number
 } | Triggered when the text selection changes. | -- When the input component type is set to **checkbox** or **radio**, the following events are supported. - - - - | Name | Parameter | Triggered when | - | ------ | ------------------------- | ------------------------------------------------------------ | - | change | { checked:true \| false } | Triggered when the checked status of the **checkbox** or **radio** button changes. | +- When **type** is set to **checkbox** or **radio**, the following events are supported. + | Name | Parameter | Description | + | ------ | ---------------------------------------- | ---------------------------------------- | + | change | {
 checked:true \| false 
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| ## Methods -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Triggered when | -| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| focus | {focus:true\|false}: If **focus** is not passed, the default value **true** is used. | Obtains or loses the focus of a component. When the component type is set to text, email, date, time, number, or password, the input method can be displayed or collapsed. | -| showError | { error: string } | Displays the error message. This attribute is available when the component type is set to text, email, date, time, number, or password. | -| delete6+ | - | Deletes the text content based on the current cursor position when the input component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. If the current input component does not have a cursor, the last character is deleted and the cursor is displayed by default. | +| Name | Parameter | Description | +| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| focus | {
 focus: true\|false
 }:
If **focus** is not passed, the default value **true** is used.| Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or password, the input method can be displayed or hidden.| +| showError | {
 error: string 
} | Displays the error message. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| +| delete6+ | - | Deletes the text content based on the current cursor position when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**; deletes the last character and displays the cursor if the current input component does not have a cursor.| -## Example Code +## Example 1. Single-line text box - - ``` + ```html
``` - ``` + ```css /* xxx.css */ .content { width: 60%; @@ -127,7 +120,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ``` + ```js // xxx.js import prompt from '@system.prompt' export default { @@ -151,24 +144,21 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/1-2.png) + ![1-2](figures/1-2.png) 2. Common button - - ``` + ```html
``` - ``` + ```css /* xxx.css */ .div-button { flex-direction: column; align-items: center; - - } .button { margin-top: 30px; @@ -176,31 +166,27 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001198898293.png) + ![en-us_image_0000001198898293](figures/en-us_image_0000001198898293.png) 3. Check box - - ``` + ```html
-
``` - ``` + ```css /* xxx.css */ .content{ width: 100%; height: 200px; - - align-items: center; justify-content: center; } ``` - ``` + ```js // xxx.js import prompt from '@system.prompt' export default { @@ -213,11 +199,10 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324749.png) + ![en-us_image_0000001173324749](figures/en-us_image_0000001173324749.png) 4. Radio button - - ``` + ```html
@@ -226,7 +211,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
``` - ``` + ```css /* xxx.css */ .content{ width: 100%; @@ -236,7 +221,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ``` + ```js // xxx.js import prompt from '@system.prompt' export default { @@ -251,4 +236,4 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/1-3.png) \ No newline at end of file + ![1-3](figures/1-3.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-label.md b/en/application-dev/reference/arkui-js/js-components-basic-label.md index c11333a9fc94b423f81c6c5e1ed491c6e9cf69d5..eef2bce9d40bc947896fd8a1ed40377e14666484 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-label.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-label.md @@ -89,4 +89,4 @@ Not supported } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152834002.png) \ No newline at end of file +![img](figures/en-us_image_0000001152834002.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md index 9f12052d05a725a0764a786abda833e209166efb..9f13895436ce5f1104994f9d6956deba5e04a928 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -1,67 +1,69 @@ # marquee -The **\** component displays single-line scrolling text. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> Since API version 6, the text scrolls only when its width exceeds the width of the **\** component. + +The **\** component is used to display a scrolling piece of text. ## Required Permissions None -## Child Component + +## Child Components Not supported -## Attributes -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. +## Attributes +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. +| Name | Type | Default Value | Mandatory | Description | +| ------------ | ------ | ---- | ---- | ---------------------------------------- | +| scrollamount | number | 6 | No | Maximum length of each scroll. | +| loop | number | -1 | No | Number of rolling times. If this parameter is not set, the default value **-1** is used. When the value is less than or equal to **0**, the marquee scrolls continuously.| +| direction | string | left | No | Direction in which the marquee scrolls, which can be **left** or **right**. | -| Name | Type | Default Value | Mandatory | Description | -| ------------ | ------ | ------------- | --------- | ------------------------------------------------------------ | -| scrollamount | number | 6 | No | Maximum length of each scroll. | -| loop | number | -1 | No | Number of rolling times. If this parameter is not set, the default value **-1** is used. When the value is less than or equal to **0**, the marquee scrolls continuously. | -| direction | string | left | No | Direction in which the marquee scrolls, which can be **left** or **right**. | ## Styles -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. +| Name | Type | Default Value | Mandatory | Description | +| ----------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| color | <color> | \#e5000000 | No | Font color of the scrolling text. | +| font-size | <length> | 37.5 | No | Font size of the scrolling text. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\ component](../arkui-js/js-components-basic-text.md#styles)**.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| -| Name | Type | Default Value | Mandatory | Description | -| ----------- | ---------------- | ------------- | --------- | ------------------------------------------------------------ | -| color | \ | #e5000000 | No | Font color of the scrolling text. | -| font-size | \ | 37.5 | No | Font size of the scrolling text. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.NOTE:If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | -| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see [font-weight](js-components-basic-text.md#section5775351116) of the **text** component. | -| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by [Custom Font Styles](js-components-common-customizing-font.md) in the family is selected as the font for the text. | - ## Events -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. -| Name | Parameter | Description | -| ------------ | --------- | ------------------------------------------------------------ | -| bounce(Rich) | - | Triggered when the marquee scrolls to the end. | -| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0. | -| start(Rich) | - | Triggered when the marquee starts to scroll. | +| Name | Parameter | Description | +| ------------ | ---- | ---------------------------------------- | +| bounce(Rich) | - | Triggered when the marquee scrolls to the end. | +| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.| +| start(Rich) | - | Triggered when the marquee starts to scroll. | ## Methods -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. +| Name | Parameter | Description | +| ----- | ---- | ----- | +| start | - | Starts scrolling.| +| stop | - | Stops scrolling.| -| Name | Parameter | Description | -| ----- | --------- | ----------------- | -| start | - | Starts scrolling. | -| stop | - | Stops scrolling. | +## Example -## Example Code - -``` +```html
Stop +``` + +```css /* xxx.css */ .container { flex-direction: column; @@ -99,6 +104,9 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m background-color: #F2F2F2; text-color: #0D81F2; } +``` + +```js // xxx.js export default { data: { @@ -125,4 +133,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/lite_bar.gif) \ No newline at end of file +![lite_bar](figures/lite_bar.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-menu.md b/en/application-dev/reference/arkui-js/js-components-basic-menu.md index 23a62f265cad23460faac818a6f811035c28eb36..fe75accae0842ae491aebdf021117b1138035548 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-menu.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-menu.md @@ -96,4 +96,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/menu13.gif) \ No newline at end of file +![img](figures/menu13.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md index 4f55dadba544c0c7c48d91e231a41fd61faa3119..d069266b48f0cd28c77e5c8770f89fd1b867dc76 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker-view.md @@ -192,4 +192,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/lite_bar-4.png) \ No newline at end of file +![img](figures/lite_bar-4.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index cdbc9d4d238bfe2e5c60418f56dcbe933bcf664f..6c50d6789a8ae7c3a85215ee3fa82c3ebc79ddd5 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -287,4 +287,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/mmmm.gif) \ No newline at end of file +![img](figures/mmmm.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-piece.md b/en/application-dev/reference/arkui-js/js-components-basic-piece.md index be89c5eafdfd65d36cccf0338c7e10523322a68e..11666b49f84e4ed29cb4ca9c9f325d8efe2348ea 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-piece.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-piece.md @@ -65,4 +65,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/11-5.gif) \ No newline at end of file +![img](figures/11-5.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-progress.md b/en/application-dev/reference/arkui-js/js-components-basic-progress.md index 4c8063d2c64e000c59e53edb3df1dc72f5169d91..db2432309121e8327ef25984ea0e0f7b33d4b905 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-progress.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-progress.md @@ -138,4 +138,4 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/progress.png) \ No newline at end of file +![img](figures/progress.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md b/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md index 47f23bea405cca4503d1c029ed1c79bd15a0b071..850efc33599916f6a90a6acf001e25b7c1c0dc57 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md @@ -108,4 +108,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/12.gif) \ No newline at end of file +![img](figures/12.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-rating.md b/en/application-dev/reference/arkui-js/js-components-basic-rating.md index 69067f89342380940966728966c1ab518ab6590d..f120f8fef0082993b9f8aeaaae2a817ac04af9bb 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-rating.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-rating.md @@ -82,4 +82,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/1-6.png) \ No newline at end of file +![img](figures/1-6.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-search.md b/en/application-dev/reference/arkui-js/js-components-basic-search.md index 6b9c7ceccfb95035d0b7e1507b5c827529dd443c..860df0847434d8cfaefe688e9dd4c96e267e348e 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-search.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-search.md @@ -80,4 +80,4 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001153427082.png) \ No newline at end of file +![img](figures/en-us_image_0000001153427082.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-select.md b/en/application-dev/reference/arkui-js/js-components-basic-select.md index 965668a261be86d8f0c9d3b654630ccfd41fca4a..99d9f7906386b257620cfec8b01bbe54b4b1049a 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-select.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-select.md @@ -67,4 +67,4 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152588538.png) \ No newline at end of file +![img](figures/en-us_image_0000001152588538.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-slider.md b/en/application-dev/reference/arkui-js/js-components-basic-slider.md index 7b69be3ec4127e4b416314452f4d4ded85cd67bd..506301abbff476ed96544e1a6faebf2e44a1f1ef 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-slider.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-slider.md @@ -96,4 +96,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/slider.png) \ No newline at end of file +![img](figures/slider.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-span.md b/en/application-dev/reference/arkui-js/js-components-basic-span.md index b894bc9123548cbeceda39420871f51d2fe45fe7..de34e6d85ae7de460e53da457aff469509894350 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-span.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-span.md @@ -67,4 +67,4 @@ Not supported } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152588626.png) \ No newline at end of file +![img](figures/en-us_image_0000001152588626.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-switch.md b/en/application-dev/reference/arkui-js/js-components-basic-switch.md index 9dceb0f89dc7d0c9ae4f4c9db57d4380b0c29b96..32baae42a0bcd5a877ee0421ea15c3af2831e470 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-switch.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-switch.md @@ -94,4 +94,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152862510.gif) \ No newline at end of file +![img](figures/en-us_image_0000001152862510.gif) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-text.md b/en/application-dev/reference/arkui-js/js-components-basic-text.md index 353b70f0dff192433c0e2ce78adc9b009566e7a4..26f65c6a925cd369646254c2550c82d944420287 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-text.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-text.md @@ -102,7 +102,7 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/3.png) +![img](figures/3.png) ``` @@ -138,4 +138,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/2.png) \ No newline at end of file +![img](figures/2.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-textarea.md b/en/application-dev/reference/arkui-js/js-components-basic-textarea.md index e5a4846b529559a756505a69d23c4a1427329083..3e89cac3505b5bcd35b4a60aeea290ecae872e5b 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-textarea.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-textarea.md @@ -98,4 +98,4 @@ change(e){ } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/000000.png) \ No newline at end of file +![img](figures/000000.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-toggle.md b/en/application-dev/reference/arkui-js/js-components-basic-toggle.md index 83e25006778be1a220faa75853b67f44c9c62053..e2f4767d3ad061cd265d8799443ea288e50a764d 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-toggle.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-toggle.md @@ -102,4 +102,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/screenshot.png) \ No newline at end of file +![img](figures/screenshot.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-basic-toolbar-item.md b/en/application-dev/reference/arkui-js/js-components-basic-toolbar-item.md index 3a8f59f80f45665fd0d86dfa2678dce279059b3a..fa0c77c83d8affe11a97391bde0f6eeb26c9e706 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-toolbar-item.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-toolbar-item.md @@ -64,4 +64,4 @@ Not supported ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/progress-7.jpg) \ No newline at end of file +![img](figures/progress-7.jpg) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 9e0019f99dcb114627747916c206aeaae2cdc458..bd6b16c2bd8e1f56a53c5c588ada704371ce6a16 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -40,4 +40,4 @@ Adds a color stop for the** CanvasGradient** object based on the specified offse } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001152610806.png) \ No newline at end of file + ![img](figures/en-us_image_0000001152610806.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index fc885a6a4a1a5955418275afc785cfa0dfe9ed98..f3ede6c1ec2980d9053ad552e4d29ca4987aaa87 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -1,6 +1,6 @@ # CanvasRenderingContext2D -> ![icon-note.gif](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/public_sys-resources/icon-note.gif) **NOTE** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. **CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas. @@ -38,11 +38,11 @@ - Anti-aliasing disabled - ![en-us_image_0000001214837333](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214837333.png) + ![en-us_image_0000001214837333](figures/en-us_image_0000001214837333.png) - Anti-aliasing enabled - ![screenshot-8](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/screenshot-8.png) + ![screenshot-8](figures/screenshot-8.png) ## Attributes @@ -55,7 +55,7 @@ | [lineJoin](js-components-canvas-canvasrenderingcontext2d.md) | string | miter | Style of the intersection point between line segments. The options are as follows:
-**round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
-**miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**. | | [miterLimit](js-components-canvas-canvasrenderingcontext2d.md) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | | [font](js-components-canvas-canvasrenderingcontext2d.md) | string | "normal normal 14px sans-serif" | Font style. Syntax: ctx.font="font-style font-weight font-size font-family"5+
-(Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**. | -| [textAlign](js-components-canvas-canvasrenderingcontext2d.md) | string | left | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
-**right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
>![icon-note.gif](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/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**. | +| [textAlign](js-components-canvas-canvasrenderingcontext2d.md) | string | left | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
-**right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
>![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**. | | [textBaseline](js-components-canvas-canvasrenderingcontext2d.md) | string | alphabetic | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
-**hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
- **ideographic**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | | [globalAlpha](js-components-canvas-canvasrenderingcontext2d.md) | number | - | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | | [lineDashOffset](js-components-canvas-canvasrenderingcontext2d.md) | number | 0.0 | Offset of the dashed line. The precision is float. | @@ -85,7 +85,7 @@ export default { } ``` -![en-us_image_0000001166962736](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001166962736.png) +![en-us_image_0000001166962736](figures/en-us_image_0000001166962736.png) ### lineWidth @@ -105,7 +105,7 @@ export default { } ``` -![en-us_image_0000001166484430](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001166484430.png) +![en-us_image_0000001166484430](figures/en-us_image_0000001166484430.png) ### strokeStyle @@ -126,7 +126,7 @@ export default { } ``` -![en-us_image_0000001212124299](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001212124299.png) +![en-us_image_0000001212124299](figures/en-us_image_0000001212124299.png) ### lineCap @@ -150,7 +150,7 @@ export default { } ``` -![en-us_image_0000001214837127](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214837127.png) +![en-us_image_0000001214837127](figures/en-us_image_0000001214837127.png) ### lineJoin @@ -175,7 +175,7 @@ export default { } ``` -![en-us_image_0000001214717247](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214717247.png) +![en-us_image_0000001214717247](figures/en-us_image_0000001214717247.png) ### miterLimit @@ -200,7 +200,7 @@ export default { } ``` -![en-us_image_0000001167001464](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167001464.png) +![en-us_image_0000001167001464](figures/en-us_image_0000001167001464.png) ### font @@ -220,7 +220,7 @@ export default { } ``` -![en-us_image_0000001167046832](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167046832.png) +![en-us_image_0000001167046832](figures/en-us_image_0000001167046832.png) ### textAlign @@ -254,7 +254,7 @@ export default { } ``` -![en-us_image_0000001167472798](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167472798.png) +![en-us_image_0000001167472798](figures/en-us_image_0000001167472798.png) ### textBaseline @@ -287,7 +287,7 @@ export default { } ``` -![en-us_image_0000001169315920](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169315920.png) +![en-us_image_0000001169315920](figures/en-us_image_0000001169315920.png) ### globalAlpha @@ -311,7 +311,7 @@ export default { } ``` -![en-us_image_0000001167953648](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167953648.png) +![en-us_image_0000001167953648](figures/en-us_image_0000001167953648.png) ### lineDashOffset @@ -333,7 +333,7 @@ export default { } ``` -![en-us_image_0000001167950468](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167950468.png) +![en-us_image_0000001167950468](figures/en-us_image_0000001167950468.png) ### globalCompositeOperation @@ -380,7 +380,7 @@ export default { } ``` -![en-us_image_0000001213192781](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001213192781.png) +![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. @@ -404,7 +404,7 @@ export default { } ``` -![en-us_image_0000001168111514](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001168111514.png) +![en-us_image_0000001168111514](figures/en-us_image_0000001168111514.png) ### shadowColor @@ -426,7 +426,7 @@ export default { } ``` -![en-us_image_0000001168111610](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001168111610.png) +![en-us_image_0000001168111610](figures/en-us_image_0000001168111610.png) ### shadowOffsetX @@ -449,7 +449,7 @@ export default { } ``` -![en-us_image_0000001167631876](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001167631876.png) +![en-us_image_0000001167631876](figures/en-us_image_0000001167631876.png) ### shadowOffsetY @@ -472,7 +472,7 @@ export default { } ``` -![en-us_image_0000001213193285](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001213193285.png) +![en-us_image_0000001213193285](figures/en-us_image_0000001213193285.png) ### imageSmoothingEnabled6+ @@ -496,7 +496,7 @@ export default { } ``` -![smoothoff](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/smoothoff.png) +![smoothoff](figures/smoothoff.png) ## Methods @@ -532,7 +532,7 @@ export default { } ``` -![en-us_image_0000001214811029](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214811029.png) +![en-us_image_0000001214811029](figures/en-us_image_0000001214811029.png) ### clearRect @@ -571,7 +571,7 @@ Clears the content in a rectangle on the canvas. } ``` - ![en-us_image_0000001214619417](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214619417.png) + ![en-us_image_0000001214619417](figures/en-us_image_0000001214619417.png) ### strokeRect @@ -608,7 +608,7 @@ Draws a rectangle stroke on the canvas. } ``` - ![en-us_image_0000001214822091](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214822091.png) + ![en-us_image_0000001214822091](figures/en-us_image_0000001214822091.png) ### fillText @@ -645,7 +645,7 @@ Draws filled text on the canvas. } ``` - ![en-us_image_0000001214469787](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214469787.png) + ![en-us_image_0000001214469787](figures/en-us_image_0000001214469787.png) ### strokeText @@ -682,7 +682,7 @@ Draws a text stroke on the canvas. } ``` - ![en-us_image_0000001214460669](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214460669.png) + ![en-us_image_0000001214460669](figures/en-us_image_0000001214460669.png) ### measureText @@ -725,7 +725,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text. } ``` - ![en-us_image_0000001169142476](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169142476.png) + ![en-us_image_0000001169142476](figures/en-us_image_0000001169142476.png) ### stroke @@ -757,7 +757,7 @@ Draws a stroke. } ``` - ![en-us_image_0000001236697937](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001236697937.png) + ![en-us_image_0000001236697937](figures/en-us_image_0000001236697937.png) ### beginPath @@ -790,7 +790,7 @@ Creates a drawing path. } ``` - ![en-us_image_0000001214629745](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214629745.png) + ![en-us_image_0000001214629745](figures/en-us_image_0000001214629745.png) ### moveTo @@ -828,7 +828,7 @@ Moves a drawing path to a target position on the canvas. } ``` - ![en-us_image_0000001169309948](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169309948.png) + ![en-us_image_0000001169309948](figures/en-us_image_0000001169309948.png) ### lineTo @@ -866,7 +866,7 @@ Connects the current point to a target position using a straight line. } ``` - ![en-us_image_0000001169469914](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169469914.png) + ![en-us_image_0000001169469914](figures/en-us_image_0000001169469914.png) ### closePath @@ -899,7 +899,7 @@ Draws a closed path. } ``` - ![en-us_image_0000001169151508](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169151508.png) + ![en-us_image_0000001169151508](figures/en-us_image_0000001169151508.png) ### createPattern @@ -944,7 +944,7 @@ Creates a pattern for image filling based on a specified source image and repeti } ``` - ![en-us_image_0000001169301188](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169301188.png) + ![en-us_image_0000001169301188](figures/en-us_image_0000001169301188.png) ### bezierCurveTo @@ -986,7 +986,7 @@ Draws a cubic bezier curve on the canvas. } ``` - ![en-us_image_0000001214621177](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214621177.png) + ![en-us_image_0000001214621177](figures/en-us_image_0000001214621177.png) ### quadraticCurveTo @@ -1026,7 +1026,7 @@ Draws a quadratic curve on the canvas. } ``` - ![en-us_image_0000001169461910](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169461910.png) + ![en-us_image_0000001169461910](figures/en-us_image_0000001169461910.png) ### arc @@ -1067,7 +1067,7 @@ Draws an arc on the canvas. } ``` - ![en-us_image_0000001169470288](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169470288.png) + ![en-us_image_0000001169470288](figures/en-us_image_0000001169470288.png) ### arcTo @@ -1107,7 +1107,7 @@ Draws an arc based on the radius and points on the arc. } ``` - ![en-us_image_0000001169143586](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169143586.png) + ![en-us_image_0000001169143586](figures/en-us_image_0000001169143586.png) ### ellipse6+ @@ -1150,7 +1150,7 @@ Draws an ellipse in the specified rectangular region on the canvas. } ``` - ![ellipse](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/ellipse.png) + ![ellipse](figures/ellipse.png) ### rect @@ -1188,7 +1188,7 @@ Creates a rectangle on the canvas. } ``` - ![en-us_image_0000001214630783](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214630783.png) + ![en-us_image_0000001214630783](figures/en-us_image_0000001214630783.png) ### fill @@ -1217,7 +1217,7 @@ Fills the area inside a closed path on the canvas. } ``` - ![en-us_image_0000001214703717](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214703717.png) + ![en-us_image_0000001214703717](figures/en-us_image_0000001214703717.png) ### clip @@ -1250,7 +1250,7 @@ Sets the current path to a clipping path. } ``` - ![en-us_image_0000001169303414](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169303414.png) + ![en-us_image_0000001169303414](figures/en-us_image_0000001169303414.png) ### rotate @@ -1285,7 +1285,7 @@ Rotates a canvas clockwise around its coordinate axes. } ``` - ![en-us_image_0000001169463368](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169463368.png) + ![en-us_image_0000001169463368](figures/en-us_image_0000001169463368.png) ### scale @@ -1322,7 +1322,7 @@ Scales the canvas based on scale factors. } ``` - ![en-us_image_0000001214463281](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214463281.png) + ![en-us_image_0000001214463281](figures/en-us_image_0000001214463281.png) ### transform @@ -1330,7 +1330,7 @@ transform(scaleX: number, skewX: number, skewY: number, scale: number, translate Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. -> ![icon-note.gif](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/public_sys-resources/icon-note.gif) **NOTE** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > 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 @@ -1374,7 +1374,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para } ``` - ![en-us_image_0000001214623227](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214623227.png) + ![en-us_image_0000001214623227](figures/en-us_image_0000001214623227.png) ### setTransform @@ -1417,7 +1417,7 @@ Resets the existing transformation matrix and creates a new transformation matri } ``` - ![en-us_image_0000001168984880](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001168984880.png) + ![en-us_image_0000001168984880](figures/en-us_image_0000001168984880.png) ### translate @@ -1454,7 +1454,7 @@ Moves the origin of the coordinate system. } ``` - ![en-us_image_0000001169144864](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169144864.png) + ![en-us_image_0000001169144864](figures/en-us_image_0000001169144864.png) ### createPath2D6+ @@ -1500,7 +1500,7 @@ Creates a **Path2D** object. } ``` - ![en-us_image_0000001214824709](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214824709.png) + ![en-us_image_0000001214824709](figures/en-us_image_0000001214824709.png) ### drawImage @@ -1544,7 +1544,7 @@ Draws an image on the canvas. } ``` - ![en-us_image_0000001214704759](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214704759.png) + ![en-us_image_0000001214704759](figures/en-us_image_0000001214704759.png) ### restore @@ -1648,7 +1648,7 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details, } ``` - ![en-us_image_0000001169303416](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169303416.png) + ![en-us_image_0000001169303416](figures/en-us_image_0000001169303416.png) ### createRadialGradient6+ @@ -1702,7 +1702,7 @@ Creates a radial gradient and returns a **CanvasGradient** object. } ``` - ![en-us_image_0000001169463370](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001169463370.png) + ![en-us_image_0000001169463370](figures/en-us_image_0000001169463370.png) ### createImageData @@ -1831,7 +1831,7 @@ Puts the **ImageData** onto a rectangular area on the canvas. } ``` - ![en-us_image_0000001214463283](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214463283.png) + ![en-us_image_0000001214463283](figures/en-us_image_0000001214463283.png) ### setLineDash @@ -1867,7 +1867,7 @@ Sets the dash line style. } ``` - ![en-us_image_0000001214623229](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001214623229.png) + ![en-us_image_0000001214623229](figures/en-us_image_0000001214623229.png) ### getLineDash @@ -1939,4 +1939,4 @@ Displays the specified **ImageBitmap** object. } ``` - ![en-us_image_0000001168984882](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001168984882.png) \ No newline at end of file + ![en-us_image_0000001168984882](figures/en-us_image_0000001168984882.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-image.md b/en/application-dev/reference/arkui-js/js-components-canvas-image.md index c4f54cbc505f8b1b0390d347c53c74075fab277c..a91df2450a037bba1d2093d3d7051cbc3d6491c0 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-image.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-image.md @@ -39,4 +39,4 @@ export default { } ``` -![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/1-9.png) \ No newline at end of file +![img](figures/1-9.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md index 08353c55f4d15eb001f4141e5e2e7f057bb2d075..2ac27755648d8e6052888ea6ba4d0c6f8c4cbd0a 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md @@ -39,7 +39,7 @@ Adds a path to this path. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164873.png) + ![img](figures/en-us_image_0000001173164873.png) ## setTransform @@ -82,7 +82,7 @@ Sets the path transformation matrix. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125208.png) + ![img](figures/en-us_image_0000001127125208.png) ## closePath @@ -115,7 +115,7 @@ Moves the current point of the path back to the start point of the path, and dra } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125202.png) + ![img](figures/en-us_image_0000001127125202.png) ## moveTo @@ -157,7 +157,7 @@ Moves the current coordinate point of the path to the target point, without draw } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164869.png) + ![img](figures/en-us_image_0000001173164869.png) ## lineTo @@ -200,7 +200,7 @@ Draws a straight line from the current point to the target point. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127285024.png) + ![img](figures/en-us_image_0000001127285024.png) ## bezierCurveTo @@ -244,7 +244,7 @@ Draws a cubic bezier curve on the canvas. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324783.png) + ![img](figures/en-us_image_0000001173324783.png) ## quadraticCurveTo @@ -286,7 +286,7 @@ Draws a quadratic curve on the canvas. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164871.png) + ![img](figures/en-us_image_0000001173164871.png) ## arc @@ -329,7 +329,7 @@ Draws an arc on the canvas. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173164867.png) + ![img](figures/en-us_image_0000001173164867.png) ## arcTo @@ -371,7 +371,7 @@ Draws an arc based on the radius and points on the arc. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125204.png) + ![img](figures/en-us_image_0000001127125204.png) ## ellipse @@ -416,7 +416,7 @@ Draws an ellipse in the specified rectangular region. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001173324787.png) + ![img](figures/en-us_image_0000001173324787.png) ## rect @@ -457,4 +457,4 @@ Creates a rectangle. } ``` - ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/reference/arkui-js/figures/en-us_image_0000001127125212.png) \ No newline at end of file + ![img](figures/en-us_image_0000001127125212.png) \ No newline at end of file diff --git a/en/application-dev/reference/arkui-js/js-components-common-animation.md b/en/application-dev/reference/arkui-js/js-components-common-animation.md index daa287ac149995c87c1a5477d24a0823f46a840b..24676a73232a85ae609e6ea07b403bdd78961bb4 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-animation.md +++ b/en/application-dev/reference/arkui-js/js-components-common-animation.md @@ -2,14 +2,16 @@ Components support dynamic rotation, translation, and scaling effects. These effects can be set in the **style** attribute or CSS files. - +> **NOTE** +> +> The initial APIs of this component are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. | Name | Type | Default Value | Description | | ------------------------- | ------------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------ | | transform-origin | string6+ \| \ \| \ string6+ \| \ \| \ | center center | Origin position of the transformed element. The unit can be px or a percentage (relative to the animation target component). If only one value is specified, the other one is **50%**. The available values for the first string are **left**, **center**, and **right**. The available values for the second string are **top**, **center**, and **bottom**.
Example:
transform-origin: 200px 30%
transform-origin: 100px topt
ransform-origin: center center | -| transform | string | - | Translation, rotation, and scaling attributes.
For details, see [Table 1](js-components-common-animation.md). | +| transform | string | - | Translation, rotation, and scaling attributes.
For details, see **transform**. | | animation6+ | string | 0s ease 0s 1 normal none running none | Animation attributes in the format of **duration \| timing-function \| delay \| iteration-count \| direction \| fill-mode \| play-state \| name**. The order of the parameters is not specified, but the **duration** and **delay** parameters are parsed based on where they are placed. | -| animation-name | string | - | @keyframes rule. For details, see [Table 2](js-components-common-animation.md). | +| animation-name | string | - | @keyframes rule. For details, see **@keyframes**. | | animation-delay | \