diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 7216f9a9553638f840ec25e395e01e7169cec824..fe61907695916c62d805c964d47724e54f50b35c 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -20,23 +20,22 @@ - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) - - Basic Feature Development - - [Common Event and Notification](notification/Readme-EN.md) - - [Window Manager](windowmanager/Readme-EN.md) - - [WebGL](webgl/Readme-EN.md) - - [Media](media/Readme-EN.md) - - [Security](security/Readme-EN.md) - - [Connectivity](connectivity/Readme-EN.md) - - [Data Management](database/Readme-EN.md) - - [Telephony](telephony/Readme-EN.md) - - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) - - [Background Task Management](background-task-management/Readme-EN.md) - - [Work Scheduler](work-scheduler/Readme-EN.md) - - [Device Management](device/Readme-EN.md) - - [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) + - [Common Event and Notification](notification/Readme-EN.md) + - [Window Manager](windowmanager/Readme-EN.md) + - [WebGL](webgl/Readme-EN.md) + - [Media](media/Readme-EN.md) + - [Security](security/Readme-EN.md) + - [Connectivity](connectivity/Readme-EN.md) + - [Data Management](database/Readme-EN.md) + - [Telephony](telephony/Readme-EN.md) + - [Agent-Powered Scheduled Reminders](background-agent-scheduled-reminder/Readme-EN.md) + - [Background Task Management](background-task-management/Readme-EN.md) + - [Work Scheduler](work-scheduler/Readme-EN.md) + - [Device Management](device/Readme-EN.md) + - [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) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index b930a33717318765c26a10ac022fa4b1e617d15f..ba5279cd72999b994bbc306b93a019592dcf1fbe 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -3,17 +3,14 @@ ## Widget Overview A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider - The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. -- Widget host - The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. -- Widget Manager - The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. @@ -25,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: - Develop the lifecycle callbacks in **LifecycleForm**. -- Create a **FormBindingData** object. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. @@ -41,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. | +| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. | For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -76,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li export default { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -89,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li console.log('FormAbility onCastToNormal'); }, onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -119,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li } ``` -### Configuring config.json for the Form Ability +### Configuring the Widget Configuration File -Configure the **config.json** file for the **Form** ability. +Configure the **config.json** file for the widget. -- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows: +- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows: | Field| Description | Data Type| Default | | -------- | ------------------------------------------------------------ | -------- | ------------------------ | @@ -156,12 +153,12 @@ Configure the **config.json** file for the **Form** ability. | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | - | formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | + | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | @@ -198,7 +195,7 @@ Configure the **config.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Store Widget Data Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. @@ -210,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -225,9 +223,11 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget instance. + // The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples". + deleteFormInfo(formId); } ``` @@ -235,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. -Normal widget: a widget that will be persistently used by the widget host +- Normal widget: a widget that will be persistently used by the widget host -Temporary widget: a widget that is temporarily used by the widget host +- Temporary widget: a widget that is temporarily used by the widget host Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - HML: @@ -326,10 +326,8 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example - -The following sample is provided to help you better understand how to develop a widget on the FA model: - -[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) +## Samples -This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. +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/stage-ability.md b/en/application-dev/ability/stage-ability.md index 024be022ed65db076ea0771cef50744fed303ca9..4dfe6cf0e1ef001bdd72d4ae362baadc5d155d63 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -1,18 +1,14 @@ # Ability Development ## When to Use -The stage model is an application development model introduced in API version 9. For details about this model, see [Stage Model Overview](stage-brief.md). To develop an ability based on the stage model, you must implement the following logic: -- Create Page abilities for an application that needs to be browsed on the screen and supports man-machine interaction, such as video playback and news browsing. -- Obtain ability configuration information, such as **ApplicationInfo**, **AbilityInfo**, and **HapModuleInfo**. -- Start an ability, start an ability with start options, start an ability with the returned result, or start an ability with an account ID. -- Request certain permissions from end users. -- Notify the ability stage and ability of environment configuration changes. -- Call common components. For details, see [Call Development](stage-call.md). -- Connect to and disconnect from the Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md). -- Continue the application on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). +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. +- 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. -The **launchType** item in the **module.json** file is used to specify the 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. | Launch Type | Description |Description | | ----------- | ------- |---------------- | @@ -20,56 +16,49 @@ The **launchType** item in the **module.json** file is used to specify the launc | singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| -By default, **singleton** is used. - -## Available APIs -The table below describes the APIs provided by the **AbilityStage** class, which has the **context** attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). +By default, the singleton mode is used. The following is an example of the `module.json` file: +```json +{ + "module": { + "abilities": [ + { + "launchType": "singleton", + } + ] + } +} +``` +## Creating an Ability +### Available APIs +The table below describes the APIs provided by the `AbilityStage` class, which has the `context` attribute. For details about the APIs, see [AbilityStage](../reference/apis/js-apis-application-abilitystage.md). **Table 1** AbilityStage APIs |API|Description| |:------|:------| -|void onCreate()|Called when an ability stage is created.| -|string onAcceptWant(want: Want)|Called when a specified ability is started.| -|void onConfigurationUpdated(config: Configuration)|Called when the global configuration is updated.| +|onCreate(): void|Called when an ability stage is created.| +|onAcceptWant(want: Want): string|Called when a specified ability is started.| +|onConfigurationUpdated(config: Configuration): void|Called when the global configuration is updated.| -The table below describes the APIs provided by the **Ability** class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). +The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 2** Ability APIs |API|Description| |:------|:------| -|void onCreate(want: Want, param: AbilityConstant.LaunchParam)|Called when an ability is created.| -|void onDestroy()|Called when the ability is destroyed.| -|void onWindowStageCreate(windowStage: window.WindowStage)|Called when a **WindowStage** is created for the ability. You can use the **window.WindowStage** APIs to implement operations such as page loading.| -|void onWindowStageDestroy()|Called when the **WindowStage** is destroyed for the ability.| -|void onForeground()|Called when the ability is running in the foreground.| -|void onBackground()|Called when the ability is switched to the background.| -|void onNewWant(want: Want)|Called when the ability startup mode is set to singleton.| -|void onConfigurationUpdated(config: Configuration)|Called when the configuration of the environment where the ability is running is updated.| - -The **Ability** class has the **context** attribute, which belongs to the **AbilityContext** class. The **AbilityContext** class has attributes such as **abilityInfo** and **currentHapModuleInfo**. For details about the APIs, see [AbilityContext](../reference/apis/js-apis-ability-context.md). - -**Table 3** AbilityContext APIs -|API|Description| -|:------|:------| -|void startAbility(want: Want, callback: AsyncCallback\)|Starts an ability.| -|void startAbility(want: Want, options: StartOptions, callback: AsyncCallback\)|Starts an ability with start options.| -|void startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\)|Starts an ability with the account ID.| -|void startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\)|Starts an ability with the account ID and start options.| -|void startAbilityForResult(want: Want, callback: AsyncCallback\)|Starts an ability with the returned result.| -|void startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback\)|Starts an ability with the returned result and start options.| -|void startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\)|Starts an ability with the returned result and account ID.| -|void startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\)|Starts an ability with the returned result, account ID, and start options.| -|void terminateSelf(callback: AsyncCallback\)|Destroys the Page ability.| -|void terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\)|Destroys the Page ability with the returned result.| - -## How to Develop -### Creating Page Abilities for an Application -To create Page abilities for an application on the stage model, you must implement the **AbilityStage** class and ability lifecycle callbacks, and use the **Window** APIs to set the pages. The sample code is as follows: -1. Import the **AbilityStage** module. +|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| +|onDestroy(): void|Called when the ability is destroyed.| +|onWindowStageCreate(windowStage: window.WindowStage): void|Called when a `WindowStage` is created for the ability. You can use the `window.WindowStage` APIs to implement operations such as page loading.| +|onWindowStageDestroy(): void|Called when the `WindowStage` is destroyed for the ability.| +|onForeground(): void|Called when the ability is switched to the foreground.| +|onBackground(): void|Called when the ability is switched to the background.| +|onNewWant(want: Want): void|Called when the ability launch type is set to `singleton`.| +|onConfigurationUpdated(config: Configuration): void|Called when the configuration of the environment where the ability is running is updated.| +### Implementing AbilityStage and Ability Lifecycle Callbacks +To create Page abilities for an application in the stage model, you must implement the `AbilityStage` class and ability lifecycle callbacks, and use the `Window` APIs to set the pages. The sample code is as follows: +1. Import the `AbilityStage` module. ``` import AbilityStage from "@ohos.application.AbilityStage" ``` -2. Implement the **AbilityStage** class. +2. Implement the `AbilityStage` class. ```ts export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -77,48 +66,48 @@ To create Page abilities for an application on the stage model, you must impleme } } ``` -3. Import the **Ability** module. +3. Import the `Ability` module. ```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. - In the **onWindowStageCreate(windowStage)** API, use **loadContent** to set the pages to be loaded by the application. For details about how to use the **Window** APIs, see [Window Development](../windowmanager/window-guidelines.md). + 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 export default class MainAbility extends Ability { onCreate(want, launchParam) { console.log("MainAbility onCreate") } - + onDestroy() { console.log("MainAbility onDestroy") } - + onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - + windowStage.loadContent("pages/index").then((data) => { console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) }).catch((error) => { console.error("MainAbility load content failed with error: "+ JSON.stringify(error)) }) } - + onWindowStageDestroy() { console.log("MainAbility onWindowStageDestroy") } - + onForeground() { console.log("MainAbility onForeground") } - + onBackground() { console.log("MainAbility onBackground") } } ``` -### Obtaining AbilityStage and Ability Configuration Information -Both the **AbilityStage** and **Ability** classes have the **context** attribute. An application can obtain the context of the **Ability** instance through **this.context** to obtain detailed configuration information. The following example shows how the ability stage obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute. The sample code is as follows: +### 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: ```ts import AbilityStage from "@ohos.application.AbilityStage" export default class MyAbilityStage extends AbilityStage { @@ -137,7 +126,7 @@ export default class MyAbilityStage extends AbilityStage { } ``` -The following example shows how the ability obtains the bundle code directory, HAP file name, ability name, and system language through the **context** attribute. The sample code is as follows: +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 `Ability` class. The sample code is as follows: ```ts import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { @@ -155,9 +144,83 @@ export default class MainAbility extends Ability { } } ``` +### 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. -### Starting an Ability -An application can obtain the context of an **Ability** instance through **this.context** and then use the **StartAbility** API in the **AbilityContext** class to start the ability. The ability can be started by specifying **Want**, **StartOptions**, and **accountId**, and the operation result can be returned using a callback or **Promise** instance. The sample code is as follows: +Declare the required permissions in the `module.json` file. +```json +"requestPermissions": [ + { + "name": "ohos.permission.READ_CALENDAR" + } +] +``` +Request the permissions from consumers in the form of a dialog box: +```ts +let context = this.context +let permissions: Array = ['ohos.permission.READ_CALENDAR'] +context.requestPermissionsFromUser(permissions).then((data) => { + console.log("Succeed to request permission from user with data: " + JSON.stringify(data)) +}).catch((error) => { + console.log("Failed to request permission from user with error: " + JSON.stringify(error)) +}) +``` +### 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). + +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. +```ts +import Ability from '@ohos.application.Ability' +import ConfigurationConstant from '@ohos.application.ConfigurationConstant' + +export default class MyAbilityStage extends AbilityStage { + onConfigurationUpdated(config) { + if (config.colorMode === ConfigurationConstant.ColorMode.COLOR_MODE_DARK) { + console.log('colorMode changed to dark') + } + } +} +``` + +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. +```ts +import Ability from '@ohos.application.Ability' +import ConfigurationConstant from '@ohos.application.ConfigurationConstant' + +export default class MainAbility extends Ability { + direction : number; + + onCreate(want, launchParam) { + this.direction = this.context.config.direction + } + + onConfigurationUpdated(config) { + if (this.direction !== config.direction) { + console.log(`direction changed to ${config.direction}`) + } + } +} +``` +## 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). + +**Table 3** AbilityContext APIs + +|API|Description| +|:------|:------| +|startAbility(want: Want, callback: AsyncCallback\): void|Starts an ability.| +|startAbility(want: Want, options?: StartOptions): Promise\|Starts an ability.| +|startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the account ID.| +|startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the account ID.| +|startAbilityForResult(want: Want, callback: AsyncCallback\): void|Starts an ability with the returned result.| +|startAbilityForResult(want: Want, options?: StartOptions): Promise\|Starts an ability with the returned result.| +|startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void|Starts an ability with the execution result and account ID.| +|startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\|Starts an ability with the execution result and account ID.| +### Starting an Ability on the Same Device +An application can obtain the context of an `Ability` instance through `this.context` and then use the `startAbility` API in the `AbilityContext` class to start the ability. The ability can be started by specifying `Want`, `StartOptions`, and `accountId`, and the operation result can be returned using a callback or `Promise` instance. The sample code is as follows: ```ts let context = this.context var want = { @@ -165,20 +228,17 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -var options = { - windowMode: 0, - displayId: 2 -}; -context.startAbility(want, options).then((data) => { +context.startAbility(want).then((data) => { console.log("Succeed to start ability with data: " + JSON.stringify(data)) }).catch((error) => { console.error("Failed to start ability with error: "+ JSON.stringify(error)) }) ``` -### Starting an Ability on a Remote Device (Available only to System Applications) ->Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, cross-device ability startup applies only to system applications. +### 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. 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 = { @@ -192,7 +252,7 @@ context.startAbility(want).then((data) => { console.error("Failed to start remote ability with error: "+ JSON.stringify(error)) }) ``` -Obtain the ID of a specified device from **DeviceManager**. The sample code is as follows: +Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; function getRemoteDeviceId() { @@ -209,68 +269,57 @@ 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). +### 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: -### Requesting Permissions -If an application requires certain permissions, such as storage, location information, and log access, the application must request the permissions from end users. After determining the required permissions, add the permissions in the **module.json** file and use **requestPermissionsFromUser** to request the permissions from end users in the form of a dialog box. The following uses the permissions for calendar access as an example. -Modify the **module.json** file as follows: -```json -"requestPermissions": [ - { - "name": "ohos.permission.READ_CALENDAR" - } -] -``` -Request the permissions from end users in the form of a dialog box: +When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information. ```ts -let context = this.context -let permissions: Array = ['ohos.permission.READ_CALENDAR'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) -``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: -```ts -let context = this.context -let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) +async function reStartAbility() { + try { + await this.context.startAbility({ + bundleName: "com.sample.MyApplication", + abilityName: "MainAbility", + uri: "pages/second" + }) + console.log('start ability succeed') + } catch (error) { + console.error(`start ability failed with ${error.code}`) + } +} ``` -### Notifying of Environment Configuration Changes -When the global configuration, for example, system language and color mode, changes, the **onConfigurationUpdated** API is called to notify the ability stage and ability. System applications can update the system language and color mode through the **updateConfiguration** API. 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 change. The sample code is as follows: +Obtain the `want` parameter that contains the page information from the `onNewWant` callback of the ability. ```ts import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' -export default class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log("MyAbilityStage onConfigurationUpdated") - console.log("MyAbilityStage config language" + config.language) - console.log("MyAbilityStage config colorMode" + config.colorMode) - } + +export default class MainAbility extends Ability { + onNewWant(want) { + globalThis.newWant = want + } } ``` -The following example shows the implement of the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, and display parameters (such as the direction and density) change. The sample code is as follows: +Obtain the `want` parameter that contains the page information from the custom component and process the route based on the URI. ```ts -import Ability from '@ohos.application.Ability' -import ConfigurationConstant from '@ohos.application.ConfigurationConstant' -export default class MainAbility extends Ability { { - onConfigurationUpdated(config) { - console.log("MainAbility onConfigurationUpdated") - console.log("MainAbility config language" + config.language) - console.log("MainAbility config colorMode" + config.colorMode) - console.log("MainAbility config direction" + config.direction) - console.log("MainAbility config screenDensity" + config.screenDensity) - console.log("MainAbility config displayId" + config.displayId) +import router from '@system.router' + +@Entry +@Component +struct Index { + newWant = undefined + + onPageShow() { + console.info('Index onPageShow') + let newWant = globalThis.newWant + if (newWant.hasOwnProperty("uri")) { + router.push({ uri: 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 Ability Creation and Usage (eTS) (API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) +- [`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 4d006f01fad3c6503022fc750a7071c5a6737656..e402454ddf6afd1b1aab71601e52b19d8010b425 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -8,21 +8,27 @@ The following figure shows the ability call process. ![stage-call](figures/stage-call.png) +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The startup mode of the callee must be **singleton**. +> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee. + ## Available APIs The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). **Table 1** Ability call APIs |API|Description| |:------|:------| -|Promise\ startAbilityByCall(want: Want)|Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background.| -|void on(method: string, callback: CalleeCallBack)|Callee.on: callback invoked when the callee registers a method.| -|void off(method: string)|Callee.off: callback invoked when the callee deregisters a method.| -|Promise\ call(method: string, data: rpc.Sequenceable)|Caller.call: sends agreed sequenceable data to the callee.| -|Promise\ callWithResult(method: string, data: rpc.Sequenceable)|Caller.callWithResult: sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| -|void release()|Caller.release: releases the caller interface.| -|void onRelease(callback: OnReleaseCallBack)|Caller.onRelease: registers a callback that is invoked when the caller is disconnected.| +|startAbilityByCall(want: Want): Promise\|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| +|on(method: string, callback: CaleeCallBack): void|Callback invoked when the callee registers a method.| +|off(method: string): void|Callback invoked when the callee deregisters a method.| +|call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee.| +|callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| +|release(): void|Releases the caller interface.| +|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| ## How to Develop +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. For details about the complete project code, see [Samples](#samples). ### Creating a Callee For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. 1. Configure the ability startup mode. @@ -51,7 +57,7 @@ import Ability from '@ohos.application.Ability' ``` 3. Define the agreed sequenceable data. - The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code is as follows: + The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code snippet is as follows: ```ts export default class MySequenceable { num: number = 0 @@ -77,7 +83,7 @@ export default class MySequenceable { ``` 4. Implement **Callee.on** and **Callee.off**. - The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **CalleeSortMethod** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns them. You need to implement processing based on service requirements. The sample code is as follows: + The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: ```ts const TAG: string = '[CalleeAbility]' const MSG_SEND_METHOD: string = 'CallSendMsg' @@ -121,7 +127,7 @@ import Ability from '@ohos.application.Ability' ``` 2. Obtain the caller interface. - The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code is as follows: + The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code snippet is as follows: ```ts async onButtonGetCaller() { try { @@ -142,7 +148,7 @@ async onButtonGetCaller() { console.error(TAG + 'get caller failed with ' + error) }) ``` -In the cross-device scenario, you need to specify the ID of the peer device. The sample code is as follows: + In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: ```ts let TAG = '[MainAbility] ' var caller = undefined @@ -166,7 +172,7 @@ context.startAbilityByCall({ console.error(TAG + 'get remote caller failed with ' + error) }) ``` -Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code is as follows: + Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; var dmClass; @@ -184,7 +190,7 @@ function getRemoteDeviceId() { } } ``` -In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: + In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: ```ts let context = this.context let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] @@ -196,7 +202,7 @@ context.requestPermissionsFromUser(permissions).then((data) => { ``` 3. Send agreed sequenceable data. -The sequenceable data can be sent to the callee in either of the following ways: without a return value or obtaining data returned by the callee. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code is as follows: + The sequenceable data can be sent to the callee with or without a return value. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' async onButtonCall() { @@ -209,7 +215,7 @@ async onButtonCall() { } ``` -In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code is as follows: + In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' originMsg: string = '' @@ -231,7 +237,7 @@ async onButtonCallWithResult(originMsg, backMsg) { ``` 4. Release the caller interface. -When the caller interface is no longer required, call the **release** API to release it. The sample code is as follows: + When the caller interface is no longer required, call the **release** API to release it. The sample code snippet is as follows: ```ts try { this.caller.release() @@ -242,9 +248,6 @@ try { } ``` -## Development Example +## Samples The following sample is provided to help you better understand how to develop an ability call in the stage model: - -[StageCallAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility) - -In this sample, the **AbilityStage** APIs are implemented in the **AbilityStage.ts** file in the **Application** directory, the **Ability** APIs are implemented in the **MainAbility** directory, and **pages/index** is the pages of the ability. Another ability and callee are implemented in the **CalleeAbility** directory, and its pages are the content configured in **pages/second**. The **MainAbility** functions as the caller, and the **CalleeAbility** functions as the callee. After starting the **CalleeAbility**, the **MainAbility** obtains the caller interface, processes the string entered by the user, and transfers the processed string to the **CalleeAbility**. The **CalleeAbility** refreshes the page based on the received data and returns the result to the **MainAbility**. +- [`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 9ce9471970bc805325db026ae5a522b9bd55358b..8ff179ff5f617a2d5c1f1a432528eef3cf7e58ec 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -4,24 +4,15 @@ A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the service widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: -- Widget provider - - The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. - -- Widget host - - The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. - -- Widget Manager - - The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. +- Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. +- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. @@ -30,16 +21,16 @@ The widget provider controls the widget content to display, component layout, an ## When to Use -Stage ability development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: +Stage widget development refers to the development conducted by the widget provider based on the [stage model](stage-brief.md). As a widget provider, you need to carry out the following operations: -- Develop the lifecycle callback functions in **FormExtension**. -- Create a **FormBindingData** object. +- Develop the lifecycle callbacks in **FormExtension**. +- Create a **FormBindingData** instance. - Update a widget through **FormProvider**. - Develop the widget UI page. ## Available APIs -The **FormExtension** class has the **context** attribute. For details on the APIs provided by the **FormExtension** class, see [FormExtension](../reference/apis/js-apis-formextension.md). +The **FormExtension** class has the following APIs. For details, see [FormExtension](../reference/apis/js-apis-formextension.md). **Table 1** FormExtension APIs @@ -48,19 +39,19 @@ The **FormExtension** class has the **context** attribute. For details on the AP | onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | -| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | -| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | +| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. | +| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the ability is running is updated. | +| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the widget is running is updated. | -The **context** attribute of the **FormExtension** class inherits from the **FormExtensionContext** class. For details about the APIs provided by the **FormExtensionContext** class, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). +The **FormExtension** class also has a member context, that is, the **FormExtensionContext** class. For details, see [FormExtensionContext](../reference/apis/js-apis-formextensioncontext.md). **Table 2** FormExtensionContext APIs | API | Description | | :----------------------------------------------------------- | :------------------------ | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This method uses a callback to return the result. | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This method uses a promise to return the result.| +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This API uses an asynchronous callback to return the result. | +| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This API uses a promise to return the result.| For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -75,9 +66,9 @@ For details about the **FormProvider** APIs, see [FormProvider](../reference/api ## How to Develop -### Creating a Form Extension +### Creating a FormExtension Instance -To create a widget in the stage model, you need to implement the lifecycle callback functions of **FormExtension**. The sample code is as follows: +To create a widget in the stage model, implement the lifecycle callbacks of **FormExtension**. The sample code is as follows: 1. Import the required modules. @@ -88,13 +79,13 @@ To create a widget in the stage model, you need to implement the lifecycle callb import formProvider from '@ohos.application.formProvider' ``` -2. Implement the lifecycle callback functions of **FormExtension**. +2. Implement the lifecycle callbacks of **FormExtension**. ```javascript export default class FormAbility extends FormExtension { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -107,7 +98,7 @@ To create a widget in the stage model, you need to implement the lifecycle callb console.log('FormAbility onCastToNormal'); } onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -136,24 +127,22 @@ To create a widget in the stage model, you need to implement the lifecycle callb } ``` -### Configuring config.json for the Form Ability - -Configure the **module.json** file for the **Form** ability. +### Configuring the Widget Configuration File -- The internal field structure of the **extensionAbility** module is described as follows: +- Configure Extension ability information under **extensionAbilities** in the **module.json5** file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ----------- | ------------------------------------------------------------ | ---------- | -------------------- | - | name | Name of an extension ability. | String | No | - | srcEntrance | JS code path of the extension ability. | String | No | - | description | Description of the extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| - | icon | Index of the extension ability icon file. | String | Yes (initial value: left empty)| - | label | Descriptive information about the extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| - | type | Type of the extension ability. The value can be **form** or **service**. | String | No | + | name | Name of the Extension ability. This field must be specified. | String | No | + | srcEntrance | Path of the Extension ability lifecycle code. This field must be specified.| String | No | + | description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty)| + | icon | Index of the Extension ability icon file. | String | Yes (initial value: left empty)| + | label | Descriptive information about the Extension ability presented externally. The value can be a string or a resource index to the description.| String | Yes (initial value: left empty)| + | type | Type of the Extension ability. In the current development scenario, set this field to **form**.| String | No | | permissions | Permissions required for abilities of another application to call the current ability. | String array| Yes (initial value: left empty)| - | metadata | Metadata of the extension ability. It describes the configuration information of the extension ability.| Object | Yes (initial value: left empty) | + | metadata | Metadata (configuration information) of the Extension ability.| Object | Yes (initial value: left empty) | - For a Form Extension ability, set **type** to **form** and **metadata** to the widget details. + For a Form Extension ability, you must specify **metadata**. Specifically, set **name** to **ohos.extension.form** (fixed), and set **resource** to the index of the widget configuration information. A configuration example is as follows: @@ -171,25 +160,25 @@ Configure the **module.json** file for the **Form** ability. }] ``` -- Configure the widget profile module. In the metadata of the Form Extension ability, the resource file path specified by **ohos.extension.form** must be used. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile. +- Configure the widget configuration information. **resource** in **metadata** specifies the index of the widget configuration information. For example, **$profile:form_config** means that **form_config.json** in the **resources/base/profile/** directory of the development view is used as the widget profile configuration file. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | - | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | + | name | Class name of a widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | src | Full path of the UI code corresponding to the widget. | String | No | | window | Window-related configurations. | Object | Yes | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| - | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | + | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | - | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | + | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | A configuration example is as follows: @@ -217,9 +206,9 @@ Configure the **module.json** file for the **Form** ability. ``` -### Widget Data Persistence +### Persistently Storing Widget Data -Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. +Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting the widget. ```javascript onCreate(want) { @@ -228,7 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget information for subsequent use, such as widget instance retrieval and update. + // Persistently store widget data for subsequent use, such as widget instance retrieval and update. + // The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below. storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -244,9 +234,11 @@ You should override **onDestroy** to delete widget data. ```javascript onDestroy(formId) { - // Delete widget data. - deleteFormInfo(formId); console.log('FormAbility onDestroy'); + + // You need to implement the code for deleting the persistent widget data. + // The deleteFormInfo API is not implemented here. For details about the implementation, see "Samples" below. + deleteFormInfo(formId); } ``` @@ -258,14 +250,12 @@ Note that the **Want** passed by the widget host to the widget provider contains - Temporary widget: a widget that is temporarily used by the widget host - -Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. +Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - hml: @@ -347,10 +337,7 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) -## Development Example +## Samples The following sample is provided to help you better understand how to develop a widget on the stage model: - -[FormExtAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility) - -This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. +- [`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/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index aaefaf25e04f5455ce8081cb38c75ecf62f5a06e..4b3ea45a7f6016a92f8e04b3feaa1fda77b07b76 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -54,7 +54,7 @@ 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) - APIs - - [JS and TS APIs](reference/apis/Readme-CN.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) diff --git a/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md index 63e42760af0329365bd1a0379a21259dd3502c14..997f750a0d937e6b7711b815c9b19e0ab5b741fe 100644 --- a/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md +++ b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md @@ -9,16 +9,13 @@ You can set your application to call the **ReminderRequest** class to create sch **reminderAgent** encapsulates the methods for publishing and canceling reminders. **Table 1** Major APIs in reminderAgent - - - | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | | function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void;
function publishReminder(reminderReq: ReminderRequest): Promise\; | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | | function cancelReminder(reminderId: number, callback: AsyncCallback\): void;
function cancelReminder(reminderId: number): Promise\; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) | | function getValidReminders(callback: AsyncCallback>): void;
function getValidReminders(): Promise>; | Obtains all valid reminders set by the current application. | | function cancelAllReminders(callback: AsyncCallback\): void;
function cancelAllReminders(): Promise\; | Cancels all reminders set by the current application. | -| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void;
function addNotificationSlot(slot: NotificationSlot): Promise; | Registers a NotificationSlot instance to be used by the reminder. | +| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\): void;
function addNotificationSlot(slot: NotificationSlot): Promise\; | Registers a NotificationSlot instance to be used by the reminder. | | function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void;function removeNotificationSlot(slotType: notification.SlotType): Promise\; | Removes a NotificationSlot instance of a specified type. | **ActionButtonType** enumerates types of buttons displayed in a reminder notification. diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md index d6d4e822448939fb55b6cef353ddf9bd27ea82fd..772a47b86cdf8cdc14d00cf077154344dc58d726 100644 --- a/en/application-dev/background-task-management/background-task-dev-guide.md +++ b/en/application-dev/background-task-management/background-task-dev-guide.md @@ -41,7 +41,7 @@ If a service needs to be continued when the application or service module is run backgroundTaskManager.getRemainingDelayTime(id).then( res => { console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); }); ``` @@ -74,7 +74,7 @@ console.info("The actualDelayTime is: " + time); backgroundTaskManager.getRemainingDelayTime(id).then( res => { console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); }); // Cancel the suspension delay. diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index a0107dabe7b716b4f7fe2c163c8f48970337959d..acdc2e2c8ea01d6b62a681e90577960d266d8752 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -1,161 +1,133 @@ -# IPC & RPC Development +# IPC & RPC Development -## When to Use +## When to Use IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. -## Available APIs - -**Table 1** Native IPC APIs - - - - - - - - - - - - - - - - - - - - -

Class/Interface

-

Function

-

Description

-

IRemoteBroker

-

sptr<IRemoteObject> AsObject()

-

Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of IRemoteBroker. If you call this method on the stub, the RemoteObject is returned; if you call this method on the proxy, the proxy object is returned.

-

IRemoteStub

-

virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)

-

Called to process a request from the proxy and return the result. Derived classes need to override this method.

-

IRemoteProxy

-
  

Service proxy classes are derived from the IRemoteProxy class.

-
- -## How to Develop +## Available APIs + +**Table 1** Native IPC APIs + +| Class/Interface | Function | Description | +| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| IRemoteBroker | sptr\ AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | +| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | +| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | + +## How to Develop **Using Native APIs** -1. Define the IPC interface **ITestAbility**. - - **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. - - ``` - class ITestAbility : public IRemoteBroker { - public: - // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. - virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. - }; - ``` - -2. Define and implement service provider **TestAbilityStub**. - - This class is related to the IPC framework and needs to inherit **IRemoteStub**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. - - ``` - class TestAbilityStub : public IRemoteStub { - public: - virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - int TestPingAbility(const std::u16string &dummy) override; - }; - - int TestServiceStub::OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) - { - switch (code) { - case TRANS_ID_PING_ABILITY: { - std::u16string dummy = data.ReadString16(); - int result = TestPingAbility(dummy); - reply.WriteInt32(result); - return 0; - } - default: - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - } - ``` - -3. Define the **TestAbility** class that implements functions for the stub. - - ``` - class TestAbility : public TestAbilityStub { - public: - int TestPingAbility(const std::u16string &dummy); - } - - int TestAbility::TestPingAbility(const std::u16string &dummy) { - return 0; - } - ``` - -4. Define and implement **TestAbilityProxy**. - - This class is implemented on the proxy and inherits **IRemoteProxy**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. - - ``` - class TestAbilityProxy : public IRemoteProxy { - public: - explicit TestAbilityProxy(const sptr &impl); - int TestPingService(const std::u16string &dummy) override; - private: - static inline BrokerDelegator delegator_; // Use the iface_cast macro. - } - - TestAbilityProxy::TestAbilityProxy(const sptr &impl) - : IRemoteProxy(impl) - { - } - - int TestAbilityProxy::TestPingService(const std::u16string &dummy) { - MessageOption option; - MessageParcel dataParcel, replyParcel; - dataParcel.WriteString16(dummy); - int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); - int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; - return result; - } - ``` - -5. Register and start an SA. - - Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. - - ``` - // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - samgr->AddSystemAbility(said, new TestAbility()); - - // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - ISystemAbilityManager::SAExtraProp saExtra; - saExtra.isDistributed = true; // Set a distributed SA. - int result = samgr->AddSystemAbility(said, new TestAbility(), saExtra); - ``` - -6. Obtain the SA. - - Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. - - ``` - // Obtain the proxy of the SA registered on the local device. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(said); - sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. - - // Obtain the proxies of the SAs registered with other devices. - sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - sptr remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device. - sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. - ``` +1. Define the IPC interface **ITestAbility**. + + **ITestAbility** inherits the IPC base class **IRemoteBroker** and defines descriptors, functions, and message code. The functions need to be implemented on both the proxy and stub. + ``` + class ITestAbility : public IRemoteBroker { + public: + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); + int TRANS_ID_PING_ABILITY = 1; // Define the message code. + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. + }; + ``` +2. Define and implement service provider **TestAbilityStub**. + + This class is related to the IPC framework and needs to inherit **IRemoteStub\**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. + + ``` + class TestAbilityStub : public IRemoteStub { + public: + virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int TestPingAbility(const std::u16string &dummy) override; + }; + + int TestServiceStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + switch (code) { + case TRANS_ID_PING_ABILITY: { + std::u16string dummy = data.ReadString16(); + int result = TestPingAbility(dummy); + reply.WriteInt32(result); + return 0; + } + default: + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + ``` + +3. Define the **TestAbility** class that implements functions for the stub. + + ``` + class TestAbility : public TestAbilityStub { + public: + int TestPingAbility(const std::u16string &dummy); + } + + int TestAbility::TestPingAbility(const std::u16string &dummy) { + return 0; + } + ``` + +4. Define and implement **TestAbilityProxy**. + + This class is implemented on the proxy and inherits **IRemoteProxy\**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. + + ``` + class TestAbilityProxy : public IRemoteProxy { + public: + explicit TestAbilityProxy(const sptr &impl); + int TestPingService(const std::u16string &dummy) override; + private: + static inline BrokerDelegator delegator_; // Use the iface_cast macro. + } + + TestAbilityProxy::TestAbilityProxy(const sptr &impl) + : IRemoteProxy(impl) + { + } + + int TestAbilityProxy::TestPingService(const std::u16string &dummy) { + MessageOption option; + MessageParcel dataParcel, replyParcel; + dataParcel.WriteString16(dummy); + int error = Remote()->SendRequest(TRANS_ID_PING_ABILITY, dataParcel, replyParcel, option); + int result = (error == ERR_NONE) ? replyParcel.ReadInt32() : -1; + return result; + } + ``` + +5. Register and start an SA. + + Call **AddSystemAbility** to register the **TestAbilityStub** instance of the SA with **SystemAbilityManager**. The registration parameters vary depending on whether the **SystemAbilityManager** resides on the same device as the SA. + + ``` + // Register the TestAbilityStub instance with the SystemAbilityManager on the same device as the SA. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + samgr->AddSystemAbility(said, new TestAbility()); + + // Register the TestAbilityStub instance with the SystemAbilityManager on a different device. + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + ISystemAbilityManager::SAExtraProp saExtra; + saExtra.isDistributed = true; // Set a distributed SA. + int result = samgr->AddSystemAbility(said, new TestAbility(), saExtra); + ``` + +6. Obtain the SA. + + Call the **GetSystemAbility** function of the **SystemAbilityManager** class to obtain the **IRemoteObject** for the SA, and create a **TestAbilityProxy** instance. + + ``` + // Obtain the proxy of the SA registered on the local device. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + sptr remoteObject = samgr->GetSystemAbility(said); + sptr testAbility = iface_cast(remoteObject); // Use the iface_cast macro to convert the proxy to a specific type. + + // Obtain the proxies of the SAs registered with other devices. + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + sptr remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device. + sptr proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. + ``` \ No newline at end of file diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 00ff76707d2e8d6a2d0ee7dee92fbe8ff92adc84..ab1664eb718591f8abdcd691f1b9ff37b2f97a14 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,152 +1,152 @@ # Audio Capture Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show how a JS application can use AudioCapturer to record the audio. -Applications can use the APIs provided in this document to record raw audio files. - -## **AudioCapturer Framework** -The AudioCapturer interface is one of the most important components of the audio framework. -### **Audio Capturing:** -The AudioCapturer framework provides APIs for capturing raw audio files. - -## **Usage** -Here's an example of how to use AudioCapturer to capture a raw audio file. -1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\ - This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications. - ``` - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; - ``` +## When to Use + +You can use the APIs provided by **AudioCapturer** to record raw audio files. + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. + +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md). + +**Figure 1** Audio capturer state + +![](figures/audio-capturer-state.png) + +## How to Develop + +1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. + + Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification. -2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. - If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. - There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details. + ```js + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 + } + + var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + var state = audioRenderer.state; ``` + +2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. +If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js audioCapturer.on('stateChange',(state) => { console.info('AudioCapturerLog: Changed State to : ' + state) switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } }); - ``` -3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ - The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers. - ``` - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } +3. Use **start()** to start audio recording. - ``` + The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. -4. Obtain the minimum buffer size to read using the **getBufferSize()** API. + ```js + await audioCapturer.start(); + if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.info('AudioRecLog: Capturer start failed'); + } ``` - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); - ``` +4. Use **getBufferSize()** to obtain the minimum buffer size to read. -5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data - until the application wants to stop the recording. The following example shows how to write recorded data into a file. + ```js + var bufferSize = await audioCapturer.getBufferSize(); + console.info('AudioRecLog: buffer size: ' + bufferSize); ``` - import fileio from '@ohos.fileio'; - - const path = '/data/data/.pulse_dir/capture_js.wav'; - let fd = fileio.openSync(path, 0o102, 0o777); - if (fd !== null) { - console.info('AudioRecLog: file fd created'); - } - else{ - console.info('AudioRecLog: file fd create : FAILED'); - return; - } - - fd = fileio.openSync(path, 0o2002, 0o666); - if (fd !== null) { - console.info('AudioRecLog: file fd opened in append mode'); - } - - var numBuffersToCapture = 150; - while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); - if (typeof(buffer) == undefined) { - console.info('read buffer failed'); - } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); - } - - numBuffersToCapture--; - } - ``` -6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording. - ``` - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + +5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording. + + The following example shows how to write recorded data into a file. + + ```js + import fileio from '@ohos.fileio'; + + const path = '/data/data/.pulse_dir/capture_js.wav'; + let fd = fileio.openSync(path, 0o102, 0o777); + if (fd !== null) { + console.info('AudioRecLog: file fd created'); + } + else{ + console.info('AudioRecLog: file fd create : FAILED'); + return; + } + + fd = fileio.openSync(path, 0o2002, 0o666); + if (fd !== null) { + console.info('AudioRecLog: file fd opened in append mode'); + } + + var numBuffersToCapture = 150; + while (numBuffersToCapture) { + var buffer = await audioCapturer.read(bufferSize, true); + if (typeof(buffer) == undefined) { + console.info('read buffer failed'); + } else { + var number = fileio.writeSync(fd, buffer); + console.info('AudioRecLog: data written: ' + number); + } + + numBuffersToCapture--; + } ``` -7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. +6. Once the recording is complete, call **stop()** to stop the recording. + ``` - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } + await audioCapturer.stop(); + if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.info('AudioRecLog: Capturer stop failed'); + } ``` -## **Importance of State Check** -Application developers should keep in mind that an AudioCapturer is state-based. -That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state. +7. After the task is complete, call **release()** to release related resources. -## **Other APIs** -See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. + ```js + await audioCapturer.release(); + if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + ``` diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index f9dfb75c2a08d6c8d641bbe0c8e7960efc6bc6ee..8e2be849396373aaa68ee7c4eb5e36a4cad28c1c 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,152 +1,124 @@ # Audio Rendering Development ---- -## ***Note***: - 1. This document applies to JavaScript. ---- -## **Summary** -This guide will show you how to use AudioRenderer to create an audio player app. -You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. +## When to Use -## **AudioRenderer Framework** -The AudioRenderer interface is one of the most important components of the audio framework. -### **Audio Rendering:** -The AudioRenderer framework provides APIs for playing audio files and controlling the playback. -### **Audio Interruption:** -When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\ -For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ -With the sample code below, we'll look at how AudioInterrupt works in detail.\ -
-Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. +**AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. +### Audio Interruption -## **Usage** -Here's an example of how to use AudioRenderer to play a raw audio file. -1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ - This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. - ``` +When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop). + +### State Check + +During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. + +**Figure 1** Audio renderer state + +![](figures/audio-renderer-state.png) + +### Asynchronous Operations + +To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + + + +## How to Develop + +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. + Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + + ```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, 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 } - + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` -2. Subscribe to audio interruption events using the **on** API.\ - Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\ - In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on. - - In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\ -
- The following information will be provided by the Interrupt Event Notification: - - 1) **eventType:** Whether the interruption has begun or ended. - - | Value | Description | - | :------------------- | :-------------------------------------------- | - | INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. | - | INTERRUPT_TYPE_END | Indicates that the interruption has finished. | - - 2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action. - - | Value | Description | - | :-------------- | :------------------------------------------------------------------ | - | INTERRUPT_FORCE | The audio state has been changed by the framework. | - | INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. | - - 3) **hintType:** The kind of action taken or to be taken. - - | Value | Description | - | :-------------------- | :--------------------------- | - | INTERRUPT_HINT_PAUSE | Pausing the playback. | - | INTERRUPT_HINT_RESUME | Resuming the playback. | - | INTERRUPT_HINT_STOP | Stopping the playback. | - | INTERRUPT_HINT_DUCK | Ducking the stream volume. | - | INTERRUPT_HINT_UNDUCK | Unducking the stream volume. | - - 4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ - For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback. - - | Action | Description | - | :-------------------- | :-------------------------------------------------------------------------------- | - | INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. | - | INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - | INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | - +2. Use **on('interrupt')** to subscribe to audio interruption events. + + Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device. + + In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. + + In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). + + ```js + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); ``` - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); - ``` +3. Use **start()** to start audio rendering. + + The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. -4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ - The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers. - ``` + ```js async function startRenderer() { var state = audioRenderer.state; - // state should be prepared, paused or stopped. + // The state should be prepared, paused, or stopped. if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || state != audio.AudioState.STATE_STOPPED) { console.info('Renderer is not in a correct state to start'); return; } - + await audioRenderer.start(); - + state = audioRenderer.state; if (state == audio.AudioState.STATE_RUNNING) { console.info('Renderer started'); @@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. console.error('Renderer start failed'); } } - - ``` -5. Make **write** calls to start rendering the buffers. - Read the audio data to be played into a buffer. Call the write function repeatedly to write data. ``` + +4. Call **write()** to write data to the buffer. + + Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. + + ```js async function writeBuffer(buf) { var state = audioRenderer.state; if (state != audio.AudioState.STATE_RUNNING) { @@ -167,13 +141,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. return; } let writtenbytes = await audioRenderer.write(buf); - + console.info('Actual written bytes: ' + writtenbytes); if (writtenbytes < 0) { console.error('Write buffer failed. check the state of renderer'); } } - + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. const bufferSize = await audioRenderer.getBufferSize(); const path = '/data/file_example_WAV_2MG.wav'; @@ -183,7 +157,7 @@ Here's an example of how to use AudioRenderer to play a raw audio file. let discardHeader = new ArrayBuffer(44); ss.readSync(discardHeader); rlen += 44; - + var id = setInterval(() => { if (isPlay || isRelease) { if (rlen >= totalSize || isRelease) { @@ -201,74 +175,65 @@ Here's an example of how to use AudioRenderer to play a raw audio file. } , 30); // interval to be set based on audio file format ``` -6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. -``` - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } -} -``` - -7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ - AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**. -``` - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } - - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - - } -``` - -## **Importance of State Check:** -You should also keep in mind that an AudioRenderer is state-based. -That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\ -The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\ +5. (Optional) Call **pause()** or **stop()** to pause or stop rendering. + + ```js + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` -## **Asynchronous Operations:** -Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ -For each API, the framework provides both callback and promises functions.\ -In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) -provides reference for both callback and promise. +6. After the task is complete, call **release()** to release related resources. + + **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete. + + ```js + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } + ``` -## **Other APIs:** -See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. + diff --git a/en/application-dev/media/figures/audio-capturer-state.png b/en/application-dev/media/figures/audio-capturer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..52b5556260dbf78c5e816b37013248a07e8dbbc6 Binary files /dev/null and b/en/application-dev/media/figures/audio-capturer-state.png differ diff --git a/en/application-dev/media/figures/audio-renderer-state.png b/en/application-dev/media/figures/audio-renderer-state.png new file mode 100644 index 0000000000000000000000000000000000000000..9ae30c2a9306dc85662405c36da9e11d07ed9a2a Binary files /dev/null and b/en/application-dev/media/figures/audio-renderer-state.png differ diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index ebcb811f7886a097c741198f0696b61327cefefb..9ab337ed1c29e18772ff4e348c47e3202f74815f 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -1,6 +1,6 @@ # Native APIs - [Using Native APIs in Application Projects](napi-guidelines.md) - +- [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) diff --git a/en/application-dev/napi/drawing-guidelines.md b/en/application-dev/napi/drawing-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e813f84d92d4155e78c9ca651af6a3e3cd010232 --- /dev/null +++ b/en/application-dev/napi/drawing-guidelines.md @@ -0,0 +1,208 @@ +# Drawing Development + +## When to Use + +The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development: +* Drawing 2D graphics +* Drawing and painting text + +## Available APIs + +| API| Description| +| -------- | -------- | +| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.| +| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.| +| OH_Drawing_CanvasCreate (void) | Creates a canvas object.| +| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).| +| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.| +| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.| +| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.| +| OH_Drawing_PathCreate (void) | Creates a path object.| +| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.| +| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. | +| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.| +| OH_Drawing_PenCreate (void) | Creates a pen object.| +| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.| +| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.| +| OH_Drawing_BrushCreate (void) | Creates a brush object.| +| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.| +| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.| +| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.| +| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.| +| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.| + + + +## Development Procedure for 2D Graphics Drawing + +The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics. + +1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format. + + ```c++ + // Create a bitmap object. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + // Define the pixel format of the bitmap. + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE}; + // Set the pixel format for the bitmap. + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + ``` + +2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object. + + ```c++ + // Create a canvas object. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + // Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory. + OH_Drawing_CanvasBind(cCanvas, cBitmap); + // Use white to clear the canvas. + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`. + + ```c++ + int len = 300; + + float aX = 500; + float aY = 500; + + float dX = aX - len * std::sin(18.0f); + float dY = aY + len * std::cos(18.0f); + + float cX = aX + len * std::sin(18.0f); + float cY = dY; + + float bX = aX + (len / 2.0); + float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0)); + + float eX = aX - (len / 2.0); + float eY = bY; + + // Create a path object and use the APIs to draw a pentagram. + OH_Drawing_Path* cPath = OH_Drawing_PathCreate(); + // Specify the start point of the path. + OH_Drawing_PathMoveTo(cPath, aX, aY); + // Draw a line segment from the last point of a path to the target point. + OH_Drawing_PathLineTo(cPath, bX, bY); + OH_Drawing_PathLineTo(cPath, cX, cY); + OH_Drawing_PathLineTo(cPath, dX, dY); + OH_Drawing_PathLineTo(cPath, eX, eY); + // Close the path. Now the path is drawn. + OH_Drawing_PathClose(cPath); + ``` + +4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas. + + ```c++ + // Create a pen object and set the anti-aliasing, color, and thickness. + OH_Drawing_Pen* cPen = OH_Drawing_PenCreate(); + OH_Drawing_PenSetAntiAlias(cPen, true); + OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00)); + OH_Drawing_PenSetWidth(cPen, 10.0); + OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN); + // Attach the pen to the canvas. + OH_Drawing_CanvasAttachPen(cCanvas, cPen); + + // Create a brush object and set the color. + OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate(); + OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00)); + + // Attach the brush to the canvas. + OH_Drawing_CanvasAttachBrush(cCanvas, cBrush); + ``` + +5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed. + + ```c++ + // Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush. + OH_Drawing_CanvasDrawPath(cCanvas, cPath); + // Destroy the created objects when they are no longer needed. + OH_Drawing_BrushDestory(cBrush); + OH_Drawing_PenDestory(cPen); + OH_Drawing_PathDestory(cPath); + ``` + +6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas. + + ```c++ + // Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas. + void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap); + auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize); + if (ret != EOK) { + LOGI("memcpy_s failed"); + } + // Destroy the canvas object. + OH_Drawing_CanvasDestory(cCanvas); + // Destroy the bitmap object. + OH_Drawing_BitmapDestory(cBitmap); + ``` + +## Development Procedure for Text Drawing and Display + +The following steps describe how to use the text drawing and display feature of the Native Drawing module. +1. **Create a canvas and a bitmap.** + + ```c++ + // Create a bitmap. + OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate(); + OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; + OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat); + // Create a canvas. + OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate(); + OH_Drawing_CanvasBind(cCanvas, cBitmap); + OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF)); + ``` + +2. **Set the typography style.** + + ```c++ + // Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode. + OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle(); + OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR); + OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT); + ``` + +3. **Set the text style.** + + ```c++ + // Set the text color, for example, black. + OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle(); + OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00)); + // Set text attributes such as the font size and weight. + double fontSize = 30; + OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize); + OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400); + OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC); + OH_Drawing_SetTextStyleFontHeight(txtStyle, 1); + // Set the font families. + const char* fontFamilies[] = {"Roboto"}; + OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies); + OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL); + OH_Drawing_SetTextStyleLocale(txtStyle, "en"); + ``` + +4. **Generate the final text display effect.** + + ```c++ + OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle, + OH_Drawing_CreateFontCollection()); + OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle); + // Set the text content. + const char* text = "OpenHarmony\n"; + OH_Drawing_TypographyHandlerAddText(handler, text); + OH_Drawing_TypographyHandlerPopTextStyle(handler); + OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler); + // Set the maximum width. + double maxWidth = 800.0; + OH_Drawing_TypographyLayout(typography, maxWidth); + // Set the start position for text display. + 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/rawfile-guidelines.md b/en/application-dev/napi/rawfile-guidelines.md index 29f66194bd40cd4f7a228213734db2ad65c81180..c585b162a2dc483ca72a5369170b2ee0f43a01a1 100644 --- a/en/application-dev/napi/rawfile-guidelines.md +++ b/en/application-dev/napi/rawfile-guidelines.md @@ -4,7 +4,7 @@ ## When to Use -This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. The table below describes the APIs. +This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files. ## Available APIs @@ -16,14 +16,14 @@ This document describes how to use the native Rawfile APIs to manage raw file di | const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. | | RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. | | long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. | -| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a data read/write position in a raw file based on the specified offset. | +| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. | | long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. | | int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. | | void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. | | void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. | -| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file description (FD) of a raw file. | +| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. | | bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. | -| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases native resource manager resources. | +| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. | ## How to Develop @@ -38,7 +38,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di 2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance. ```js - // Call the JS API to pass the JS resource manager. + // Import the JS resource manager from the JS head file and pass it to the C++ file. import resManager from '@ohos.resourceManager' import rawfileTest from 'librawFileTest.so' resManager.getResourceManager().then(resmgr => { @@ -49,7 +49,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ``` ```c++ - // The C++ API obtains and parses the parameters passed by the JS API. + // Obtain and parse the parameters in the C++ file. NativeResourceManager* nativeResourceManager = nullptr; std::string path; if (i == 0 && valueType == napi_string) { @@ -57,7 +57,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...... path = buf.data(); } else if (i == 1 && valueType == napi_object) { - // Parse the second parameter, which is the resource manager. + // Parse the second parameter, which is the JS resource manager. nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); } ``` @@ -80,7 +80,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file based on the specified index. +5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index. ```c++ for (int index = 0; index < count; index++) { @@ -90,7 +90,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance based on the specified file name. +6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name. ```c++ RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); @@ -106,7 +106,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -8. Call **OH_ResourceManager_SeekRawFile** to seek a data read/write position in the raw file based on the specified offset. +8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset. ```c++ int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); @@ -124,7 +124,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -10. Call **OH_ResourceManager_ReadRawFile** to read a raw file. +10. Call **OH_ResourceManager_ReadRawFile** to read the raw file. ```c++ std::unique_ptr mediaData = std::make_unique(rawFileSize); @@ -149,7 +149,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di -13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain **RawFileDescriptor** of the raw file. +13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file. ```c++ RawFileDescriptor descriptor; diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 2b048cbfc552920661c973fd08744bb18726e654..f46e565f2a9d203a056e6f9ceed055b81e8dcf08 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). -```javascript +```js private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. // Subscriber information @@ -42,7 +42,7 @@ var subscribeInfo = { 3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. -```javascript +```js // Callback for subscriber creation. commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { if (err.code) { @@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { 4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). -```javascript +```js // Callback for common event subscription. if (this.subscriber != null) { commonEvent.subscribe(this.subscriber, (err, data) => { @@ -74,7 +74,7 @@ if (this.subscriber != null) { } ``` -## Public Event Publishing Development +## Common Event Publishing Development ### When to Use You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. @@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car #### Development for Publishing a Common Event 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Pass in the common event name and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", (err) => { if (err.code) { @@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => { #### Development for Publishing a Common Event with Given Attributes 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent' ``` 2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). -```javascript +```js // Attributes of a common event. var options = { code: 1, // Result code of the common event @@ -125,7 +125,7 @@ var options = { 3. Pass in the common event name, attributes of the common event, and callback, and publish the event. -```javascript +```js // Publish a common event. commonEvent.publish("event", options, (err) => { if (err.code) { @@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ### How to Develop 1. Import the **commonEvent** module. -```javascript +```js import commonEvent from '@ohos.commonEvent'; ``` 2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. -```javascript +```js if (this.subscriber != null) { commonEvent.unsubscribe(this.subscriber, (err) => { if (err.code) { diff --git a/en/application-dev/notification/notification.md b/en/application-dev/notification/notification.md index a40723a42ce795e0d9a709fe39595b8c486f9855..107346659df11ffa808dc8701c9c971721a13282 100644 --- a/en/application-dev/notification/notification.md +++ b/en/application-dev/notification/notification.md @@ -45,9 +45,9 @@ If the notification function of an application is disabled, it cannot send notif | API | Description | | ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Unsubscribes from a notification. | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | +| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | The subscription APIs support subscription to all notifications or notifications from specific applications. @@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications | API | Description | | ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback): void; | Cancels all notifications published by the application.| +| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | +| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | +| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | +| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. diff --git a/en/application-dev/quick-start/figures/image-20220326064841782.png b/en/application-dev/quick-start/figures/image-20220326064841782.png index 57ee1a1ca5a7e62893195a296795ffb8eec00bdc..a7811ffe339baceffbfff66f2173b2e5e29a6fc1 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064841782.png and b/en/application-dev/quick-start/figures/image-20220326064841782.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064913834.png b/en/application-dev/quick-start/figures/image-20220326064913834.png index c55df52abc42e8f9a4d0a9d5fc098aa3a3456a0e..9bb845a90c3b80db95c736cc84d2434537cf8522 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064913834.png and b/en/application-dev/quick-start/figures/image-20220326064913834.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064955505.png b/en/application-dev/quick-start/figures/image-20220326064955505.png index db4f6fa370cd5c02b3d2cd98b187e324848e8d99..89a43655a064971b721a5aee4222d7c2d37c9523 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326064955505.png and b/en/application-dev/quick-start/figures/image-20220326064955505.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065043006.png b/en/application-dev/quick-start/figures/image-20220326065043006.png index 997acad905475baa43f0debf936508efdcfa2c5f..c8b11931993c83e507dbf7150a5be740430ae42f 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065043006.png and b/en/application-dev/quick-start/figures/image-20220326065043006.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065124911.png b/en/application-dev/quick-start/figures/image-20220326065124911.png index 872f36c3bf328dcb4ff58ac6f9106d5c4726dc56..858a8af31bc83367fc4c2f696d0f69e58b36b216 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065124911.png and b/en/application-dev/quick-start/figures/image-20220326065124911.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065201867.png b/en/application-dev/quick-start/figures/image-20220326065201867.png index e64cc86fef41a31e4a6b93a96faf2ee7eda03e86..e447e34c0a80c472cb2dfd684e1822866b4134d8 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326065201867.png and b/en/application-dev/quick-start/figures/image-20220326065201867.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326072448840.png b/en/application-dev/quick-start/figures/image-20220326072448840.png index dac0f9dfe41d8f7667e21f2224563910e3aa9429..861ef6a871ce38d28a1144722ff4d0d327a8bc84 100644 Binary files a/en/application-dev/quick-start/figures/image-20220326072448840.png and b/en/application-dev/quick-start/figures/image-20220326072448840.png differ diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index ef19d2b394b87375811dd483ab162d81a7068b4a..7fe24ab3c28b8b1d94aa1cd7c258a32be9f126e9 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -2,24 +2,26 @@ # Application Package Structure Configuration File -When developing an application in the FA model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json** file. +When developing an application in the Feature Ability (FA) model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json** and **app.json** files. -## Internal Structure of the module.json File +## Configuration File Internal Structure -The **module.json** file consists of two tags: **app** and **module**. See Table 1 for details. +The configuration files consist of two parts: **app** and **module**. See Table 1 for details. -Table 1 Internal structure of the module.json file +Table 1 Configuration file internal structure | Tag| Description | Data Type| Initial Value Allowed| | -------- | ------------------------------------------------------------ | -------- | ---------- | | app | Global configuration of an application. Different HAP files of an application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | | module | Configuration of a HAP file. The **module** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | -Example of the **module.json** file: +### Internal Structure of the app Tag + +Code snippet in the **app.json** file: ```json { - "app": { + "app": { "bundleName": "com.application.music", "vendor": "application", "versionCode": 1, @@ -37,7 +39,37 @@ Example of the **module.json** file: "car": { "apiCompatibleVersion": 8 } - }, + } +} +``` + +This tag is an application-level attribute that applies to all the HAP files and components in the application. For the internal structure of the tag, see Table 2. + +Table 2 Internal structure of the app tag + +| Attribute | Description | Data Type| Initial Value Allowed | +| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | +| bundleName | Bundle name that uniquely identifies the application. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
For an application compiled with the system source code, its bundle name must be in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony. | String | No | +| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | +| icon | Icon of the application. The value is the index to the resource file. | String | No | +| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | +| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | +| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | +| minCompatibleVersionCode | Minimum API version compatible with the application. | Number | Yes (initial value: value of **versionCode**)| +| minAPIVersion | Minimum API version required for running the application. | Number | No | +| targetAPIVersion | Target API version required for running the application. | Integer | No | +| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | +| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | +| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: unspecified) | + +### Internal Structure of the module Tag + +Example of the **module.json** file: + +```json +{ "module": { "name": "myHapName", "type": "entry|feature|har", @@ -159,31 +191,6 @@ Example of the **module.json** file: } ``` -### Internal Structure of the app Tag - -This tag is an application-level attribute that affects all the HAP files and components in the application. For the internal structure of the tag, see Table 2. - -Table 2 Internal structure of the app tag - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | Bundle name that uniquely identifies the application. This attribute cannot be left empty. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*. The first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
The application compiled with the system source code must be named in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony.| String | No | -| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | -| icon | Icon of the application. The value is the index to the resource file. | String | No | -| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | -| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | -| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | -| minCompatibleVersionCode | Minimum API version required for running the application. | Number | Yes (initial value: value of **versionCode**)| -| minAPIVersion | Target API version required for running the application. | Number | No | -| targetAPIVersion | Target API version required for running the application. | Integer | No | -| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | -| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | -| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: unspecified) | - -### Internal Structure of the module Tag - This tag stores the HAP configuration, which only applies to the current HAP file. Table 3 Internal structure of the module tag @@ -199,7 +206,7 @@ Table 3 Internal structure of the module tag | deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Different from **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | | deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | | installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | +| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
The value **ark** means that the target VM type is Ark, and **default** means otherwise. This attribute is automatically inserted when DevEco Studio builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | | uiSyntax | Syntax type of the JS component.
**hml**: indicates that the JS component is developed using HML, CSS, or JS.
**ets**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **hml**) | | pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario| | metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details about **metadata**, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | @@ -209,13 +216,13 @@ Table 3 Internal structure of the module tag Table 4 System-defined deviceTypes values -| Device Type | Value | Description | -| ------------ | ------------ | -------------------------------------------------------- | -| tablet | tablet | Tablet, speaker with a screen | -| smart TV | tv | | -| smart watch | wearable | Smart watch, kids' watch, especially a watch that provides call features| -| head unit | car | | -| router | router | Router | +| Device Type | Value | Description | +| ----------- | -------- | -------------------------------------------------------- | +| Tablet | tablet | Tablet, speaker with a screen | +| Smart TV | tv | Smart TV | +| Smart watch | wearable | Smart watch, kids' watch, especially a watch that provides call features| +| Head unit | car | Head unit | +| Router | router | Router | Example of the **deviceTypes** attribute structure: @@ -231,7 +238,7 @@ Example of the **deviceTypes** attribute structure: } ``` -Example of the **pages** attribute structure:: +Example of the **pages** attribute structure: ```json { @@ -306,15 +313,13 @@ Table 6 Internal structure of the abilities attribute | srcEntrance | JS code path corresponding to the ability. The value is a string with a maximum of 127 bytes.| String | No | | launchType | Ability startup mode. The value can be **standard**, **singleton**, or **specified**. The default value is **singleton**. The value **standard** indicates common multi-instance, the value **singleton** indicates a singleton, and the value **specified** indicates one or more specified instances, depending on the internal service of the ability.| String | Yes (initial value: **singleton**) | | description | Ability description. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the ability. The value is the index to the resource file. This attribute can be left empty, and the default value is an empty array.
If **ability** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| +| icon | Icon of the ability. The value is the index to the resource file. | String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| | permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute. | String array| Yes (initial value: left empty) | | metadata | Metadata about the ability. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | -| visible | Indicates whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | +| visible | Whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite. | Boolean | Yes (initial value: **false**) | | continuable | Whether the ability can be migrated. The value **true** means that the ability can be migrated, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | | skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | | backgroundModes | Continuous task modes of the ability.
Continuous tasks are classified into the following types:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables)
**multiDeviceConnection**: multi-device interconnection service
**wifiInteraction**: Wi-Fi scanning, connection, and transmission services (multi-screen cloning)
**voip**: voice/video call and VoIP services
**taskKeeping**: computing service
| String | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | No | -| startWindowBackground | Index to the background color resource file of the ability startup page. Example value: **$color:red**. | String | No | Example of the **abilities** attribute structure: @@ -361,7 +366,7 @@ Table 7 Internal structure of the skills attribute | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | A set of want action values that can be received. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| | entities | Categories of abilities that can receive the want. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details about the internal structure of **uris**, see Table 8.| Object array | Yes (initial value: left empty)| +| uris | Data specification to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details about the internal structure of **uris**, see Table 8.| Object array | Yes (initial value: left empty)| Table 8 Internal structure of the uris attribute @@ -441,10 +446,10 @@ Table 9 Internal structure of the extensionAbility attribute | description | Description of the extensionAbility. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | | icon | Icon of the extensionAbility. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | | label | Name of the extensionAbility displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | -| type | Type of the extension capability. The value can be form, workScheduler, inputMethod, service, accessibility, dataShare, fileShare, staticSubscriber, wallpaper, or backup. | String | No | +| type | Type of the extension capability. The value can be **form**, **workScheduler**, **inputMethod**, service, **accessibility**, **dataShare**, **fileShare**, **staticSubscriber**, **wallpaper**, **backup**, or **window**.| String | No | | permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty) | | uri | Data URI provided by the ability. The value is an array containing a maximum of 255 characters and is in the format of a reverse domain name. This attribute is mandatory when **type** is set to **extensionAbility** of the dataShare type.| String | Yes (initial value: left empty) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | +| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | | metadata | Metadata of extensionAbility. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | | visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| | Yes (initial value: **false**)| @@ -488,16 +493,18 @@ This attribute identifies a set of permissions that the application needs to app Table 10 requestPermissions attributes -| Attribute | Description | **Type** | **Value Range** | **Default Value** | **Restrictions** | +| Attribute | Description | **Type** | **Value Range** | **Default Value** | **Restrictions** | | --------- | ------------------------------------------------------------ | ------------------------------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | -| name | Permission name. This attribute is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | -| reason | Reason for requesting the permission. This attribute is mandatory when the requested permission is **user_grant**. | String | The maximum length is 256 bytes. | Empty | If the requested permission is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required. | -| usedScene | Application scenario and timing for using the permission, which is mandatory when the requested permission is **user_grant**. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured. | **ability**: string array; **when**: string | **ability**: ability name; **when**: **inuse** or **always** | **ability**: left empty; **when**: **inuse** | If the requested permission is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | +| name | Permission name. This attribute is mandatory. | String | Custom | N/A | Parsing will fail if this attribute is not set. | +| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. | String | A maximum of 256 bytes | Empty | If the permission to request is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| +| usedScene | Application scenario and timing for using the permission. This attribute is mandatory when the permission to request is **user_grant**. It consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured.| **ability**: string array; **when**: string| **ability**: ability name; **when**: **inuse** or **always**| **ability**: null; **when**: **inuse**| If the permission to request is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | Example of the **requestPermissions** attribute structure: ```json { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", "usedScene": { "abilities": [ "AudioAbility", @@ -513,8 +520,11 @@ Example of the **requestPermissions** attribute structure: The **forms** attribute indicates the service widget configuration. The service widget is an application brief view that can be displayed on the home screen and periodically updated. You can include the **forms** attribute in any of the following modes: 1. Set **type** to **form** in **extensions**. + 2. Specify the **form** information in **metadata**, where: - - **name** indicates the name of the service widget, for example, **ohos.extability.form**. + + - **name** indicates the name of the service widget, for example, **ohos.extability.form**. + - **resource** indicates where the resources of the service widget are stored. Table 11 Internal structure of the forms attribute @@ -612,7 +622,7 @@ Table 13 Internal structure of the shortcuts attribute | Attribute | Description | Data Type| Initial Value Allowed | | ---------- | ------------------------------------------------------------ | -------- | -------------------------- | -| shortcutId | Shortcut ID. The value is a string with a maximum of 63 bytes. | String | No | +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | | label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | | icon | Icon of the shortcut. The value is the index to the resource file. | String | Yes (initial value: left empty)| | wants | Wants to which the shortcut points. The attribute consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut; string type.
**abilityName**: target component name of the shortcut; string type.| Object | Yes (initial value: left empty) | @@ -743,14 +753,14 @@ Table 16 Internal structure of the apiVersion attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released. | Array | Yes (initial value: left empty)| +| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| Table 17 Internal structure of the screenShape attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| +| value | The value can be **circle** or **rect**. Example: Different HAP files can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| Table 18 Internal structure of the screenWindow attribute diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md index bd81ff6771735d0cb78be5321269460a7ebd0bd2..e74c958c4df493bd5084ad477b95f78c7893cd48 100644 --- a/en/application-dev/quick-start/syscap.md +++ b/en/application-dev/quick-start/syscap.md @@ -4,26 +4,26 @@ ### System Capabilities and APIs -SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each system capability corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in the IDE for association. +SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association. ![image-20220326064841782](figures/image-20220326064841782.png) -### Supported Capability Set, Associated Capability Set, and Required Capability Set +### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set -The supported capability set, associated capability set, and required capability set are collections of system capabilities. -The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. -The associated capability set covers the system capabilities of associated APIs that the IDE offers during application development. +The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. +The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. +The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development. ![image-20220326064913834](figures/image-20220326064913834.png) -### Devices and Supported Capability Sets +### Devices and Supported SysCap Sets -Each device provides a capability set that matches its hardware capability. -The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors. +Each device provides a SysCap set that matches its hardware capability. +The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors. ![image-20220326064955505](figures/image-20220326064955505.png) @@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general ### Mapping Between Devices and SDK Capabilities -The SDK provides a full set of APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input). +The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input). ![image-20220326065043006](figures/image-20220326065043006.png) @@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID** -### Configuring the Associated Capability Set and Required Capability Set +### Configuring the Associated SysCap Set and Required SysCap Set -The IDE automatically configures the associated capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary. -You can add APIs to the associated capability set in the IDE by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. -Exercise caution when modifying the required capability set. Incorrect modifications may result in the application being unable to be distributed to the target device. +DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary. +You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. +Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. ``` /* syscap.json */ @@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat ... ] }, - development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated capability set. */ + development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ addedSysCaps: [ "SystemCapability.Location.Location.Lite", ... ] }, production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ - addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set. - removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device. + addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. + removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. } } ``` @@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat ### Single-Device Application Development -By default, the associated capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set. +By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set. ![image-20220326065124911](figures/image-20220326065124911.png) @@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of ### Cross-Device Application Development -By default, the associated capability set of an application is the union of multiple devices' supported capability sets, while the required capability set is the intersection of the devices' supported capability sets. +By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets. ![image-20220326065201867](figures/image-20220326065201867.png) @@ -133,9 +133,9 @@ if (geolocation) { -### Checking the Differences Between Devices with the Same Capability +### Checking the Differences Between Devices with a Specific SysCap -The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. +The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. ``` import userAuth from '@ohos.userIAM.userAuth'; @@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat ![image-20220326072448840](figures/image-20220326072448840.png) -1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps. +1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps. 2. In a normalized released SDK, APIs are mapped to SysCap sets. @@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat 4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled. -5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed to mitigate the SysCap differences of devices. +5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices. 6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available. -7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application can be installed. +7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device. 8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 45b8f99113133d89ab396d3662c62b8372cb211b..7fc6a40023ec8480267c735eba2dc84f9181e71d 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -112,6 +112,7 @@ - [@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 @@ -141,6 +142,9 @@ - [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.connectedTag](js-apis-connectedTag.md) + - [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) + - [@ohos.nfc.controller](js-apis-nfcController.md) + - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) @@ -214,7 +218,6 @@ - APIs No Longer Maintained - [@ohos.bytrace](js-apis-bytrace.md) - - [@ohos.data.storage](js-apis-data-storage.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) - [@system.bluetooth](js-apis-system-bluetooth.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index e631e0e777d8e315c667f58dd2632ec89ef4ce92..4e37d4be279a2acc092617c9bc69723d2c924d9f 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -143,7 +143,7 @@ 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. @@ -166,7 +166,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 +185,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,7 +220,7 @@ 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. @@ -238,7 +238,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** @@ -276,7 +276,7 @@ SystemCapability.BundleManager.BundleFramework | ----------- | ------------- | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | [BundleOptions](#bundleoptions)| No | Includes **userId**. | +| options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | **Return value** @@ -359,7 +359,7 @@ SystemCapability.BundleManager.BundleFramework | ----------- | -------------------------- | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | +| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -495,7 +495,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { ## bundle.getBundleArchiveInfo -getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise +getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise\ Obtains information about the bundles contained in a HAP file. This API uses a promise to return the result. @@ -508,7 +508,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| **Return value** | Type | Description | @@ -530,7 +530,7 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) ## bundle.getBundleArchiveInfo -getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback) : void +getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback\) : void Obtains information about the bundles contained in a HAP file. This API uses an asynchronous callback to return the result. @@ -543,8 +543,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| -| callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object 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 information about the bundles.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 7a3b34caaa88c446d4e98ba7383176f6a7a374b9..ea18e37651532fb28e6fba36825dcedf2a1a2a43 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -1,4 +1,4 @@ -# Context Module +# Context ## Modules to Import @@ -925,9 +925,9 @@ Describes the HAP module information. | iconId | number | Yes | No | Module icon ID. | | backgroundImg | string | Yes | No | Module background image. | | supportedModes | number | Yes | No | Modes supported by the module. | -| reqCapabilities | Array | Yes | No | Capabilities required for module running.| -| deviceTypes | Array | Yes | No | An array of supported device types.| -| abilityInfo | Array\ | Yes | No | Ability information. | +| reqCapabilities | Array\ | Yes | No | Capabilities required for module running.| +| deviceTypes | Array\ | Yes | No | An array of supported device types.| +| abilityInfo | Array\\ | Yes | No | Ability information. | | moduleName | string | Yes | No | Module name. | | mainAbilityName | string | Yes | No | Name of the entrance ability. | | installationFree | boolean | Yes | No | When installation-free is supported. | 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 418cd920f5e9d35ad751212b610693e06668d181..9898e94c71af330e9d5ab02ec955c357fe7b8af7 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -1,19 +1,18 @@ -# AbilityContext - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +# Ability Context +> **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. Implements the ability context. This module is inherited from **Context**. +# Modules to Import -## Usage - +```js +import Ability from '@ohos.application.Ability' +``` +## Usage Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. - - - ```js import Ability from '@ohos.application.Ability' class MainAbility extends Ability { @@ -23,243 +22,481 @@ class MainAbility extends Ability { } ``` - ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| +| Name | Type | Readable | Writable | Description | +| --------------------- | --------------- | ------ | ------- | ----------------------------------- | +| config | Configuration | Yes | No | Configuration. | +| abilityInfo | AbilityInfo | Yes | No | Ability information. | +| currentHapModuleInfo | HapModuleInfo | Yes | No | Information about the current HAP. | -## AbilityContext.startAbility +## startAbility startAbility(want: Want, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - this.context.startAbility(want, (error) => { - console.log("error.code = " + error.code) - }) - ``` - +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +this.context.startAbility(want, (error) => { + console.log("error.code = " + error.code) +}) +``` -## AbilityContext.startAbility +## startAbility startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability with **options** specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) - ``` +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +var options = { + windowMode: 0, +}; +this.context.startAbility(want, options, (error) => { + console.log("error.code = " + error.code) +}) +``` -## AbilityContext.startAbility +## startAbility -startAbility(want: Want, options?: StartOptions): Promise<void>; +startAbility(want: Want, options: StartOptions): Promise<void> -Starts an ability. This API uses a promise to return the result. +Starts an ability with **options** specified. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| +| 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.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +var options = { + windowMode: 0, +}; +this.context.startAbility(want, options) +.then((data) => { + console.log('Operation successful.') +}).catch((error) => { + console.log('Operation failed.'); +}) +``` + +## startAbilityByCall + +startAbilityByCall(want: Want): Promise<Caller> + +Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options) - .then((data) => { - console.log('Operation successful.') - }).catch((error) => { - console.log('Operation failed.'); - }) - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| +**Return value** -## AbilityContext.startAbilityForResult +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| -startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; +**Example** + +```js +import Ability from '@ohos.application.Ability'; +var caller; +export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "com.example.myservice.MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + console.log('Caller GetCaller Get ' + call); + }).catch((e) => { + console.log('Caller GetCaller error ' + e); + }); + } +} +``` + +## startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. +Starts an ability with **accountId** specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +var accountId = 11; +this.context.startAbility(want, accountId, (error) => { + console.log("error.code = " + error.code) +}) +``` + +## startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void +Starts an ability with **accountId** and **options** specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** + +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +var options = { + windowMode: 0, +}; +var accountId = 11; +this.context.startAbility(want, accountId, options, (error) => { + console.log("error.code = " + error.code) +}) +``` - ```js - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` -## AbilityContext.startAbilityForResult +## startAbilityWithAccount -startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; +startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\ -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. +Starts an ability with **accountId** and **options** specified. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| options | StartOptions | No| Parameters used for starting the ability.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +}; +var options = { + windowMode: 0, +}; +var accountId = 11; +this.context.startAbility(want, accountId, options) +.then((data) => { + console.log('Operation successful.') +}).catch((error) => { + console.log('Operation failed.'); +}) +``` + +## startAbilityForResult - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void + +Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#AbilityResult)> | Yes| Callback used to return the result.| + +**Example** + +```js +this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, + (error, result) => { + console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) + console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) + } +); +``` -## AbilityContext.startAbilityForResult +## startAbilityForResult -startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; +startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void -Starts an ability. This API uses a promise to return the execution result when the ability is terminated. +Starts an ability with **options** specified. This API uses an asynchronous callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#AbilityResult)> | Yes| Callback used to return the result.| + +**Example** + +```js +var options = { + windowMode: 0, +}; +this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, + (error, result) => { + console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) + console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) + } +); +``` + + +## startAbilityForResult + +startAbilityForResult(want: Want, options: StartOptions): Promise<AbilityResult>; + +Starts an ability with **options** specified. This API uses a promise to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| options | StartOptions | Yes| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-featureAbility.md#AbilityResult)> | Promise used to return the result.| **Example** +```js +var options = { + windowMode: 0, +}; +this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { + console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) +}, (error) => { + console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) +}) +``` + +## startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void + +Starts an ability with **accountId** specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#AbilityResult)> | Yes| Callback used to return the result.| - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { - console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) - }, (error) => { - console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) - }) - ``` +**Example** +```js +var accountId = 111; +this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, + accountId, + (error, result) => { + console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) + console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) + } +); +``` -## AbilityContext.terminateSelf +## startAbilityForResultWithAccount -terminateSelf(callback: AsyncCallback<void>): void; +startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void -Terminates this ability. This API uses a callback to return the result. +Starts an ability with **accountId** and **options** specified. This API uses an asynchronous callback to return the result when the ability is terminated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| options | StartOptions | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); - }); - ``` +```js +var options = { + windowMode: 0, +}; +var accountId = 111; +this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, + accountId, + options, + () => { + console.log("startAbilityForResult AsyncCallback is called") + } +); +``` +## startAbilityForResultWithAccount -## AbilityContext.terminateSelf +startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -terminateSelf(): Promise<void>; +Starts an ability with **accountId** and **options** specified. This API uses a promise to return the result when the ability is terminated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| options | StartOptions | Yes| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-featureAbility.md#AbilityResult)> | Promise used to return the result.| + +**Example** + +```js +var accountId = 111; +var options = { + windowMode: 0, +}; +this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, accountId, options).then((result) => { + console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) +}, (error) => { + console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) +}) +``` + +## terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void + +Terminates 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<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| + +**Example** + +```js +this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringfy(err)); +}); +``` + +## terminateSelf + +terminateSelf(): Promise<void> Terminates this ability. This API uses a promise to return the result. @@ -267,231 +504,350 @@ Terminates this ability. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| **Example** - ```js - this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - +```js +this.context.terminateSelf(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); +}); +``` -## AbilityContext.terminateSelfWithResult +## terminateSelfWithResult -terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void -Terminates this ability. This API uses a callback to return the information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses an asynchronous callback to return the information to the caller of **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-featureAbility.md#AbilityResult) | Yes| Information returned to the caller.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }, (error) => { - console.log("terminateSelfWithResult is called = " + error.code) - } - ); - ``` +```js +this.context.terminateSelfWithResult( + { + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 + }, (error) => { + console.log("terminateSelfWithResult is called = " + error.code) + } +); +``` -## AbilityContext.terminateSelfWithResult +## terminateSelfWithResult -terminateSelfWithResult(parameter: AbilityResult): Promise<void>; +terminateSelfWithResult(parameter: AbilityResult): Promise<void> Terminates this ability. This API uses a promise to return information to the caller of **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-featureAbility.md#AbilityResult) | Yes| Information returned to the caller.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** +```js +this.context.terminateSelfWithResult( +{ + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 +}).then((result) => { + console.log("terminateSelfWithResult") +}) +``` + +## connectAbility + +connectAbility(want: Want, options: ConnectOptions): number + +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| options | ConnectOptions | Yes| Connection channel.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| number | ID of the connection between the two abilities.| **Example** +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +} +var options = { + onConnect: (elementName, remote) => { + console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) + }, + onDisconnect: (elementName) => { + console.log('connectAbility onDisconnect, elementName: ' + elementName) + }, + onFailed: (code) => { + console.log('connectAbility onFailed, code: ' + code) + } +} +this.context.connectAbility(want, options) { + console.log('code: ' + code) +} +``` + +## connectAbilityWithAccount + +connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number + +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability based on an account. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }).then((result) => { - console.log("terminateSelfWithResult") +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID.| +| options | ConnectOptions | Yes| Connection channel.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | ID of the connection between the two abilities.| + +**Example** +```js +var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" +} +var accountId = 111; +var options = { + onConnect: (elementName, remote) => { + console.log('connectAbility onConnect, elementName: ' + elementName + ', remote: ' remote) + }, + onDisconnect: (elementName) => { + console.log('connectAbility onDisconnect, elementName: ' + elementName) + }, + onFailed: (code) => { + console.log('connectAbility onFailed, code: ' + code) } - ) - ``` +} +this.context.connectAbility(want, accountId, options) { + console.log('code: ' + code) +} +``` +## disconnectAbility -## AbilityContext.startAbilityByCall +disconnectAbility(connection: number, callback:AsyncCallback\): void -startAbilityByCall(want: Want): Promise<Caller>; +Disconnects this ability from another ability. This API uses an asynchronous callback to return the result. -Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| ID of the connection to be disconnected.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```js +var connection = 111; +this.context.disconnectAbility(connection, () => { + console.log('disconnection') +}) +``` + +## disconnectAbility + +disconnectAbility(connection: number): Promise\ + +Disconnects this ability from another ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| ID of the connection to be disconnected.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Caller> | Promise used to return the caller object to communicate with.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - console.log('Caller GetCaller Get ' + call); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` +```js +var connection = 111; +this.context.disconnectAbility(connection).then(() => { + console.log('disconnect success') +}).catch((err) => { + console.log('disconnect filed') +}) +``` -## AbilityContext.requestPermissionsFromUser +## setMissionLabel -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; +setMissionLabel(label: string, callback:AsyncCallback<void>): void -Requests permissions from the user by displaying a pop-up window. This API uses a callback to return the result. +Sets the label of the ability in the mission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| - | callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| **Example** - ``` - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - ``` +```js +this.context.setMissionLabel("test",(result) => { + console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); +}); +``` -## AbilityContext.requestPermissionsFromUser +## setMissionLabel -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; +setMissionLabel(label: string): Promise\ -Requests permissions from the user by displaying a pop-up window. This API uses a promise to return the result. +Sets the label of the ability in the mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result indicating whether the API is successfully called.| **Example** - ``` - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - +```js +this.context.setMissionLabel("test").then((data) => { + console.log('success:' + JSON.stringfy(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); +}); +``` -## AbilityContext.setMissionLabel +## requestPermissionsFromUser -setMissionLabel(label: string, callback:AsyncCallback<void>): void; +requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void -Sets the label of the ability displayed in the task. This API uses a callback to return the result. +Requests permissions from end users in the form of a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| Permissions to request.| +| callback | AsyncCallback<PermissionRequestResult> | Yes| Callback used to return the result indicating whether the API is successfully called.| **Example** - ```js - this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - ``` +```js +this.context.requestPermissionsFromUser(permissions,(result) => { + console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); +}); +``` -## AbilityContext.setMissionLabel +## requestPermissionsFromUser -setMissionLabel(label: string): Promise<void> +requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult> -Sets the label of the ability displayed in the task. This API uses a promise to return the result. +Requests permissions from end users in the form of a dialog box. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| Permissions to request.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| +| Type| Description| +| -------- | -------- | +| Promise<PermissionRequestResult> | Promise used to return the result indicating whether the API is successfully called.| **Example** - ```js - this.context.setMissionLabel("test").then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` +```js +this.context.requestPermissionsFromUser(permissions).then((data) => { + console.log('success:' + JSON.stringfy(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); +}); +``` + +## restoreWindowStage + +restoreWindowStage(contentStorage: ContentStorage) : void + +Restores the window stage data during ability continuation. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| contentStorage | ContentStorage | Yes| Window stage data to restore.| + +**Example** + +```js +var contentStorage = { + "link": 'link', +}; +this.context.restoreWindowStage(contentStorage); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilityManager.md b/en/application-dev/reference/apis/js-apis-abilityManager.md index ccd0cd96c51f747588cb30bd7a3144fd34534c9c..a7c52b8c10ec3221565d7bc21b40866ad3b770d6 100644 --- a/en/application-dev/reference/apis/js-apis-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-abilityManager.md @@ -1,6 +1,6 @@ # AbilityManager -> **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. > @@ -18,13 +18,13 @@ Enumerates the ability states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| INITIAL | 0 | The ability is in the initial state.| -| FOREGROUND | 9 | The ability is in the foreground state. | -| BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | ## updateConfiguration diff --git a/en/application-dev/reference/apis/js-apis-abilityStageContext.md b/en/application-dev/reference/apis/js-apis-abilityStageContext.md index f5d9e951461c0ff77ac85e75bd60c6d657074a66..786affbe343ea5993351de7ea8689a6e6e0e69a6 100644 --- a/en/application-dev/reference/apis/js-apis-abilityStageContext.md +++ b/en/application-dev/reference/apis/js-apis-abilityStageContext.md @@ -1,19 +1,23 @@ # AbilityStageContext -> ![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. Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md). +## Modules to Import + +```js +import AbilityStage from '@ohos.application.AbilityStage'; +``` ## Usage The ability stage context is obtained through an **AbilityStage** instance. - - ```js import AbilityStage from '@ohos.application.AbilityStage'; class MyAbilityStage extends AbilityStage { @@ -28,7 +32,7 @@ class MyAbilityStage extends AbilityStage { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| +| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md index b4f137e8d3f3da19beb7a1b5a8bbbc8a4ab74ee3..555b5562aea4b9cfd83491c17b52dd598c342fcd 100644 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md @@ -1,19 +1,23 @@ # AbilityRunningInfo -> ![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. Provides ability running information. +## Modules to Import + +```js +import abilitymanager from '@ohos.application.abilityManager'; +``` ## Usage The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. - - ```js import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getAbilityRunningInfos((err,data) => { @@ -27,12 +31,12 @@ abilitymanager.getAbilityRunningInfos((err,data) => { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| No| Information that matches an ability. | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID. | -| processName | string | Yes| No| Process name. | -| startTime | number | Yes| No| Ability start time. | -| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | Yes| No| Ability state. | +| ability | ElementName | Yes| No| Information that matches an ability. | +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID. | +| processName | string | Yes| No| Process name. | +| startTime | number | Yes| No| Ability start time. | +| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | Yes| No| Ability state. | ## abilityManager.AbilityState @@ -41,10 +45,10 @@ Enumerates the ability states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| INITIAL | 0 | The ability is in the initial state.| -| FOREGROUND | 9 | The ability is in the foreground state. | -| BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the foregrounding state. | +| BACKGROUNDING | 12 | The ability is in the backgrounding state. | diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 462e56f7d18c0df2661e1ce1944bce0d159fcffe..590e3145e6e8f43507ad2b9c4aacd05085e905a7 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,248 +1,240 @@ -# Animation +# Animator + +> **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. ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -**requestAnimationFrame**: none +``` +import animator from '@ohos.animator'; +``` + + +## createAnimator + +createAnimator(options: AnimatorOptions): AnimatorResult + +Creates an **Animator** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| + +**Return value** +| Type| Description| +| -------- | -------- | +| [AnimatorResult](#animatorresult) | Animator result.| + +**Example** + + ``` + +
+
+
+
+ ``` + + ``` + // js + export default { + data : { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + var options = { + duration: 1500, + easing: 'friction', + fill: 'forwards', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.createAnimator(options); + }, + Show() { + var options1 = { + duration: 2000, + easing: 'friction', + fill: 'forwards', + iterations: 1, + begin: 200.0, + end: 400.0 + }; + this.animator.update(options1); + var _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); + } + } + ``` + +## AnimatorResult + +Defines the animator result. + +### update + +update(options: AnimatorOptions): void + +Updates this animator. -**cancelAnimationFrame**: none +**System capability**: SystemCapability.ArkUI.ArkUI.Full -**createAnimator**: +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| +**Example** ``` -import animator from '@ohos.animator'; +animator.update(options); ``` -## Required Permissions +### play -None +play(): void -## requestAnimationFrame +Plays this animation. -requestAnimationFrame\(handler\[, \[ ...args\]\]\): number +**System capability**: SystemCapability.ArkUI.ArkUI.Full -Requests an animation frame. +**Example** +``` +animator.play(); +``` -- Parameters +### finish - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Handler used to request a frame. When **requestAnimationFrame** calls the **handler**, the timestamp is passed to the first parameter to indicate the time when **requestAnimationFrame** starts to execute the callback. | - | ...args | Array\ | No | Additional parameter, which is passed to the **handler** as a parameter during function callback. | +finish(): void -- Return values +Ends this animation. - | Type | Description | - | ------ | ----------- | - | number | Request ID. | - -- Example +**System capability**: SystemCapability.ArkUI.ArkUI.Full - ``` - -
- -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - } - } - ``` +**Example** +``` +animator.finish(); +``` +### pause -## cancelAnimationFrame +pause(): void -cancelAnimationFrame\(requestId: number\): void +Pauses this animation. -Cancels the animation frame request. +**System capability**: SystemCapability.ArkUI.ArkUI.Full -- Parameters +**Example** +``` +animator.pause(); +``` - | Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ------------------------ | - | requestId | number | Yes | ID of the frame request. | - -- Example +### cancel - ``` - -
- - -
- ``` - - ``` - /* xxx.css */ - .container { - flex-direction: column; - justify-content: center; - align-items: center; - width: 100%; - height: 100%; - } - .btn{ - width: 300px; - margin-top: 40px; - } - ``` - - ``` - /* xxx.js */ - export default { - data: { - requestId: 0, - startTime: 0, - }, - beginAnimation() { - cancelAnimationFrame(this.requestId); - this.requestId = requestAnimationFrame(this.runAnimation); - }, - runAnimation(timestamp) { - if (this.startTime == 0) { - this.startTime = timestamp; - } - var elapsed = timestamp - this.startTime; - if (elapsed < 500) { - console.log('callback handler timestamp: ' + timestamp); - this.requestId = requestAnimationFrame(this.runAnimation); - } - }, - stopAnimation() { - cancelAnimationFrame(this.requestId); - } - } - ``` +cancel(): void +Cancels this animation. -## createAnimator +**System capability**: SystemCapability.ArkUI.ArkUI.Full -createAnimator\(options\[...\]\): void - -Creates an animation object. - -- Parameters - - | Name | Type | Mandatory | Description | - | ------- | ------ | --------- | ------------------------------------------------------------ | - | options | Object | Yes | Attributes of the **Animator** to be created. For details, see the options table. | - -- Description of options - - | Name | Type | Mandatory | Description | - | ---------- | ------ | --------- | ------------------------------------------------------------ | - | duration | number | No | Duration for playing an animation, in milliseconds. The default value is **0**. | - | easing | string | No | Animation easing curve. The default value is **ease**. | - | delay | number | No | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. | - | fill | string | No | Animation start/stop mode. The default value is **none**. | - | direction | string | No | Animation playback mode. The default value is **normal**. | - | iterations | number | No | Number of times that an animation is played. The default value is **1**. If this parameter is set to **0**, the animation is not played. If this parameter is set to **-1**, the animation is played for an unlimited number of times. | - | begin | number | No | Start point of the animation easing. If this parameter is not set, the default value **0** is used. | - | end | number | No | End point of the animation easing. If this parameter is not set, the default value **1** is used. | - -- animator interfaces - - | Name | Type | Description | - | ------- | ------- | ------------------------------------------------------------ | - | update | options | Updates the animation parameters. The input parameters are the same as those of **createAnimator**. | - | play | - | Starts an animation. | - | finish | - | Ends an animation. | - | pause | - | Pauses an animation. | - | cancel | - | Cancels an animation. | - | reverse | - | Reverses an animation. | - - -- **animator** supported events: - - | Name | Type | Description | - | ------ | ------ | ----------------------------------- | - | frame | number | The frame is requested. | - | cancel | - | The animation is forcibly canceled. | - | finish | - | The animation playback is complete. | - | repeat | - | The animation replays. | - -- Example - - ``` - -
-
-
-
- ``` - - ``` - // js - export default { - data : { - divWidth: 200, - divHeight: 200, - animator: null - }, - onInit() { - var options = { - duration: 1500, - easing: 'friction', - fill: 'forwards', - iterations: 2, - begin: 200.0, - end: 400.0 - }; - this.animator = animator.createAnimator(options); - }, - Show() { - var options1 = { - duration: 2000, - easing: 'friction', - fill: 'forwards', - iterations: 1, - begin: 200.0, - end: 400.0 - }; - this.animator.update(options1); - var _this = this; - this.animator.onframe = function(value) { - _this.divWidth = value; - _this.divHeight = value; - }; - this.animator.play(); - } - } - ``` \ No newline at end of file +**Example** +``` +animator.cancel(); +``` + +### reverse + +reverse(): void + +Plays this animation in reverse order. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.reverse(); +``` + +### onframe + +onframe: (progress: number) => void + +Called when a frame is received. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | number | Yes| Current progress of the animation.| + +**Example** +``` +animator.onframe(); +``` + +### onfinish + +onfinish: () => void + +Called when this animation is finished. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onfinish(); +``` + +### oncancel + +oncancel: () => void + +Called when this animation is canceled. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.oncancel(); +``` + +### onrepeat + +onrepeat: () => void + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** +``` +animator.onrepeat(); +``` + +Called when this animation repeats. + +## AnimatorOptions + +Defines animator options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| +| easing | string | Yes| Animation interpolation curve. The default value is **ease**.| +| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| +| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that after the animation is executed, the target will retain the state (defined by the last keyframe) it is in when the animation ends.| +| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| +| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.| +| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.| +| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.| diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index 30d7ac0dd8a49df8f05cab425baa6d781d18371e..dfa57f762424de8035a8febcd2262b4c2431d004 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 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -26,7 +26,7 @@ Creates an **AppAccountManager** instance. **Example** ```js - var appAccountManager = account.createAppAccountManager(); + const appAccountManager = account_appAccount.createAppAccountManager(); ``` ## AppAccountManager @@ -387,7 +387,7 @@ Checks whether an app account allows application data synchronization. This meth ### setAccountCredential -setAccountCredential(name: string, credentialType: string, credential: string, callback: AsyncCallback<void>): void +setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void Sets a credential for an app account. This method uses an asynchronous callback to return the result. diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md index 0c8f62fcfb300c152b632fa434cd28e603a2c835..1650aa1821597bb9b6891d4e6d5addea9226ae1c 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md @@ -1,8 +1,10 @@ # AbilityDelegator -> **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. +> +> API version 9 is a canary version for trial use. The APIs of this version may be unstable. ## Modules to Import @@ -10,11 +12,518 @@ import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' ``` +## AbilityDelegator +### addAbilityMonitor9+ -## AbilityDelegator +addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void + +Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor, (err : any) => { + console.info("addAbilityMonitor callback"); +}); +``` + +### addAbilityMonitor9+ + +addAbilityMonitor(monitor: AbilityMonitor): Promise\ + +Adds an **AbilityMonitor** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor).then(() => { + console.info("addAbilityMonitor promise"); +}); +``` + +### removeAbilityMonitor9+ + +removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void + +Removes an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { + console.info("removeAbilityMonitor callback"); +}); +``` + +### removeAbilityMonitor9+ + +removeAbilityMonitor(monitor: AbilityMonitor): Promise\ + +Removes an **AbilityMonitor** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.removeAbilityMonitor(monitor).then(() => { + console.info("removeAbilityMonitor promise"); +}); +``` + +### waitAbilityMonitor9+ + +waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void + +Waits for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { + console.info("waitAbilityMonitor callback"); +}); +``` + +### waitAbilityMonitor9+ + +waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void + +Waits a period of time for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| timeout | number | Yes | Maximum waiting time, in milliseconds. | +| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | + +**Example** + +```js +var abilityDelegator; +var timeout = 100; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => { + console.info("waitAbilityMonitor callback"); +}); +``` + +### waitAbilityMonitor9+ + +waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ + +Waits a period of time for the ability that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle and returns the **Ability** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| timeout | number | No | Maximum waiting time, in milliseconds. | + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | -------------------------- | +| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the **Ability** instance.| + +**Example** + +```js +var abilityDelegator; + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { + console.info("waitAbilityMonitor promise"); +}); +``` + +### getAppContext9+ + +getAppContext(): Context + +Obtains the application context. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------- | ------------------------------------------- | +| [Context](js-apis-Context.md#Context) | [Context](js-apis-Context.md#Context) of the application.| + +**Example** + +```js +var abilityDelegator; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +var context = abilityDelegator.getAppContext(); +``` + +### getAbilityState9+ + +getAbilityState(ability: Ability): number + +Obtains the lifecycle state of an ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------- | ---- | --------------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes | Target ability.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Lifecycle state of the ability. For details about the available enumerated values, see [AbilityLifecycleState](js-apis-abilityDelegatorRegistry.md#AbilityLifecycleState).| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; + var state = abilityDelegator.getAbilityState(ability); + console.info("getAbilityState" + state); +}); +``` + +### getCurrentTopAbility9+ + +getCurrentTopAbility(callback: AsyncCallback\): void + +Obtains the top ability of the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; +}); +``` + +### getCurrentTopAbility9+ + +getCurrentTopAbility(): Promise\ + +Obtains the top ability of the application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | -------------------------------------- | +| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the top ability.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility().then((data : any) => { + console.info("getCurrentTopAbility promise"); + ability = data; +}); +``` + +### doAbilityForeground9+ + +doAbilityForeground(ability: Ability, callback: AsyncCallback\): void -### startAbility +Schedules the lifecycle state of an ability to **Foreground**. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------- | +| ability | Ability | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; + abilityDelegator.doAbilityForeground(ability, (err : any, data : any) => { + console.info("doAbilityForeground callback"); + }); +}); +``` + +### doAbilityForeground9+ + +doAbilityForeground(ability: Ability): Promise\ + +Schedules the lifecycle state of an ability to **Foreground**. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | --------------- | +| ability | Ability | Yes | Target ability.| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; + abilityDelegator.doAbilityForeground(ability).then((data : any) => { + console.info("doAbilityForeground promise"); + }); +}); +``` + +### doAbilityBackground9+ + +doAbilityBackground(ability: Ability, callback: AsyncCallback\): void + +Schedules the lifecycle state of an ability to **Background**. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------- | +| ability | Ability | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; + abilityDelegator.doAbilityBackground(ability, (err : any, data : any) => { + console.info("doAbilityBackground callback"); + }); +}); +``` + +### doAbilityBackground9+ + +doAbilityBackground(ability: Ability): Promise\ + +Schedules the lifecycle state of an ability to **Background**. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | --------------- | +| ability | Ability | Yes | Target ability.| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation fails.| + +**Example** + +```js +var abilityDelegator; +var ability; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.getCurrentTopAbility((err : any, data : any) => { + console.info("getCurrentTopAbility callback"); + ability = data; + abilityDelegator.doAbilityBackground(ability).then((data : any) => { + console.info("doAbilityBackground promise"); + }); +}); +``` + +### startAbility9+ startAbility(want: Want, callback: AsyncCallback\): void @@ -46,7 +555,7 @@ abilityDelegator.startAbility(want, (err, data) => { -### startAbility +### startAbility9+ startAbility(want: Want): Promise\ @@ -81,6 +590,8 @@ abilityDelegator.startAbility(want).then((data: any) => { }); ``` + + ### print print(msg: string, callback: AsyncCallback\): void @@ -157,7 +668,7 @@ Executes a shell command. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | | cmd | string | Yes | Shell command string. | -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result.| **Example** @@ -187,7 +698,7 @@ Executes a shell command with the timeout period specified. This API uses an asy | ----------- | ------------------------------------------------------------ | ---- | ----------------------------- | | cmd | string | Yes | Shell command string. | | timeoutSecs | number | Yes | Command timeout period, in seconds.| -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object. | +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result. | **Example** @@ -206,7 +717,7 @@ abilityDelegator.executeShellCommand(cmd, timeout, (err, data) => { ### executeShellCommand -executeShellCommand(cmd: string, timeoutSecs: number): Promise\ +executeShellCommand(cmd: string, timeoutSecs?: number): Promise\; Executes a shell command with the timeout period specified. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-application-missionInfo.md index 132865404467fd607538615d7674afbe19ef7ad2..2fcab5e80e4f3dfdf3dcc9ac259ad31254b427ff 100644 --- a/en/application-dev/reference/apis/js-apis-application-missionInfo.md +++ b/en/application-dev/reference/apis/js-apis-application-missionInfo.md @@ -1,6 +1,7 @@ # MissionInfo -> **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 diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 45f347cf9dc3c36552b5f9db66127d1d9361b2a8..ee5095aba5ba61018f68ce9147ccc54049fab321 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -1,6 +1,7 @@ # appManager -> ![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. @@ -25,9 +26,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -49,9 +50,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -75,9 +76,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -99,9 +100,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -122,9 +123,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Size of the application memory.| **Example** @@ -146,9 +147,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | No| Size of the application memory.| **Example** @@ -160,7 +161,7 @@ Obtains the memory size of this application. This API uses an asynchronous callb ``` ## appManager.getProcessRunningInfos8+ -getProcessRunningInfos(): Promise>; +getProcessRunningInfos(): Promise\>; Obtains information about the running processes. This API uses a promise to return the result. @@ -168,9 +169,9 @@ Obtains information about the running processes. This API uses a promise to retu **Return value** - | Type| Description| - | -------- | -------- | - | Promise> | Promise used to return the process information.| +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| **Example** @@ -184,7 +185,7 @@ Obtains information about the running processes. This API uses a promise to retu ## appManager.getProcessRunningInfos8+ -getProcessRunningInfos(callback: AsyncCallback>): void; +getProcessRunningInfos(callback: AsyncCallback\>): void; Obtains information about the running processes. This API uses an asynchronous callback to return the result. @@ -192,9 +193,9 @@ Obtains information about the running processes. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback> | No| Callback used to return the process information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | No| Callback used to return the process information.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 9019234d28f4952b0d7a78130b6f6bc1eb0b17a5..332f8903b50359b0927e6437355a6492fccabb73 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,6 +1,7 @@ # Audio Management -> **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 release for trial use. The APIs of this version may be unstable. @@ -544,7 +545,7 @@ Describes the callback invoked for audio interruption or focus gain events. | ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| | type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](interrupthint) | No | Hint provided along with the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | | activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| ## VolumeEvent8+ @@ -2656,7 +2657,7 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo | Name | Type | Readable| Writable| Description | | :---- | :------------------------- | :--- | :--- | :--------------- | -| state8+ | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 1c15667d64c044997925abf523414c238e244899..eaeeb4eed2bad246570487fdd2a8f542d0bbb09b 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -67,10 +67,10 @@ Obtains the remaining duration before the application is suspended. This API use ```js let id = 1; backgroundTaskManager.getRemainingDelayTime(id, (err, res) => { - if(err.data === 0) { - console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); + if(err) { + console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code); } else { - console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.data); + console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); } }) ``` @@ -100,7 +100,7 @@ Obtains the remaining duration before the application is suspended. This API use backgroundTaskManager.getRemainingDelayTime(id).then( res => { console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); }).catch( err => { - console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); + console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index 5197114dc3068f84c457530b58ca8a7a5520d1c2..a0d93b14fc86287eeb8b9dedcff4bfd7f0d210f3 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,9 +1,9 @@ # Bluetooth -> ![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. -> -> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. + +Provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. ## Modules to Import @@ -223,7 +223,7 @@ Obtains the connection status of a profile. **Example** ```js -let result = bluetooth.getProfileConnState(PROFILE_A2DP_SOURCE); +let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ``` @@ -364,7 +364,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de ```js // The device can be discovered and connected only when the discoverable and connectable mode is used. -let result = bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); +let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); ``` @@ -456,7 +456,7 @@ Sets the device pairing confirmation. | Name | Type | Mandatory | Description | | ------ | ------- | ---- | -------------------------------- | -| device | string | Yes | Address of the target remote device, for example, XX:XX:XX:XX:XX:XX.| +| device | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| | accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | **Return value** @@ -729,7 +729,7 @@ bluetooth.off('stateChange', onReceiveEvent); ``` -## bluetooth.sppListen8+ +## bluetooth.sppListen8+ sppListen(name: string, option: SppOption, callback: AsyncCallback<number>): void @@ -782,6 +782,14 @@ Listens for a connection to be made to this socket from the client and accepts i **Example** ```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} let clientNumber = -1; function acceptClientSocket(code, number) { console.log('bluetooth error code: ' + code.code); @@ -847,6 +855,14 @@ Closes the listening socket of the server. **Example** ```js +let serverNumber = -1; +function serverSocket(code, number) { + console.log('bluetooth error code: ' + code.code); + if (code.code == 0) { + console.log('bluetooth serverSocket Number: ' + number); + serverNumber = number; + } +} bluetooth.sppCloseServerSocket(serverNumber); ``` @@ -869,6 +885,15 @@ Closes the client socket. **Example** ```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} bluetooth.sppCloseClientSocket(clientNumber); ``` @@ -897,6 +922,15 @@ Writes data to the remote device through the socket. **Example** ```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} let arrayBuffer = new ArrayBuffer(8); let data = new Uint8Array(arrayBuffer); data[0] = 123; @@ -932,6 +966,15 @@ No value is returned. **Example** ```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} function dataRead(dataBuffer) { let data = new Uint8Array(dataBuffer); console.log('bluetooth data is: ' + data[0]); @@ -963,6 +1006,15 @@ No value is returned. **Example** ```js +let clientNumber = -1; +function clientSocket(code, number) { + if (code.code != 0) { + return; + } + console.log('bluetooth serverSocket Number: ' + number); + // The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client. + clientNumber = number; +} bluetooth.off('sppRead', clientNumber); ``` @@ -1218,7 +1270,7 @@ No value is returned. | | | | ------------------- | ------------- | | Type | Description | -| Array<string> | List of addresses of the connected devices. | +| Array<string> | Addresses of the connected devices. | ### getDeviceState8+ @@ -1236,14 +1288,12 @@ Obtains the connection status of the profile. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | | device | string | Yes | Address of the target device.| -| - **Return value** | | | | ------------------------------------------------- | ----------------------- | | Type | Description | -| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained. | +| [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. | ## A2dpSourceProfile @@ -1251,7 +1301,7 @@ Obtains the connection status of the profile. Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method. -### connect8+ +### connect8+ connect(device: string): boolean @@ -1278,12 +1328,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+ disconnect(device: string): boolean @@ -1310,7 +1360,7 @@ Disconnects an A2DP connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1397,7 +1447,7 @@ Obtains the playing status of a device. **Example** ```js -let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); ``` @@ -1407,7 +1457,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method. -### connect8+ +### connect8+ connect(device: string): boolean @@ -1434,12 +1484,12 @@ Sets up a Hands-free Profile (HFP) connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); ``` -### disconnect8+ +### disconnect8+ disconnect(device: string): boolean @@ -1465,7 +1515,7 @@ Disconnects the HFP connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1665,7 +1715,7 @@ cccV[0] = 1; let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', - characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptorsN}; + characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; characteristics[0] = characteristic; // Create a gattService instance. @@ -1757,8 +1807,11 @@ Notifies the connected client device when a characteristic value changes. **Example** ```js +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', +characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', - characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: notifyCcc.characteristicValue, confirm: false}; +characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false}; let server = bluetooth.BLE.createGattServer(); server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); ``` @@ -1984,7 +2037,7 @@ Subscribes to the descriptor read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| -| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request from the GATT client. | +| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | **Return value** @@ -2334,7 +2387,7 @@ 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(); -let services = device.getServices(); +var services = device.getServices(); console.log("bluetooth services size is ", services.length); for (let i = 0; i < services.length; i++) { @@ -2672,8 +2725,11 @@ Sets the function of notifying the GATT client when the characteristic value of **Example** ```js +let arrayBufferC = new ArrayBuffer(8); +let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', + characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); -device.setNotifyCharacteristicChanged(notifyCcc, false); +device.setNotifyCharacteristicChanged(characteristic, false); ``` diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md new file mode 100644 index 0000000000000000000000000000000000000000..3f0d063a7e435b2f777f79bb6934aaf8d233e13a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -0,0 +1,111 @@ +# Standard NFC Card Emulation + +Implements Near-Field Communication (NFC) card emulation. + +> **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 cardEmulation from '@ohos.nfc.cardEmulation'; +``` + + +## cardEmulation.isSupported + +isSupported(feature: number): boolean + +Checks whether a certain type of card emulation is supported. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| + +## HceService + +Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. + +### startHCE + +startHCE(aidList: string[]): boolean + +Starts HCE. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------- | ---- | ----------------------- | +| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| + +### stopHCE + +stopHCE(): boolean + +Stops HCE. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +### on + +on(type: "hceCmd", callback: AsyncCallback): void; + +Subscribes to messages from the peer device after **startHCE()**. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------------- | +| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | +| callback | AsyncCallback | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| + +### sendResponse + +sendResponse(responseApdu: number[]): void; + +Sends a response to the peer device. + +**Required permissions**: ohos.permission.NFC_CARD_EMULATION + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | -------- | ---- | -------------------------------------------------- | +| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| + +**Example** + +```js +var hceService = new cardEmulation.HceService(); +hceService.startHCE([ + "F0010203040506", "A0000000041010" +]) +hceService.stopHCE(); +hceService.on("hceCmd", (err, res) => { + if(err.data === 0) { + console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); + hceService.sendResponse([0x00,0xa4,0x04,0x00, + 0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44, + 0x46,0x30,0x31,0x00]); + } else { + console.log('callback => Operation hceCmd failed. Cause: ' + err.data); + } +}) +``` 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 3991e4ab9dff7911220c98d4aa89b2c896cbb1fe..8145056a3d6788baa31f7b80fdc3b7565c0ec77a 100644 --- a/en/application-dev/reference/apis/js-apis-config-policy.md +++ b/en/application-dev/reference/apis/js-apis-config-policy.md @@ -1,14 +1,16 @@ # Configuration Policy -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module are system APIs and cannot be called by third-party applications. +> **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 import configPolicy from '@ohos.configPolicy'; ``` @@ -22,18 +24,18 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | relPath | string | Yes| Name of the configuration file.| - | callback | AsyncCallback<string> | Yes| Callback used to return the path of the configuration file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| relPath | string | Yes| Name of the configuration file.| +| callback | AsyncCallback<string> | Yes| Callback used to return the path of the configuration file.| **Example** - ``` + ```js configPolicy.getOneCfgFile('config.xml', (error, value) => { if (error == undefined) { - console.log(value); + console.log("value is " + value); } else { - console.log(error); + console.log("error occurs "+ error); } }); ``` @@ -48,19 +50,19 @@ Obtains the path of a configuration file with the specified name and highest pri **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | relPath | string | Yes| Name of the configuration file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| relPath | string | Yes| Name of the configuration file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the path of the configuration file.| +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the path of the configuration file.| **Example** - ``` + ```js configPolicy.getOneCfgFile('config.xml').then(value => { - console.log(value); + console.log("value is " + value); }).catch(error => { console.log("getOneCfgFile promise " + error); }); @@ -77,18 +79,18 @@ and **/sys-pod/etc/config.xml**, then **/system/etc/config.xml, /sys-pod/etc/con **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | relPath | string | Yes| Name of the configuration file.| - | callback | AsyncCallback<Array<string>> | Yes| Callback used to return the file list.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| relPath | string | Yes| Name of the configuration file.| +| callback | AsyncCallback<Array<string>> | Yes| Callback used to return the file list.| **Example** - ``` + ```js configPolicy.getCfgFiles('config.xml', (error, value) => { if (error == undefined) { - console.log(value); + console.log("value is " + value); } else { - console.log(error); + console.log("error occurs "+ error); } }); ``` @@ -103,19 +105,19 @@ Obtains all configuration files with the specified name and lists them in ascend **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | relPath | string | Yes| Name of the configuration file.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| relPath | string | Yes| Name of the configuration file.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<string>> | Promise used to return the file list.| +| Type| Description| +| -------- | -------- | +| Promise<Array<string>> | Promise used to return the file list.| **Example** - ``` + ```js configPolicy.getCfgFiles('config.xml').then(value => { - console.log(value); + console.log("value is " + value); }).catch(error => { console.log("getCfgFiles promise " + error); }); @@ -131,17 +133,17 @@ Obtains the configuration level directory list. This API uses an asynchronous ca **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Array<string>> | Yes| Callback used to return the configuration level directory list.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<string>> | Yes| Callback used to return the configuration level directory list.| **Example** - ``` + ```js configPolicy.getCfgDirList((error, value) => { if (error == undefined) { - console.log(value); + console.log("value is " + value); } else { - console.log(error); + console.log("error occurs "+ error); } }); ``` @@ -156,14 +158,14 @@ Obtains the configuration level directory list. This API uses a promise to retur **System capability**: SystemCapability.Customization.ConfigPolicy **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<string>> | Promise used to return the configuration level directory list.| +| Type| Description| +| -------- | -------- | +| Promise<Array<string>> | Promise used to return the configuration level directory list.| **Example** - ``` + ```js configPolicy.getCfgDirList().then(value => { - console.log(value); + console.log("value is " + value); }).catch(error => { console.log("getCfgDirList promise " + error); }); 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 64677ce758a5e1538c8112f714f3859ce0a11cd3..5e13507952dec34e32f7a4e49a75669ccc16fd82 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,7 @@ # DataAbilityPredicates > **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,7 +18,7 @@ import dataAbility from '@ohos.data.dataAbility'; createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates -Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. +Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -69,8 +70,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") ``` @@ -97,8 +97,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notEqualTo("NAME", "lisi") + dataAbilityPredicates.notEqualTo("NAME", "lisi") ``` @@ -119,8 +118,7 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -146,8 +144,7 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") + dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -173,8 +170,7 @@ Adds the OR condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` @@ -197,8 +193,7 @@ Adds the AND condition to this **DataAbilityPredicates**. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") + dataAbilityPredicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` @@ -227,8 +222,7 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.contains("NAME", "os") + dataAbilityPredicates.contains("NAME", "os") ``` @@ -255,8 +249,7 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.beginsWith("NAME", "os") + dataAbilityPredicates.beginsWith("NAME", "os") ``` @@ -283,8 +276,7 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Example** ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.endsWith("NAME", "se") + dataAbilityPredicates.endsWith("NAME", "se") ``` @@ -310,8 +302,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNull("NAME") + dataAbilityPredicates.isNull("NAME") ``` @@ -337,8 +328,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNotNull("NAME") + dataAbilityPredicates.isNotNull("NAME") ``` @@ -365,8 +355,7 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.like("NAME", "%os%") + dataAbilityPredicates.like("NAME", "%os%") ``` @@ -393,8 +382,7 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.glob("NAME", "?h*g") + dataAbilityPredicates.glob("NAME", "?h*g") ``` @@ -422,8 +410,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.between("AGE", 10, 50) + dataAbilityPredicates.between("AGE", 10, 50) ``` @@ -451,8 +438,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notBetween("AGE", 10, 50) + dataAbilityPredicates.notBetween("AGE", 10, 50) ``` @@ -479,8 +465,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThan("AGE", 18) + dataAbilityPredicates.greaterThan("AGE", 18) ``` @@ -507,8 +492,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThan("AGE", 20) + dataAbilityPredicates.lessThan("AGE", 20) ``` @@ -535,8 +519,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThanOrEqualTo("AGE", 18) + dataAbilityPredicates.greaterThanOrEqualTo("AGE", 18) ``` @@ -563,8 +546,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThanOrEqualTo("AGE", 20) + dataAbilityPredicates.lessThanOrEqualTo("AGE", 20) ``` @@ -590,8 +572,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByAsc("NAME") + dataAbilityPredicates.orderByAsc("NAME") ``` @@ -617,8 +598,7 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByDesc("AGE") + dataAbilityPredicates.orderByDesc("AGE") ``` @@ -639,14 +619,7 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").distinct("NAME") - let promiseDistinct = rdbStore.query(predicates, ["NAME"]) - promiseDistinct.then((resultSet) => { - console.log("distinct") - }).catch((err) => { - expect(null).assertFail(); - }) + dataAbilityPredicates.equalTo("NAME", "Rose").distinct() ``` @@ -672,8 +645,7 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").limitAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").limitAs(3) ``` @@ -699,8 +671,7 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").offsetAs(3) + dataAbilityPredicates.equalTo("NAME", "Rose").offsetAs(3) ``` @@ -726,8 +697,7 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.groupBy(["AGE", "NAME"]) + dataAbilityPredicates.groupBy(["AGE", "NAME"]) ``` ### indexedBy @@ -751,8 +721,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.indexedBy("SALARY_INDEX") + dataAbilityPredicates.indexedBy("SALARY_INDEX") ``` @@ -762,7 +731,7 @@ 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 @@ -780,8 +749,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.in("AGE", [18, 20]) + dataAbilityPredicates.in("AGE", [18, 20]) ``` @@ -791,7 +759,7 @@ 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 @@ -809,8 +777,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Example** ```js - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notIn("NAME", ["Lisa", "Rose"]) + dataAbilityPredicates.notIn("NAME", ["Lisa", "Rose"]) ``` ## ValueType diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 36761408ca6fe04d507711a0664f0903fa48be90..2fdec1122b455693f3998caece3969604b6fda7a 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,6 +1,9 @@ # Distributed Data Object +Provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. + > **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. @@ -31,14 +34,14 @@ Creates a distributed data object. **Example** ```js - import distributedObject from '@ohos.data.distributedDataObject' + import distributedObject from '@ohos.data.distributedDataObject'; // Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object. var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); ``` -## distributedObject.genSessionId() +## distributedObject.genSessionId genSessionId(): string @@ -53,7 +56,7 @@ Creates a random session ID. **Example** ```js - import distributedObject from '@ohos.data.distributedDataObject' + import distributedObject from '@ohos.data.distributedDataObject'; var sessionId = distributedObject.genSessionId(); ``` @@ -85,7 +88,7 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Example** ```js - import distributedObject from '@ohos.data.distributedDataObject' + import distributedObject from '@ohos.data.distributedDataObject'; var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}}); // Add g_object to the distributed network. @@ -110,19 +113,19 @@ Subscribes to the changes of this distributed data object. | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject' - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - g_object.on("change", function (sessionId, changeData) { - console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + g_object[element]); - }); - } - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.changeCallback = (sessionId, changeData) => { + console.info("change" + sessionId); + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + g_object[element]); + }); + } +} +g_object.on("change", globalThis.changeCallback); +``` ### off('change') @@ -136,24 +139,18 @@ Unsubscribes from the changes of this distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback used to return the changes of the distributed data object. If this parameter is not specified, this API unsubscribes from all callbacks for data changes of this distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not specified, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject' - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - g_object.on("change", function (sessionId, changeData) { - console.info("change" + sessionId); - }); - // Unsubscribe from the specified data change callback for the distributed data object. - g_object.off("change", function (sessionId, changeData) { - console.info("change" + sessionId); - }); - // Unsubscribe from all data change callbacks for the distributed data object. - g_object.off("change"); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +// Unregister the specified data change callback. +g_object.off("change", globalThis.changeCallback); +// Unregister all data change callbacks. +g_object.off("change"); +``` ### on('status') @@ -170,14 +167,14 @@ Subscribes to the status change (online or offline) of this distributed data obj | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the network ID of the device.
**status** indicates the status, which can be online or offline.| **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject' - var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, - parent:{mother:"jack mom",father:"jack Dad"}}); - g_object.on("status", function (sessionId, networkid, status) { - this.response += "status changed " + sessionId + " " + status + " " + networkId; - }); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +g_object.on("status", globalThis.statusCallback); +``` ### off('status') @@ -196,15 +193,14 @@ Unsubscribes from the status change (online or offline) of this distributed data **Example** - ```js - import distributedObject from '@ohos.data.distributedDataObject' - g_object.on("status", function (sessionId, networkId, status) { - this.response += "status changed " + sessionId + " " + status + " " + networkId; - }); - // Unsubscribe from the specified status change callback for the distributed data object. - g_object.off("status", function (sessionId, networkId, status) { - this.response += "status changed " + sessionId + " " + status + " " + networkId; - }); - // Unsubscribe from all status change callbacks for the distributed data object. - g_object.off("status"); - ``` +```js +import distributedObject from '@ohos.data.distributedDataObject'; +var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}}); +globalThis.statusCallback = (sessionId, networkId, status) => { + globalThis.response += "status changed " + sessionId + " " + status + " " + networkId; +} +// Unsubscribe from the specified status change callback for the distributed data object. +g_object.off("status",globalThis.statusCallback); +// Unsubscribe from all status change callbacks for the distributed data object. +g_object.off("status"); +``` 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 e55888e4c0e8fd24cd986fccb8663719ee8f4ed7..6d2e4596a6a87b585dbb83e886a32eb5868a8125 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -6,14 +6,12 @@ Lightweight storage provides applications with data processing capability and al > **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 dataStorage from '@ohos.data.storage'; +import data_storage from '@ohos.data.storage'; ``` ## Constants @@ -26,7 +24,7 @@ import dataStorage from '@ohos.data.storage'; | MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| -## dataStorage.getStorageSync +## data_storage.getStorageSync getStorageSync(path: string): Storage @@ -46,24 +44,17 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + 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() - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { - if (err) { - console.error('getFilesDir failed. err: ' + JSON.stringify(err)); - return; - } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - let storage = dataStorage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() - }); ``` -## dataStorage.getStorage +## data_storage.getStorage getStorage(path: string, callback: AsyncCallback<Storage>): void @@ -79,29 +70,21 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + import data_storage from '@ohos.data.storage' - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { + var path = '/data/storage/el2/database/test_storage' + data_storage.getStorage(path + '/mystore', function (err, storage) { if (err) { - console.error('getFilesDir failed. err: ' + JSON.stringify(err)); + console.info("Get the storage failed, path: " + path + '/mystore') return; } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - dataStorage.getStorage(path + '/mystore', function (err, storage) { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - storage.putSync('startup', 'auto') - storage.flushSync() - }) - }); + storage.putSync('startup', 'auto') + storage.flushSync() + }) ``` -## dataStorage.getStorage +## data_storage.getStorage getStorage(path: string): Promise<Storage> @@ -121,28 +104,21 @@ Reads the specified file and loads its data to the **Storage** instance for data **Example** ```js - import dataStorage from '@ohos.data.storage' - import featureAbility from '@ohos.ability.featureAbility' + import data_storage from '@ohos.data.storage' - var context = featureAbility.getContext() - context.getFilesDir((err, path) => { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - console.info('getFilesDir successful. path:' + JSON.stringify(path)); - let promisegetSt = dataStorage.getStorage(path + '/mystore') - promisegetSt.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) - }); + 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') + }) ``` -## dataStorage.deleteStorageSync +## data_storage.deleteStorageSync deleteStorageSync(path: string): void @@ -157,11 +133,11 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Example** ```js - dataStorage.deleteStorageSync(path + '/mystore') + data_storage.deleteStorageSync(path + '/mystore') ``` -## dataStorage.deleteStorage +## data_storage.deleteStorage deleteStorage(path: string, callback: AsyncCallback<void>): void @@ -177,7 +153,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Example** ```js - dataStorage.deleteStorage(path + '/mystore', function (err) { + data_storage.deleteStorage(path + '/mystore', function (err) { if (err) { console.info("Deleted failed with err: " + err) return @@ -187,7 +163,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete ``` -## dataStorage.deleteStorage +## data_storage.deleteStorage deleteStorage(path: string): Promise<void> @@ -207,7 +183,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Example** ```js - let promisedelSt = dataStorage.deleteStorage(path + '/mystore') + let promisedelSt = data_storage.deleteStorage(path + '/mystore') promisedelSt.then(() => { console.info("Deleted successfully.") }).catch((err) => { @@ -216,7 +192,7 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete ``` -## dataStorage.removeStorageFromCacheSync +## data_storage.removeStorageFromCacheSync removeStorageFromCacheSync(path: string): void @@ -231,11 +207,11 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Example** ```js - dataStorage.removeStorageFromCacheSync(path + '/mystore') + data_storage.removeStorageFromCacheSync(path + '/mystore') ``` -## dataStorage.removeStorageFromCache +## data_storage.removeStorageFromCache removeStorageFromCache(path: string, callback: AsyncCallback<void>): void @@ -251,7 +227,7 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Example** ```js - dataStorage.removeStorageFromCache(path + '/mystore', function (err) { + data_storage.removeStorageFromCache(path + '/mystore', function (err) { if (err) { console.info("Removed storage from cache failed with err: " + err) return @@ -261,7 +237,7 @@ Removes the singleton **Storage** instance of a file from the cache. The removed ``` -## dataStorage.removeStorageFromCache +## data_storage.removeStorageFromCache removeStorageFromCache(path: string): Promise<void> @@ -281,7 +257,7 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Example** ```js - let promiserevSt = dataStorage.removeStorageFromCache(path + '/mystore') + let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') promiserevSt.then(() => { console.info("Removed storage from cache successfully.") }).catch((err) => { diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index c96898a1f06c591a7f73ba4026eeede3654dc70a..80bc7063b2642574e791ae2c68025cfadd1b3c86 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -1,6 +1,7 @@ -# DataAbilityHelper Module (JavaScript SDK APIs) +# DataAbilityHelper -> ![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. ## Modules to Import @@ -553,7 +554,7 @@ DAHelper.insert( ## DataAbilityHelper.batchInsert -batchInsert(uri: string, valuesBuckets: Array\, callback: AsyncCallback\): void +batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\): void Inserts multiple data records into the database. This API uses an asynchronous callback to return the result. @@ -881,7 +882,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Type| Description| |------ | ------- | -|Promise<[PacMap](#pacmap)> | Promise used to return the result.| +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 26df1527338c29e9021bc941ffdaac3587460d22..994fe3a673ca9d505c0a6f96df6f007fe6d027d4 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,7 +1,6 @@ # Display -> **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. ## Modules to Import @@ -60,24 +59,22 @@ Obtains the default display object. **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 @@ -89,20 +86,20 @@ Obtains the default display object. **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 + let promise = display.getDefaultDisplay(); + promise.then(() => { + console.log('getDefaultDisplay success'); + }).catch((err) => { + console.log('getDefaultDisplay fail: ' + JSON.stringify(err)); + }); + ``` ## display.getAllDisplay @@ -114,21 +111,21 @@ Obtains all the display objects. **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 @@ -140,20 +137,20 @@ Obtains all the display objects. **Return value** -| Type | Description | -| ----------------------------------------------- | ------------------------------------------------------- | -| Promise<Array<[Display](#display)>> | Promise used to return an array containing all the display objects.| + | Type | Description | + | ----------------------------------------------- | ------------------------------------------------------- | + | Promise<Array<[Display](#display)>> | Promise used to return an array containing 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(() => { + console.log('getAllDisplay success'); + }).catch((err) => { + console.log('getAllDisplay fail: ' + JSON.stringify(err)); + }); + ``` ## display.on('add'|'remove'|'change') @@ -164,21 +161,18 @@ Enables listening. **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| 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.| **Example** - -```js -var type = "add"; -var callback = (data) => { - console.info('Listening enabled. Data: ' + JSON.stringify(data)) -} -display.on(type, callback); -``` + ```js + var callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)) + } + display.on("add", callback); + ``` ## display.off('add'|'remove'|'change') @@ -190,15 +184,12 @@ Disables listening. **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| 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.| **Example** - -```js -var type = "remove"; -display.off(type); -``` \ No newline at end of file + ```js + display.off("remove"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-eventhub.md b/en/application-dev/reference/apis/js-apis-eventhub.md index 1ee467b32f47d6f277783d6c02e6f842939d8ae8..ace4821e38335cd96971c9bdebd62f34a3783c4a 100644 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ b/en/application-dev/reference/apis/js-apis-eventhub.md @@ -1,19 +1,23 @@ # EventHub -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. Implements event subscription, unsubscription, and triggering. +## Modules to Import + +```js +import Ability from '@ohos.application.Ability' +``` ## Usage Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. - - ```js import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { @@ -34,10 +38,10 @@ Subscribes to an event. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | Yes| Callback invoked when the event is triggered.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | Yes| Callback invoked when the event is triggered.| **Example** @@ -72,10 +76,10 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| **Example** @@ -110,10 +114,10 @@ Triggers an event. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-extensionAbilityInfo.md b/en/application-dev/reference/apis/js-apis-extensionAbilityInfo.md index abee12afeee1aebc4fc898217719b50924a29fb4..c5bf0425a416168b7423f9f275cb3c180d6aacb7 100644 --- a/en/application-dev/reference/apis/js-apis-extensionAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionAbilityInfo.md @@ -1,9 +1,15 @@ # ExtensionAbilityInfo -> **NOTE**
+> **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. +## Modules to Import +```js +import bundle from "@ohos.bundle"; +``` + + ## AbilityInfo Provides the ability information. diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index f5f75e537f719657bed473a63899b15cae850f4b..6bc93f4ba4a926accb35c3f04a4c8c1ea709335a 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -1,20 +1,24 @@ # ExtensionRunningInfo -> ![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. Provides extension running information. +## Modules to Import + +```js +import abilitymanager from '@ohos.application.abilityManager'; +``` ## Usage The extension running information is obtained through an **abilityManager** instance. - - -``` +```js import abilitymanager from '@ohos.application.abilityManager'; abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); @@ -43,15 +47,15 @@ Enumerates extension types. **System capability**: SystemCapability.BundleManager.BundleFramework - | Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| FORM | 0 | Extension information of the form type.< | -| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.< | -| INPUT_METHOD | 2 | Extension information of the input method type.< | -| SERVICE | 3 | Extension information of the service type.< | -| ACCESSIBILITY | 4 | Extension information of the accessibility type.< | -| DATA_SHARE | 5 | Extension information of the data share type.< | -| FILE_SHARE | 6 | Extension information of the file share type.< | -| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.< | -| WALLPAPER | 8 | Extension information of the wallpaper type.< | -| UNSPECIFIED | 9 | Extension information of the unspecified type.< | +| FORM | 0 | Extension information of the form type.< | +| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.< | +| INPUT_METHOD | 2 | Extension information of the input method type.< | +| SERVICE | 3 | Extension information of the service type.< | +| ACCESSIBILITY | 4 | Extension information of the accessibility type.< | +| DATA_SHARE | 5 | Extension information of the data share type.< | +| FILE_SHARE | 6 | Extension information of the file share type.< | +| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.< | +| WALLPAPER | 8 | Extension information of the wallpaper type.< | +| UNSPECIFIED | 9 | Extension information of the unspecified type.< | diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 204144be86343fe9d62876a2da879c3ef35262bb..c0b25d75f2f3ffa14970cd8c752c81c379c8cfe0 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -3,7 +3,7 @@ > **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 provides file storage functions. It provides JS I/O APIs, including basic file management APIs, basic directory management APIs, statistical APIs for obtaining file information, and streaming APIs for reading and writing files. +Provides file storage and management capabilities, including basic file management, file directory management, file information statistics, and stream read and write. ## Modules to Import @@ -14,22 +14,14 @@ import fileio from '@ohos.fileio'; ## Guidelines -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). - -Application sandbox path of a file or directory = Application directory + File name or directory name - -For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the application sandbox path of the file is as follows: - -```js -let path = dir + "/xxx.txt"; -``` - - -The file descriptor is as follows: - - -```js -let fd = fileio.openSync(path); +Before using the APIs provided by this module to perform operations on files or directories, 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; + }) ``` @@ -37,7 +29,7 @@ let fd = fileio.openSync(path); stat(path: string): Promise<Stat> -Asynchronously obtains file information. This API uses a promise to return the result. +Obtains file information. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -45,7 +37,7 @@ Asynchronously obtains file information. This API uses a promise to return the r | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -56,7 +48,7 @@ Asynchronously obtains file information. This API uses a promise to return the r **Example** ```js fileio.stat(path).then(function(stat){ - console.info("getFileInfo successfully:"+ JSON.stringify(stat)); + console.info("Got file info successfully:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("getFileInfo failed with error:"+ err); }); @@ -67,14 +59,14 @@ Asynchronously obtains file information. This API uses a promise to return the r stat(path:string, callback:AsyncCallback<Stat>): void -Asynchronously obtains file information. This API uses a callback to return the result. +Obtains file information. 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 target file. | +| path | string | Yes | Application sandbox path of the file. | | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| **Example** @@ -96,7 +88,7 @@ Synchronously obtains file information. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| **Return value** @@ -115,7 +107,7 @@ Synchronously obtains file information. opendir(path: string): Promise<Dir> -Asynchronously opens a directory. This API uses a promise to return the result. +Opens a file directory. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -127,12 +119,12 @@ Asynchronously opens a directory. This API uses a promise to return the result. **Return value** | Type | Description | | -------------------------- | -------- | - | Promise<[Dir](#dir)> | A **Dir** instance corresponding to the directory.| + | Promise<[Dir](#dir)> | Promise used to return the **Dir** object.| **Example** ```js fileio.opendir(path).then(function(dir){ - console.info("opendir successfully:"+ JSON.stringify(dir)); + console.info("Opened directory successfully:"+ JSON.stringify(dir)); }).catch(function(err){ console.info("opendir failed with error:"+ err); }); @@ -143,7 +135,7 @@ Asynchronously opens a directory. This API uses a promise to return the result. opendir(path: string, callback: AsyncCallback<Dir>): void -Asynchronously opens a directory. This API uses a callback to return the result. +Opens a file directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -195,7 +187,7 @@ Synchronously opens a directory. access(path: string, mode?: number): Promise<void> -Asynchronously checks whether the current process can access a file. This API uses a promise to return the result. +Checks whether the current process can access a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -203,18 +195,18 @@ Asynchronously checks whether the current process can access a file. This API us | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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.| **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.access(path).then(function() { - console.info("access successfully"); + console.info("access succeed"); }).catch(function(err){ console.info("access failed with error:"+ err); }); @@ -225,14 +217,14 @@ Asynchronously checks whether the current process can access a file. This API us access(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously checks whether the current process can access a file. This API uses a callback to return the result. +Checks whether the current process can access 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 target file. | +| 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.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously checked. | @@ -255,7 +247,7 @@ Synchronously checks whether the current process can access the specified file. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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** @@ -272,7 +264,7 @@ Synchronously checks whether the current process can access the specified file. close(fd: number):Promise<void> -Asynchronously closes a file. This API uses a promise to return the result. +Closes a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -284,13 +276,13 @@ Asynchronously closes a file. This API uses a promise to return the result. **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js let fd = fileio.openSync(path); fileio.close(fd).then(function(){ - console.info("close file successfully"); + console.info("close file succeed"); }).catch(function(err){ console.info("close file failed with error:"+ err); }); @@ -301,7 +293,7 @@ Asynchronously closes a file. This API uses a promise to return the result. close(fd: number, callback:AsyncCallback<void>): void -Asynchronously closes a file. This API uses a callback to return the result. +Closes a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -343,19 +335,19 @@ Synchronously closes a file. close(): Promise<void> -Asynchronously closes the stream. This API uses a promise to return the result. +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 used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.close().then(function(){ - console.info("close file stream successfully"); + console.info("close file stream succeed"); }).catch(function(err){ console.info("close file stream failed with error:"+ err); }); @@ -366,7 +358,7 @@ Asynchronously closes the stream. This API uses a promise to return the result. close(callback: AsyncCallback<void>): void -Asynchronously closes the stream. This API uses a callback to return the result. +Closes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -387,7 +379,7 @@ Asynchronously closes the stream. This API uses a callback to return the result. copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> -Asynchronously copies a file. This API uses a promise to return the result. +Copies a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -401,12 +393,12 @@ Asynchronously copies a file. This API uses a promise to return the result. **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.copyFile(src, dest).then(function(){ - console.info("copyFile successfully"); + console.info("copyFile succeed"); }).catch(function(err){ console.info("copyFile failed with error:"+ err); }); @@ -417,7 +409,7 @@ Asynchronously copies a file. This API uses a promise to return the result. copyFile(src: string | number, dest: string | number, mode: number, callback: AsyncCallback<void>): void -Asynchronously copies a file. This API uses a callback to return the result. +Copies a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -462,25 +454,25 @@ Synchronously copies a file. mkdir(path:string, mode?: number): Promise<void> -Asynchronously creates a directory. This API uses a promise to return the result. +Creates a directory. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the directory to create. | +| 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 used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.mkdir(path).then(function() { - console.info("mkdir successfully"); + console.info("mkdir succeed"); }).catch(function (error){ console.info("mkdir failed with error:"+ error); }); @@ -491,21 +483,21 @@ Asynchronously creates a directory. This API uses a promise to return the result mkdir(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously creates a directory. This API uses a callback to return the result. +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 to create. | +| 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.| | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | **Example** ```js fileio.mkdir(path, function(err) { - console.info("mkdir successfully"); + console.info("mkdir succeed"); }); ``` @@ -521,7 +513,7 @@ Synchronously creates a directory. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the directory to create. | +| 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** @@ -534,26 +526,26 @@ Synchronously creates a directory. open(path: string, flags?: number, mode?: number): Promise<number> -Asynchronously opens a file. This API uses a promise to return the result. +Opens a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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.| | 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> | File descriptor of the file opened.| + | 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("open file successfully"); + console.info("Opened file successfully"); }).catch(function(error){ console.info("open file failed with error:"+ err); }); @@ -564,14 +556,14 @@ Asynchronously opens a file. This API uses a promise to return the result. open(path: string, flags: number, mode: number, callback: AsyncCallback<number>): void -Asynchronously opens a file. This API uses a callback to return the result. +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 target file. | +| 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.| | 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. | @@ -595,9 +587,9 @@ Synchronously opens a file. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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.| -| mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| +| 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 | @@ -606,7 +598,15 @@ Synchronously opens a file. **Example** ```js - let fd = fileio.openSync(path); + let fd = fileio.openSync(path, 0o102, 0o640); + ``` + ```js + let fd = fileio.openSync(path, 0o102, 0o666); + fileio.writeSync(fd, 'hello world'); + let fd1 = fileio.openSync(path, 0o2002); + fileio.writeSync(fd1, 'hello world'); + let num = fileio.readSync(fd1, new ArrayBuffer(4096), {position: 0}); + console.info("num == " + num); ``` @@ -618,7 +618,7 @@ read(fd: number, buffer: ArrayBuffer, options?: { position?: number; }): Promise<ReadOut> -Asynchronously reads data from a file. This API uses a promise to return the result. +Reads data from a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -633,14 +633,14 @@ Asynchronously reads data from a file. This API uses a promise to return the res | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | 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){ - console.info("read file data successfully"); + 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); @@ -656,7 +656,7 @@ read(fd: number, buffer: ArrayBuffer, options: { position?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from a file. This API uses a callback to return the result. +Reads data from a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -674,7 +674,7 @@ Asynchronously reads data from a file. This API uses a callback to return the re let buf = new ArrayBuffer(4096); fileio.read(fd, buf, function (err, readOut) { if (readOut) { - console.info("read file data successfully"); + console.info("Read file data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -717,7 +717,7 @@ Synchronously reads data from a file. rmdir(path: string): Promise<void> -Asynchronously deletes a directory. This API uses a promise to return the result. +Deletes a directory. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -729,12 +729,12 @@ Asynchronously deletes a directory. This API uses a promise to return the result **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.rmdir(path).then(function() { - console.info("rmdir successfully"); + console.info("rmdir succeed"); }).catch(function(err){ console.info("rmdir failed with error:"+ err); }); @@ -745,7 +745,7 @@ Asynchronously deletes a directory. This API uses a promise to return the result rmdir(path: string, callback:AsyncCallback<void>): void -Asynchronously deletes a directory. This API uses a callback to return the result. +Deletes a directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -759,7 +759,7 @@ Asynchronously deletes a directory. This API uses a callback to return the resul ```js fileio.rmdir(path, function(err){ // Do something. - console.info("rmdir successfully"); + console.info("rmdir succeed"); }); ``` @@ -787,7 +787,7 @@ Synchronously deletes a directory. unlink(path:string): Promise<void> -Asynchronously deletes a file. This API uses a promise to return the result. +Deletes a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -799,12 +799,12 @@ Asynchronously deletes a file. This API uses a promise to return the result. **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.unlink(path).then(function(){ - console.info("remove file successfully"); + console.info("Removed file successfully"); }).catch(function(error){ console.info("remove file failed with error:"+ error); }); @@ -815,20 +815,20 @@ Asynchronously deletes a file. This API uses a promise to return the result. unlink(path:string, callback:AsyncCallback<void>): void -Asynchronously deletes a file. This API uses a callback to return the result. +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 to delete.| +| 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("remove file successfully"); + console.info("Removed file successfully"); }); ``` @@ -844,7 +844,7 @@ Synchronously deletes a file. **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.| **Example** ```js @@ -861,7 +861,7 @@ write(fd: number, buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Asynchronously writes data into a file. This API uses a promise to return the result. +Writes data into a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -875,13 +875,13 @@ Asynchronously writes data into a file. This API uses a promise to return the re **Return value** | Type | Description | | --------------------- | -------- | - | Promise<number> | Length of the data written in the file.| + | Promise<number> | Promise used to return the length of the data written.| **Example** ```js let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ - console.info("write data to file successfully and size is:"+ number); + console.info("Wrote data to file successfully and size is:"+ number); }).catch(function(err){ console.info("write data to file failed with error:"+ err); }); @@ -897,7 +897,7 @@ write(fd: number, buffer: ArrayBuffer | string, options: { encoding?: string; }, callback: AsyncCallback<number>): void -Asynchronously writes data into a file. This API uses a callback to return the result. +Writes data into a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -914,7 +914,7 @@ Asynchronously writes data into a file. This API uses a callback to return the r let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { - console.info("write data to file successfully and size is:"+ bytesWritten); + console.info("Wrote data to file successfully and size is:"+ bytesWritten); } }); ``` @@ -956,25 +956,25 @@ Synchronously writes data into a file. hash(path: string, algorithm: string): Promise<string> -Asynchronously calculates the hash value of a file. This API uses a promise to return the result. +Calculates the hash value of a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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 of the file. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + | 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("calculate file hash successfully:"+ str); + console.info("Calculated file hash successfully:"+ str); }).catch(function(error){ console.info("calculate file hash failed with error:"+ err); }); @@ -985,22 +985,22 @@ Asynchronously calculates the hash value of a file. This API uses a promise to r hash(path: string, algorithm: string, callback: AsyncCallback<string>): void -Asynchronously calculates the hash value of a file. This API uses a callback to return the result. +Calculates the hash value of 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 target file. | +| 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.| -| callback | AsyncCallback<string> | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| +| 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) { if (hashStr) { - console.info("calculate file hash successfully:"+ hashStr); + console.info("Calculated file hash successfully:"+ hashStr); } }); ``` @@ -1010,25 +1010,25 @@ Asynchronously calculates the hash value of a file. This API uses a callback to chmod(path: string, mode: number):Promise<void> -Asynchronously changes the file permissions based on its path. This API uses a promise to return the result. +Changes file permissions. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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 used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.chmod(path, mode).then(function() { - console.info("chmod successfully"); + console.info("chmod succeed"); }).catch(function(err){ console.info("chmod failed with error:"+ err); }); @@ -1039,14 +1039,14 @@ Asynchronously changes the file permissions based on its path. This API uses a p chmod(path: string, mode: number, callback: AsyncCallback<void>): void -Asynchronously changes the file permissions based on its path. This API uses a callback to return the result. +Changes file permissions. 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 target file. | +| 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.| | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | @@ -1062,14 +1062,14 @@ Asynchronously changes the file permissions based on its path. This API uses a c chmodSync(path: string, mode: number): void -Synchronously changes the file permissions based on its path. +Synchronously changes file permissions. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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** @@ -1082,7 +1082,7 @@ Synchronously changes the file permissions based on its path. fstat(fd: number): Promise<Stat> -Asynchronously obtains file information based on the file descriptor. This API uses a promise to return the result. +Obtains file information based on the file descriptor. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1094,12 +1094,12 @@ Asynchronously obtains file information based on the file descriptor. This API u **Return value** | Type | Description | | ---------------------------- | ---------- | - | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| + | Promise<[Stat](#stat)> | Promise used to return the file information.| **Example** ```js fileio.fstat(fd).then(function(stat){ - console.info("fstat successfully:"+ JSON.stringify(stat)); + console.info("fstat succeed:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("fstat failed with error:"+ err); }); @@ -1110,7 +1110,7 @@ Asynchronously obtains file information based on the file descriptor. This API u fstat(fd: number, callback: AsyncCallback<Stat>): void -Asynchronously obtains file information based on the file descriptor. This API uses a callback to return the result. +Obtains file information based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1158,7 +1158,7 @@ Synchronously obtains file information based on the file descriptor. ftruncate(fd: number, len?: number): Promise<void> -Asynchronously truncates a file based on the file descriptor. This API uses a promise to return the result. +Truncates a file based on the file descriptor. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1166,18 +1166,18 @@ Asynchronously truncates a file based on the file descriptor. This API uses a pr | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | - | len | number | Yes | File length, in bytes, after truncation.| + | len | number | No | File length, in bytes, after truncation.| **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js let fd = fileio.openSync(path); fileio.ftruncate(fd, 5).then(function(err) { - console.info("File truncated successfully."); + console.info("truncate file succeed"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1188,7 +1188,7 @@ Asynchronously truncates a file based on the file descriptor. This API uses a pr ftruncate(fd: number, len: number, callback:AsyncCallback<void>): void -Asynchronously truncates a file based on the file descriptor. This API uses a callback to return the result. +Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1197,7 +1197,7 @@ Asynchronously truncates a file based on the file descriptor. This API uses a ca | -------- | ------------------------- | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | | len | number | Yes | File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | + | callback | AsyncCallback<void> | Yes | Callback which returns no value. | **Example** ```js @@ -1231,7 +1231,7 @@ Synchronously truncates a file based on the file descriptor. truncate(path: string, len?: number): Promise<void> -Asynchronously truncates a file based on its path. This API uses a promise to return the result. +Truncates a file based on the file path. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1239,17 +1239,17 @@ Asynchronously truncates a file based on its path. This API uses a promise to re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | | path | string | Yes | Application sandbox path of the file to truncate. | -| len | number | Yes | File length, in bytes, after truncation.| +| len | number | No | File length, in bytes, after truncation.| **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.truncate(path, len).then(function(){ - console.info("File truncated successfully."); + console.info("Truncated file successfully"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); }); @@ -1260,7 +1260,7 @@ Asynchronously truncates a file based on its path. This API uses a promise to re truncate(path: string, len: number, callback:AsyncCallback<void>): void -Asynchronously truncates a file based on its path. This API uses a callback to return the result. +Truncates a file based on the file path. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1269,7 +1269,7 @@ Asynchronously truncates a file based on its path. This API uses a callback to r | -------- | ------------------------- | ---- | -------------------------------- | | 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 invoked when the file is truncated asynchronously. | +| callback | AsyncCallback<void> | Yes | Callback which returns no value. | **Example** ```js @@ -1290,7 +1290,7 @@ Synchronously truncates a file based on the file path. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| path | string | Yes | Application sandbox path of the file to be truncate. | +| path | string | Yes | Application sandbox path of the file to truncate. | | len | number | No | File length, in bytes, after truncation.| **Example** @@ -1307,7 +1307,7 @@ readText(filePath: string, options?: { encoding?: string; }): Promise<string> -Asynchronously reads the text of a file. This API uses a promise to return the result. +Reads the text content of a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1320,12 +1320,12 @@ Asynchronously reads the text of a file. This API uses a promise to return the r **Return value** | Type | Description | | --------------------- | ---------- | - | Promise<string> | Promise used to return the content of the file read.| + | Promise<string> | Promise used to return the content read.| **Example** ```js fileio.readText(path).then(function(str) { - console.info("readText successfully:"+ str); + console.info("Read text successfully:"+ str); }).catch(function(err){ console.info("readText failed with error:"+ err); }); @@ -1340,7 +1340,7 @@ readText(filePath: string, options: { encoding?: string; }, callback: AsyncCallback<string>): void -Asynchronously reads the text of a file. This API uses a callback to return the result. +Reads the text content of a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1348,8 +1348,8 @@ Asynchronously reads the text of a file. This API uses a callback to return the | 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.| -| callback | AsyncCallback<string> | Yes | Callback invoked when the file is read asynchronously. | +| 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.| +| callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** ```js @@ -1392,7 +1392,7 @@ Synchronously reads the text of a file. lstat(path: string): Promise<Stat> -Asynchronously obtains link information. This API uses a promise to return the result. +Obtains link information. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1404,12 +1404,12 @@ Asynchronously obtains link information. This API uses a promise to return the r **Return value** | Type | Description | | ---------------------------- | ---------- | - | Promise<[Stat](#stat)> | Promise used to return the link information obtained.| + | 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("Link status obtained:"+ number); + console.info("Got link info successfully:"+ number); }).catch(function(err){ console.info("Failed to obtain the link status. Error:"+ err); }); @@ -1420,7 +1420,7 @@ Asynchronously obtains link information. This API uses a promise to return the r lstat(path:string, callback:AsyncCallback<Stat>): void -Asynchronously obtains link information. This API uses a callback to return the result. +Obtains link information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1428,7 +1428,7 @@ Asynchronously obtains link information. This API uses a callback to return the | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | -------------------------------------- | | path | string | Yes | Application sandbox path of the target file, pointing to the link.| -| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the link information obtained. | +| callback | AsyncCallback<[Stat](#stat)> | Yes | Callback used to return the link information obtained. | **Example** ```js @@ -1449,7 +1449,7 @@ Synchronously obtains the link information. **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 | @@ -1470,7 +1470,7 @@ read(buffer: ArrayBuffer, options?: { length?: number; }): Promise<ReadOut> -Asynchronously reads data from a file. This API uses a promise to return the result. +Reads data from a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1483,12 +1483,12 @@ Asynchronously reads data from a file. This API uses a promise to return the res **Return value** | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | 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.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); @@ -1504,7 +1504,7 @@ read(buffer: ArrayBuffer, options: { length?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from a file. This API uses a callback to return the result. +Reads data from a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1520,7 +1520,7 @@ Asynchronously reads data from a file. This API uses a callback to return the re let buf = new ArrayBuffer(4096); fileio.read(buf, function (err, readOut) { if (readOut) { - console.info("read file data successfully"); + console.info("Read file data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -1531,7 +1531,7 @@ Asynchronously reads data from a file. This API uses a callback to return the re rename(oldPath: string, newPath: string): Promise<void> -Asynchronously renames a file. This API uses a promise to return the result. +Renames a file. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1544,12 +1544,12 @@ Asynchronously renames a file. This API uses a promise to return the result. **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.rename(oldPath, newPath).then(function() { - console.info("rename successfully"); + console.info("rename succeed"); }).catch(function(err){ console.info("rename failed with error:"+ err); }); @@ -1560,7 +1560,7 @@ Asynchronously renames a file. This API uses a promise to return the result. rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): void -Asynchronously renames a file. This API uses a callback to return the result. +Renames a file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1568,7 +1568,7 @@ Asynchronously renames a file. This API uses a callback to return the result. | 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. | +| newPath | String | Yes | Application sandbox path of the file renamed. | | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed. | **Example** @@ -1602,19 +1602,19 @@ Synchronously renames a file. fsync(fd: number): Promise<void> -Asynchronously synchronizes a file. This API uses a promise to return the result. +Flushes data of a file to disk. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js @@ -1630,14 +1630,14 @@ Asynchronously synchronizes a file. This API uses a promise to return the result fsync(fd: number, callback: AsyncCallback<void>): void -Asynchronously synchronizes a file. This API uses a callback to return the result. +Flushes data of a file to disk. 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 synchronize. | + | 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** @@ -1652,14 +1652,14 @@ Asynchronously synchronizes a file. This API uses a callback to return the resul fsyncSync(fd: number): void -Synchronizes a file in synchronous mode. +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 synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Example** ```js @@ -1671,24 +1671,24 @@ Synchronizes a file in synchronous mode. fdatasync(fd: number): Promise<void> -Asynchronously synchronizes data in a file. This API uses a promise to return the result. +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. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.fdatasync(fd).then(function(err) { - console.info("sync data successfully"); + console.info("sync data succeed"); }).catch(function(err){ console.info("sync data failed with error:"+ err); }); @@ -1699,7 +1699,7 @@ Asynchronously synchronizes data in a file. This API uses a promise to return th fdatasync(fd: number, callback:AsyncCallback<void>): void -Asynchronously synchronizes data in a file. This API uses a callback to return the result. +Flushes data of a file to disk. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1728,7 +1728,7 @@ Synchronizes data in a file in synchronous mode. **Parameters** | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | - | fd | number | Yes | File descriptor of the file to synchronize.| + | fd | number | Yes | File descriptor of the file to flush.| **Example** ```js @@ -1740,25 +1740,25 @@ Synchronizes data in a file in synchronous mode. symlink(target: string, srcPath: string): Promise<void> -Asynchronously creates a symbolic link based on a path. This API uses a promise to return the result. +Creates a symbolic link based on a path. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | -| target | string | Yes | Application sandbox path of the symbolic link. | -| srcPath | string | Yes | Application sandbox path of the referenced file or directory contained in the symbolic link.| +| 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 used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.symlink(target, srcPath).then(function() { - console.info("symlink successfully"); + console.info("symlink succeed"); }).catch(function(err){ console.info("symlink failed with error:"+ err); }); @@ -1769,15 +1769,15 @@ Asynchronously creates a symbolic link based on a path. This API uses a promise symlink(target: string, srcPath: string, callback: AsyncCallback<void>): void -Asynchronously creates a symbolic link based on a path. This API uses a callback to return the result. +Creates a symbolic link based on a 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 symbolic link. | -| srcPath | string | Yes | Application sandbox path of the referenced file or directory contained in the symbolic link. | +| target | string | Yes | Application sandbox path of the target file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link file. | | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| **Example** @@ -1799,8 +1799,8 @@ Synchronously creates a symbolic link based on a specified path. **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ---------------------------- | -| target | string | Yes | Application sandbox path of the symbolic link. | -| srcPath | string | Yes | Application sandbox path the referenced file or directory contained in the symbolic link.| +| target | string | Yes | Application sandbox path of the target file. | +| srcPath | string | Yes | Application sandbox path of the symbolic link file.| **Example** ```js @@ -1812,27 +1812,27 @@ Synchronously creates a symbolic link based on a specified path. chown(path: string, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on its path. This API uses a promise to return the result. +Changes the file owner based on the file path. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New user ID (UID). | | gid | number | Yes | New group ID (GID). | **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js let stat = fileio.statSync(path); fileio.chown(path, stat.uid, stat.gid).then(function(){ - console.info("chown successfully"); + console.info("chown succeed"); }).catch(function(err){ console.info("chown failed with error:"+ err); }); @@ -1843,14 +1843,14 @@ Asynchronously changes the file owner based on its path. This API uses a promise chown(path: string, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on its path. This API uses a callback to return the result. +Changes the file owner 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 target file. | +| path | string | Yes | Application sandbox path of the file. | | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| @@ -1875,7 +1875,7 @@ Synchronously changes the file owner based on its path. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | @@ -1890,7 +1890,7 @@ Synchronously changes the file owner based on its path. mkdtemp(prefix: string): Promise<string> -Asynchronously creates a temporary directory. This API uses a promise to return the result. +Creates a temporary directory. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1902,12 +1902,12 @@ Asynchronously creates a temporary directory. This API uses a promise to return **Return value** | Name | Description | | --------------------- | ---------- | - | Promise<string> | Unique path generated.| + | Promise<string> | Promise used to return the directory generated.| **Example** ```js fileio.mkdtemp(path + "XXXX").then(function(path){ - console.info("mkdtemp successfully:"+ path); + console.info("mkdtemp succeed:"+ path); }).catch(function(err){ console.info("mkdtemp failed with error:"+ err); }); @@ -1918,7 +1918,7 @@ Asynchronously creates a temporary directory. This API uses a promise to return mkdtemp(prefix: string, callback: AsyncCallback<string>): void -Asynchronously creates a temporary directory. This API uses a callback to return the result. +Creates a temporary directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1964,7 +1964,7 @@ Synchronously creates a temporary directory. fchmod(fd: number, mode: number): Promise<void> -Asynchronously changes the file permissions based on the file descriptor. This API uses a promise to return the result. +Changes file permissions based on the file descriptor. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -1977,12 +1977,12 @@ Asynchronously changes the file permissions based on the file descriptor. This A **Return value** | Name | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js fileio.fchmod(fd, mode).then(function() { - console.info("chmod successfully"); + console.info("chmod succeed"); }).catch(function(err){ console.info("chmod failed with error:"+ err); }); @@ -1993,7 +1993,7 @@ Asynchronously changes the file permissions based on the file descriptor. This A fchmod(fd: number, mode: number, callback: AsyncCallback<void>): void -Asynchronously changes the file permissions based on the file descriptor. This API uses a callback to return the result. +Changes file permissions based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2036,14 +2036,14 @@ Synchronously changes the file permissions based on the file descriptor. createStream(path: string, mode: string): Promise<Stream> -Asynchronously opens a stream based on the file path. This API uses a promise to return the result. +Opens a file stream based on the file path. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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** @@ -2054,7 +2054,7 @@ Asynchronously opens a stream based on the file path. This API uses a promise to **Example** ```js fileio.createStream(path, "r+").then(function(stream){ - console.info("createStream successfully"); + console.info("createStream succeed"); }).catch(function(err){ console.info("createStream failed with error:"+ err); }); @@ -2065,14 +2065,14 @@ Asynchronously opens a stream based on the file path. This API uses a promise to createStream(path: string, mode: string, callback: AsyncCallback<Stream>): void -Asynchronously opens a stream based on the file path. This API uses a callback to return the result. +Opens a 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 target file. | +| 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. | @@ -2095,7 +2095,7 @@ Synchronously opens a stream based on the file path. **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| path | string | Yes | Application sandbox path of the target file. | +| 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** @@ -2113,7 +2113,7 @@ Synchronously opens a stream based on the file path. fdopenStream(fd: number, mode: string): Promise<Stream> -Asynchronously opens a stream based on the file descriptor. This API uses a promise to return the result. +Opens a file stream based on the file descriptor. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2131,7 +2131,7 @@ Asynchronously opens a stream based on the file descriptor. This API uses a prom **Example** ```js fileio.fdopenStream(fd, mode).then(function(stream){ - console.info("openStream successfully"); + console.info("openStream succeed"); }).catch(function(err){ console.info("openStream failed with error:"+ err); }); @@ -2142,7 +2142,7 @@ Asynchronously opens a stream based on the file descriptor. This API uses a prom fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): void -Asynchronously opens a stream based on the file descriptor. This API uses a callback to return the result. +Opens a file stream based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2190,7 +2190,7 @@ Synchronously opens a stream based on the file descriptor. fchown(fd: number, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on the file descriptor. This API uses a promise to return the result. +Changes the file owner based on the file descriptor. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2204,13 +2204,13 @@ Asynchronously changes the file owner based on the file descriptor. This API use **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js let stat = fileio.statSync(path); fileio.fchown(fd, stat.uid, stat.gid).then(function() { - console.info("chown successfully"); + console.info("chown succeed"); }).catch(function(err){ console.info("chown failed with error:"+ err); }); @@ -2221,7 +2221,7 @@ Asynchronously changes the file owner based on the file descriptor. This API use fchown(fd: number, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on the file descriptor. This API uses a callback to return the result. +Changes the file owner based on the file descriptor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2268,27 +2268,27 @@ Synchronously changes the file owner based on the file descriptor. lchown(path: string, uid: number, gid: number): Promise<void> -Asynchronously changes the file owner based on the file path, changes the owner of the symbolic link (not the referenced file), and returns the result in a promise. +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. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | **Return value** | Type | Description | | ------------------- | ---------------------------- | - | Promise<void> | Promise used to return the result. An empty value is returned.| + | Promise<void> | Promise which returns no value.| **Example** ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid).then(function() { - console.info("chown successfully"); + console.info("chown succeed"); }).catch(function(err){ console.info("chown failed with error:"+ err); }); @@ -2299,14 +2299,14 @@ Asynchronously changes the file owner based on the file path, changes the owner lchown(path: string, uid: number, gid: number, callback: AsyncCallback<void>): void -Asynchronously changes the file owner based on the file path, changes the owner of the symbolic link (not the referenced file), and returns the result in a callback. +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 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 target file. | +| path | string | Yes | Application sandbox path of the file. | | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| @@ -2331,7 +2331,7 @@ Synchronously changes the file owner based on the file path and changes the owne **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------- | -| path | string | Yes | Application sandbox path of the target file.| +| path | string | Yes | Application sandbox path of the file.| | uid | number | Yes | New UID. | | gid | number | Yes | New GID. | @@ -2346,21 +2346,21 @@ Synchronously changes the file owner based on the file path and changes the owne createWatcher(filename: string, events: number, callback: AsyncCallback<number>): Watcher -Asynchronously listens for the changes of a file or directory. This API uses a callback to return the result. +Listens for file or directory changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| filename | string | Yes | Application sandbox path of the target file. | +| filename | string | Yes | Application sandbox path of the file. | | events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | **Return value** | Name | Description | | -------------------- | ---------- | - | [Watcher](#watcher7) | Instance for listening for a file change event.| + | [Watcher](#watcher7) | Promise used to return the **Watcher** instance.| **Example** ```js @@ -2549,7 +2549,7 @@ Listens for the changes of a file. You can call the **Watcher.stop()** method sy stop(): Promise<void> -Asynchronously stops **watcher**. This API uses a promise to return the result. +Stops the **watcher** instance. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2563,7 +2563,7 @@ Asynchronously stops **watcher**. This API uses a promise to return the result. stop(callback: AsyncCallback<void>): void -Asynchronously stops **watcher**. This API uses a callback to return the result. +Stops the **watcher** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2583,14 +2583,14 @@ Asynchronously stops **watcher**. This API uses a callback to return the result. ## Stream7+ -File stream. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. +Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. ### close7+ close(): Promise<void> -Asynchronously closes the stream. This API uses a promise to return the result. +Closes the stream. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2603,7 +2603,7 @@ Asynchronously closes the stream. This API uses a promise to return the result. ```js let ss= fileio.createStreamSync(path); ss.close().then(function(){ - console.info("close fileStream successfully"); + console.info("Closed fileStream successfully"); }).catch(function(err){ console.info("close fileStream failed with error:"+ err); }); @@ -2614,7 +2614,7 @@ Asynchronously closes the stream. This API uses a promise to return the result. close(callback: AsyncCallback<void>): void -Asynchronously closes the stream. This API uses a callback to return the result. +Closes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2627,7 +2627,7 @@ Asynchronously closes the stream. This API uses a callback to return the result. ```js let ss= fileio.createStreamSync(path); ss.close(function (err) { - // do something + // Do something }); ``` @@ -2651,7 +2651,7 @@ Synchronously closes the stream. flush(): Promise<void> -Asynchronously flushes the stream. This API uses a promise to return the result. +Flushes the stream. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2664,7 +2664,7 @@ Asynchronously flushes the stream. This API uses a promise to return the result. ```js let ss= fileio.createStreamSync(path); ss.flush().then(function (){ - console.info("flush successfully"); + console.info("Flushed stream successfully"); }).catch(function(err){ console.info("flush failed with error:"+ err); }); @@ -2675,7 +2675,7 @@ Asynchronously flushes the stream. This API uses a promise to return the result. flush(callback: AsyncCallback<void>): void -Asynchronously flushes the stream. This API uses a callback to return the result. +Flushes the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2688,7 +2688,7 @@ Asynchronously flushes the stream. This API uses a callback to return the result ```js let ss= fileio.createStreamSync(path); ss.flush(function (err) { - // do something + // Do something }); ``` @@ -2717,7 +2717,7 @@ write(buffer: ArrayBuffer | string, options?: { encoding?: string; }): Promise<number> -Asynchronously writes data into the stream. This API uses a promise to return the result. +Writes data into the stream. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2730,13 +2730,13 @@ Asynchronously writes data into the stream. This API uses a promise to return th **Return value** | Type | Description | | --------------------- | -------- | - | Promise<number> | Length of the data written in the file.| + | Promise<number> | Promise used to return the length of the data written.| **Example** ```js let ss= fileio.createStreamSync(fpath, "r+"); ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ - console.info("write successfully and size is:"+ number); + console.info("Wrote data successfully and size is:"+ number); }).catch(function(err){ console.info("write failed with error:"+ err); }); @@ -2752,7 +2752,7 @@ write(buffer: ArrayBuffer | string, options: { encoding?: string; }, callback: AsyncCallback<number>): void -Asynchronously writes data into the stream. This API uses a callback to return the result. +Writes data into the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2768,8 +2768,8 @@ Asynchronously writes data into the stream. This API uses a callback to return t let ss= fileio.createStreamSync(fpath, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { - // do something - console.info("write successfully and size is:"+ bytesWritten); + // Do something + console.info("Wrote data successfully and size is:"+ bytesWritten); } }); ``` @@ -2814,7 +2814,7 @@ read(buffer: ArrayBuffer, options?: { length?: number; }): Promise<ReadOut> -Asynchronously reads data from the stream. This API uses a promise to return the result. +Reads data from the stream. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2827,13 +2827,13 @@ Asynchronously reads data from the stream. This API uses a promise to return the **Return value** | Type | Description | | ---------------------------------- | ------ | - | Promise<[ReadOut](#readout)> | Data read.| + | 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){ - console.info("read data successfully"); + 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); @@ -2849,7 +2849,7 @@ read(buffer: ArrayBuffer, options: { length?: number; }, callback: AsyncCallback<ReadOut>): void -Asynchronously reads data from the stream. This API uses a callback to return the result. +Reads data from the stream. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2865,7 +2865,7 @@ Asynchronously reads data from the stream. This API uses a callback to return th let ss = fileio.createStreamSync(fpath, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (readOut) { - console.info("read data successfully"); + console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); } }); @@ -2913,20 +2913,20 @@ Manages directories. Before calling a method of the **Dir** class, use the [open read(): Promise<Dirent> -Asynchronously reads the next directory entry. This API uses a promise to return the result. +Reads the next directory entry. This API uses a promise to return the result asynchronously. **System capability**: SystemCapability.FileManagement.File.FileIO **Return value** | Type | Description | | -------------------------------- | ------------- | - | Promise<[Dirent](#dirent)> | Directory entry that is read asynchronously.| + | 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 successfully:"+JSON.stringify(dirent)); + console.log("read succeed:"+JSON.stringify(dirent)); }).catch(function(err){ console.info("read failed with error:"+ err); }); @@ -2937,7 +2937,7 @@ Asynchronously reads the next directory entry. This API uses a promise to return read(callback: AsyncCallback<Dirent>): void -Asynchronously reads the next directory entry. This API uses a callback to return the result. +Reads the next directory entry. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -2951,8 +2951,8 @@ Asynchronously reads the next directory entry. This API uses a callback to retur let dir = fileio.opendirSync(path); dir.read(function (err, dirent) { if (dirent) { - // do something - console.log("read successfully:"+JSON.stringify(dirent)); + // Do something + console.log("read succeed:"+JSON.stringify(dirent)); } }); ``` @@ -2978,6 +2978,40 @@ Synchronously reads the next directory entry. ``` +### close + +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. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Example** + ```js + let dir = fileio.opendirSync(path); + dir.close().then(function(err){ + console.info("close dir successfully"); + }); + ``` + + + ### close + +close(callback: AsyncCallback<void>): void + +Closes a directory. This API uses an asynchronous callback 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(function(err){ + console.info("close dir successfully"); + }); + ``` + + ### closeSync closeSync(): void @@ -3010,7 +3044,7 @@ Provides information about files and directories. Before calling a method of the isBlockDevice(): boolean -Checks whether the current directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. +Checks whether this directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. **System capability**: SystemCapability.FileManagement.File.FileIO @@ -3070,7 +3104,7 @@ Checks whether a directory entry is a directory. isFIFO(): boolean -Checks whether the current directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. +Checks whether this directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. **System capability**: SystemCapability.FileManagement.File.FileIO diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index 88f58da288e50a05731fda26de56581fa5a46e0e..a1422c1bff0f93f58e8ce5ddac6c177eec96e16a 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -63,13 +63,19 @@ Obtains information about the root album or directory in asynchronous mode. This - Example ```js - filemanager.getRoot((err, fileInfo) => { + let option = { + "dev":{ + name:"", + } + }; + filemanager.getRoot(option,(err, fileInfo)=>{ if(Array.isArray(fileInfo)) { for (var i = 0; i < fileInfo.length; i++) { console.log("file:"+JSON.stringify(fileInfo)); } - } + } }); + ``` ## filemanager.listFile @@ -83,8 +89,8 @@ Obtains information about the second-level album or files in asynchronous mode. - Parameters | Name| Type| Mandatory| Description| | --- | --- | --- | -- | - | path | promise| Yes| URI of the directory to query.| - | type | promise| Yes| Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| + | 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 @@ -105,7 +111,7 @@ Obtains information about the second-level album or files in asynchronous mode. ```js // Obtain all files in the directory. // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri + let media_path = file.path filemanager.listFile(media_path, "file") .then((fileInfo) => { if(Array.isArray(fileInfo)) { @@ -114,10 +120,13 @@ Obtains information about the second-level album or files in asynchronous mode. } } }).catch((err) => { - console.log(err) - }); + + console.log(err) + }); ``` + + ## filemanager.listFile listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void @@ -130,8 +139,8 @@ Obtains information about the second-level album or files in asynchronous mode. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | - | path | promise | Yes | URI of the directory to query. | - | type | promise | Yes | Type of the files to query. The file type can be **file**, **image**, **audio**, or **video**.| + | 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 @@ -145,14 +154,30 @@ Obtains information about the second-level album or files in asynchronous mode. - Example ```js - // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri - filemanager.listFile(media_path, "file", (err, fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + // 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) }); ``` @@ -167,8 +192,8 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi - Parameters | Name| Type| Mandatory| Description| | --- | --- | --- | -- | - | filename | promise| Yes| Name of the file to create.| - | path | promise| Yes| URI of the file to create.| + | 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 @@ -211,8 +236,8 @@ Creates a file in the specified path in asynchronous mode. This API uses a callb | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------- | - | filename | promise | Yes | Name of the file to create. | - | path | promise | Yes | URI of the file to create. | + | 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. | @@ -230,7 +255,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a callb ```js // Create a file. // Call listFile() and getRoot() to obtain the file URI. - let media_path = file.uri + let media_path = file.path // File to be saved. let name = "xxx.jpg" filemanager.createFile(media_path, name, (err, uri) => { @@ -248,9 +273,9 @@ Defines the file information returned by **getRoot()** or **listFile()**. | Name| Type| Readable| Writable| Description| | --- | -- | -- | -- | -- | -| name | promise| Yes| No| File name.| -| path | promise| Yes| No| URI of the file.| -| type | promise| Yes| No| File type.| +| name | string | Yes| No| File name.| +| path | string | Yes| No| URI of the file.| +| type | string | Yes| No| File type.| | size | number | Yes| No| File size.| | addedTime | number | Yes| No| Time when the file was scanned to the database.| | modifiedTime | number | Yes| No| Time when the file was modified.| @@ -265,4 +290,4 @@ Defines the device type. | Name| Type | Readable| Writable| Description | | ------ | ------ | ---- | ---- | -------- | -| name | promise| Yes | Yes | Device name.| +| name | string | Yes | Yes | Device name.| diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md index c2a5e3f458fbefc83107345156f289a81b529fd2..0ea801a586cc37003d6a7aeb42679eac78e20d2c 100644 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -1,10 +1,17 @@ # FormExtensionContext -> ![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. Implements the context that provides the capabilities and APIs of **FormExtension**. This class is inherited from **ExtensionContext**. +## Modules to Import + +```js +import FormExtension from "@ohos.application.FormExtension"; +``` + ## FormExtensionContext.updateForm updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md index a9056381ea461dc26de4745e49a1664a333f3646..c31e0da32571c4f0a37b3926926355e81d92011a 100644 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -1,6 +1,7 @@ # FormHost -> **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. Provides APIs related to the widget host. @@ -591,7 +592,7 @@ SystemCapability.Ability.Form ## getAllFormsInfo -getAllFormsInfo(callback: AsyncCallback<Array<FormInfo>>): void; +getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void; Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. @@ -619,7 +620,7 @@ SystemCapability.Ability.Form ## getAllFormsInfo -getAllFormsInfo(): Promise<Array<FormInfo>>; +getAllFormsInfo(): Promise<Array<formInfo.FormInfo>>; Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. @@ -645,7 +646,7 @@ SystemCapability.Ability.Form ## getFormsInfo -getFormsInfo(bundleName: string, callback: AsyncCallback<Array<FormInfo>>): void; +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. @@ -674,7 +675,7 @@ SystemCapability.Ability.Form ## getFormsInfo -getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<FormInfo>>): void; +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. @@ -704,7 +705,7 @@ SystemCapability.Ability.Form ## getFormsInfo -getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<FormInfo>>; +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>>; Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. @@ -767,7 +768,7 @@ SystemCapability.Ability.Form ## deleteInvalidForms -function deleteInvalidForms(formIds: Array<string>): Promise<number>; +deleteInvalidForms(formIds: Array<string>): Promise<number>; Deletes invalid widgets from the list. This API uses a promise to return the result. @@ -800,7 +801,7 @@ SystemCapability.Ability.Form ## acquireFormState -acquireFormState(want: Want, callback: AsyncCallback<FormStateInfo>): void; +acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void; Obtains the widget state. This API uses an asynchronous callback to return the result. @@ -819,9 +820,14 @@ SystemCapability.Ability.Form ```js var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } }; formHost.acquireFormState(want, (error, data) => { if (error.code) { @@ -834,7 +840,7 @@ SystemCapability.Ability.Form ## acquireFormState -function acquireFormState(want: Want): Promise<FormStateInfo>; +acquireFormState(want: Want): Promise<formInfo.FormStateInfo>; Obtains the widget state. This API uses a promise to return the result. @@ -858,9 +864,14 @@ SystemCapability.Ability.Form ```js var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } }; formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index e48d4ada58ae469c73c71b6f90ae682610544706..6e4350c654ac112ecbdd2e8c45e5601a8260b056 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -1,6 +1,7 @@ # FormProvider -> **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. Provides APIs related to the widget provider. @@ -27,11 +28,11 @@ SystemCapability.Ability.Form **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | - | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | ID of a widget. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -56,16 +57,16 @@ SystemCapability.Ability.Form **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | - | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | ID of a widget. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | **Return value** - | Type | Description | - | ------------- | ---------------------------------- | - | Promise\ |Promise used to return the result. | +| Type | Description | +| ------------- | ---------------------------------- | +| Promise\ |Promise used to return the result. | **Example** @@ -80,7 +81,7 @@ SystemCapability.Ability.Form ## updateForm -updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<void>): void; Updates a widget. This API uses an asynchronous callback to return the result. @@ -90,11 +91,11 @@ SystemCapability.Ability.Form **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | - | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -111,7 +112,7 @@ SystemCapability.Ability.Form ## updateForm -updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void>; Updates a widget. This API uses a promise to return the result. @@ -121,10 +122,10 @@ SystemCapability.Ability.Form **Parameters** - | Name| Type | Mandatory| Description | - | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | - | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index b5bc89099f57b1f56b65859e6d4b0422d483df23..7d7ec04c6ca3bcbaf5cb8d1f314d256f15efbef8 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -702,7 +702,7 @@ Defines the measurement unit information. ### unitConvert8+ -unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string +static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string Converts one measurement unit into another and formats the unit based on the specified locale and style. @@ -825,7 +825,7 @@ Obtains the index of a text object. ### isDigit8+ -isDigit(char: string): boolean +static isDigit(char: string): boolean Checks whether the input character string is composed of digits. @@ -849,7 +849,7 @@ Checks whether the input character string is composed of digits. ### isSpaceChar8+ -isSpaceChar(char: string): boolean +static isSpaceChar(char: string): boolean Checks whether the input character is a space. @@ -873,7 +873,7 @@ Checks whether the input character is a space. ### isWhitespace8+ -isWhitespace(char: string): boolean +static isWhitespace(char: string): boolean Checks whether the input character is a white space. @@ -897,7 +897,7 @@ Checks whether the input character is a white space. ### isRTL8+ -isRTL(char: string): boolean +static isRTL(char: string): boolean Checks whether the input character is of the right to left (RTL) language. @@ -921,7 +921,7 @@ Checks whether the input character is of the right to left (RTL) language. ### isIdeograph8+ -isIdeograph(char: string): boolean +static isIdeograph(char: string): boolean Checks whether the input character is an ideographic character. @@ -945,7 +945,7 @@ Checks whether the input character is an ideographic character. ### isLetter8+ -isLetter(char: string): boolean +static isLetter(char: string): boolean Checks whether the input character is a letter. @@ -969,7 +969,7 @@ Checks whether the input character is a letter. ### isLowerCase8+ -isLowerCase(char: string): boolean +static isLowerCase(char: string): boolean Checks whether the input character is a lowercase letter. @@ -993,7 +993,7 @@ Checks whether the input character is a lowercase letter. ### isUpperCase8+ -isUpperCase(char: string): boolean +static isUpperCase(char: string): boolean Checks whether the input character is an uppercase letter. @@ -1017,7 +1017,7 @@ Checks whether the input character is an uppercase letter. ### getType8+ -getType(char: string): string +static getType(char: string): string Obtains the type of the input character string. @@ -1124,7 +1124,7 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text ``` var iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - breakIter.current(); // 0 + iterator.current(); // 0 ``` @@ -1145,7 +1145,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi ``` var iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - breakIter.first(); // 0 + iterator.first(); // 0 ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index deb605abe2bb17257c62c4e7004eabe97557e0cf..90c3c95c7c6f3a57edda9b2408c58533ee5eaa1f 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,6 @@ # Input Method Framework -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **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. > @@ -10,7 +10,7 @@ import inputMethod from '@ohos.inputMethod'; ``` -## inputMethod8+ +## inputMethod6+ Provides the constants. @@ -21,7 +21,7 @@ Provides the constants. | MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| -## InputMethodProperty8+ +## InputMethodProperty6+ Describes the input method application attributes. @@ -48,11 +48,11 @@ Obtains an [InputMethodController](#InputMethodController) instance. **Example** -``` -var InputMethodController = inputMethod.getInputMethodController(); -``` + ```js + var InputMethodController = inputMethod.getInputMethodController(); + ``` -## inputMethod.getInputMethodSetting8+ +## inputMethod.getInputMethodSetting6+ getInputMethodSetting(): InputMethodSetting @@ -120,7 +120,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. console.info('stopInput isSuccess = ' + isSuccess); ``` -## InputMethodSetting8+ +## 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. @@ -140,14 +140,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 diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 08c95d09acb749be562bbb51f9dfe711026f825f..01194e96351c0987fda676b112d2a3fd759a4d91 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -120,7 +120,7 @@ Creates an **AudioRecorder** instance to control audio recording. **Example** ```js -let audiorecorder = media.createAudioRecorder(); +let audioRecorder = media.createAudioRecorder(); ``` ## media.createVideoRecorder9+ diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index a04568bc95ec0a15a89c8ba2e6e8b11ec1c9e2f0..17a2f3badd90a7e1431d25bd744b518a3c25fea1 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,6 +1,7 @@ -# Media Library Management +# MediaLibrary -> **NOTE**
+> **NOTE** +> > This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -28,7 +29,6 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal | ----------------------------- | :---- | | [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| - **Example** ``` @@ -1948,7 +1948,7 @@ async function example() { Provides APIs to implement a physical album. -### **Attributes** +### Attributes **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2205,7 +2205,7 @@ Describes options for fetching media files. | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | | selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " 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 + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | | networkId8+ | string | Yes | Yes | No | Network ID of the registered device. | | extendArgs8+ | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 7cb3263efc4800810a185bf908ae98fef33808ec..1f754aa69bee3f93a3420df473d06e915a673c4f 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,12 +1,13 @@ # Media Query -> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> **NOTE** +> > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import mediaquery from '@ohos.mediaquery' ``` @@ -22,19 +23,19 @@ matchMediaSync(condition: string): MediaQueryListener Sets the media query criteria and returns the corresponding listening handle. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | condition | string | Yes| Matching condition of a media event.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| condition | string | Yes | Matching condition of a media event.| -- Return value - | Type| Description| - | -------- | -------- | - | MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| +**Return value** +| Type | Description | +| ------------------ | ---------------------- | +| MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| -- Example - ``` - listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +**Example** + ```js +listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. ``` @@ -45,10 +46,10 @@ Media query handle, including the first query result when the handle is applied ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### on @@ -57,13 +58,13 @@ on(type: 'change', callback: Callback<MediaQueryResult>): void Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | Yes| Callback registered with media query.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ---------------- | +| type | string | Yes | Must enter the string **change**.| +| callback | Callback<MediaQueryResult> | Yes | Callback registered with media query. | -- Example +**Example** For details, see [off Example](#off). @@ -72,14 +73,14 @@ Registers a callback with the corresponding query condition by using the handle. off(type: 'change', callback?: Callback<MediaQueryResult>): void Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | boolean | Yes| Must enter the string **change**.| - | callback | Callback<MediaQueryResult> | No| Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| - -- Example - ``` +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ----------------------------- | +| type | boolean | Yes | Must enter the string **change**. | +| callback | Callback<MediaQueryResult> | No | Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| + +**Example** + ```js import mediaquery from '@ohos.mediaquery' listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. @@ -90,8 +91,8 @@ Unregisters a callback with the corresponding query condition by using the handl // do something here } } - this.listener.on('change', this.onPortrait) // Registration callback. - this.listener.off('change', this.onPortrait) // Deregistration callback. + listener.on('change', onPortrait) // Register a callback. + listener.off('change', onPortrait) // Unregister a callback. ``` @@ -100,15 +101,15 @@ Unregisters a callback with the corresponding query condition by using the handl ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| matches | boolean | Yes| No| Whether the match condition is met.| -| media | string | Yes| No| Matching condition of a media event.| +| Name | Type | Readable | Writable | Description | +| ------- | ------- | ---- | ---- | ---------- | +| matches | boolean | Yes | No | Whether the match condition is met. | +| media | string | Yes | No | Matching condition of a media event.| ### Example -``` +```js import mediaquery from '@ohos.mediaquery' let portraitFunc = null diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index a36fc053da29747df95dcab84468288cd7421acc..e2d38af0a97479ef98b491f34b62a56fdfbf0f50 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -1,7 +1,8 @@ # missionManager -> ![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. @@ -26,15 +27,15 @@ Registers a listener to observe the mission status. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | listener | MissionListener | Yes| Listener to register.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| listener | MissionListener | Yes| Listener to register.| **Return value** - | Type| Description| - | -------- | -------- | - | number | Returns the index of the listener, which is created by the system and allocated when the mission status listener is registered. Each listener has a unique index.| +| Type| Description| +| -------- | -------- | +| number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** @@ -55,16 +56,16 @@ Registers a listener to observe the mission status. unregisterMissionListener(listenerId: number, callback: AsyncCallback<void>): void; -Unregisters a mission status listener. This API uses an asynchronous callback to return the result. +Deregisters a mission status listener. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Index of the mission status listener to unregister. Each listener has a unique index, which is returned by **registerMissionListener**.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -88,21 +89,21 @@ Unregisters a mission status listener. This API uses an asynchronous callback to unregisterMissionListener(listenerId: number): Promise<void>; -Unregisters a mission status listener. This API uses a promise to return the result. +Deregisters a mission status listener. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Index of the mission status listener to unregister. Each listener has a unique index, which is returned by **registerMissionListener**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -126,17 +127,17 @@ Unregisters a mission status listener. This API uses a promise to return the res getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; -Obtains the information of a given mission. This API uses an asynchronous callback to return the result. +Obtains the information about a given mission. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| **Example** @@ -159,22 +160,22 @@ Obtains the information of a given mission. This API uses an asynchronous callba getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; -Obtains the information of a given mission. This API uses a promise to return the result. +Obtains the information about a given mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| missionId | number | Yes| Mission ID.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| **Example** @@ -191,17 +192,17 @@ Obtains the information of a given mission. This API uses a promise to return th getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; -Obtains information of all missions. This API uses an asynchronous callback to return the result. +Obtains information about all missions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | numMax | number | Yes| Maximum number of missions whose information can be obtained.| - | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| numMax | number | Yes| Maximum number of missions whose information can be obtained.| +| callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| **Example** @@ -220,22 +221,22 @@ Obtains information of all missions. This API uses an asynchronous callback to r getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; -Obtains information of all missions. This API uses a promise to return the result. +Obtains information about all missions. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | numMax | number | Yes| Maximum number of missions whose information can be obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| numMax | number | Yes| Maximum number of missions whose information can be obtained.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| **Example** @@ -258,11 +259,11 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** @@ -293,16 +294,16 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| Device ID. It is a null string by default for the local device.| +| missionId | number | Yes| Mission ID.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| +| Type| Description| +| -------- | -------- | +| Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** @@ -331,10 +332,10 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -364,15 +365,15 @@ Locks a given mission. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -435,15 +436,15 @@ Unlocks a given mission. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -476,10 +477,10 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -509,15 +510,15 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -566,9 +567,9 @@ Clears all unlocked missions. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -590,10 +591,10 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -623,11 +624,11 @@ Switches a given mission to the foreground, with the startup parameters for the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| - | options | StartOptions | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| options | StartOptions | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -657,16 +658,16 @@ Switches a given mission to the foreground, with the startup parameters for the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| - | options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** @@ -684,20 +685,3 @@ Switches a given mission to the foreground, with the startup parameters for the console.log(err); }); ``` - -## MissionInfo - -Describes the mission information. - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| want | [Want](js-apis-featureAbility.md#want) | Yes| Yes| **Want** information of the mission.| -| label | string | Yes| Yes| Label of the mission.| -| iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission is continuable.| diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md new file mode 100644 index 0000000000000000000000000000000000000000..d4c99452483b63a9893905329d4fd1aae0be4505 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -0,0 +1,148 @@ +# Standard NFC + +Implements Near-Field Communication (NFC). + +> **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 controller from '@ohos.nfc.controller'; +``` + + +## controller.isNfcAvailable + +isNfcAvailable(): boolean + +Checks whether NFC is available. + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if NFC is available; returns **false** otherwise.| + + +## controller.openNfc + +openNfc(): boolean + +Opens NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | + +## controller.closeNfc + +closeNfc(): boolean + +Closes NFC. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +## controller.isNfcOpen + +isNfcOpen(): boolean + +Checks whether NFC is open. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ----------------------------------- | +| boolean | Returns **true** if NFC is open; returns **false** otherwise.| + +## controller.getNfcState + +getNfcState(): NfcState + +Obtains the NFC state. + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------------- | +| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| + +## controller.on('nfcStateChange') + +on(type: "nfcStateChange", callback: Callback<NfcState>): void + +Subscribes to NFC state changes. + +**System capability**: SystemCapability.Communication.NFC + +**Parameter** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| + | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + + + +## controller.off('nfcStateChange') + +off(type: "nfcStateChange", callback?: Callback<NfcState>): void + +Unsubscribes from the NFC state changes. + +**System capability**: SystemCapability.Communication.NFC + +**Parameter** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| +| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + + ```js + import nfcController from '@ohos.nfcController'; + + var NFC_STATE_NOTIFY = "nfcStateChange"; + + var recvNfcStateNotifyFunc = result => { + console.info("nfc state receive state: " + result); + } + + // Subscribe to the NFC state changes. + nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); + + // Unsubscribe from the NFC state changes. + nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); + ``` + +## NfcState + +Enumerates the NFC states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | Off| +| STATE_TURNING_ON | 2 | Turning on| +| STATE_ON | 3 | On| +| STATE_TURNING_OFF | 4 | Turning off| diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md new file mode 100644 index 0000000000000000000000000000000000000000..51731e95e192713e71add3304331475c11dd6629 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -0,0 +1,78 @@ +# Standard NFC Tag + +Manages Near-Field Communication (NFC) tags. + +> **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 tag from '@ohos.nfc.tag'; +``` + + +## tag.getNfcATag + +getNfcATag(tagInfo: TagInfo): NfcATag + +Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| NfcATag | **NfcATag** object obtained.| + +## tag.getNfcBTag + +getNfcBTag(tagInfo: TagInfo): NfcBTag + +Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcBTag | **NfcBTag** object obtained.| + +## tag.getNfcFTag + +getNfcFTag(tagInfo: TagInfo): NfcFTag + +Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcFTag | **NfcFTag** object obtained.| + +## tag.getNfcVTag + +getNfcVTag(tagInfo: TagInfo): NfcVTag + +Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| -------- | ---------------- | +| NfcVTag | **NfcVTag** object obtained.| diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index 20f6b7859945481356f504b2bc8b64b41cdd58ff..01651e83e0bdfc97e5deb0527574a81677ed39c0 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -1,17 +1,23 @@ # PermissionRequestResult -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - Provides the permission request result. +## Modules to Import + +```js +import Ability from '@ohos.application.Ability' +``` + ## Attributes **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | +| permissions | Array<string> | Yes| No| Permissions requested.| +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index 29d055c83fc1e408404a3d91c81ea0ab090a6258..167d216652325fa4f48f4aec5a1c9d923bd48ec4 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,19 +1,23 @@ # ProcessRunningInfo -> ![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. Provides process running information. +## Modules to Import + +```js +import appManager from '@ohos.application.appManager' +``` ## Usage The process running information is obtained through an **appManager** instance. - - ```js import appManager from '@ohos.application.appManager'; appManager.getProcessRunningInfos((error,data) => { @@ -26,9 +30,9 @@ appManager.getProcessRunningInfos((error,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| bundleNames | Array<string> | Yes| No| Names of all bundles running in the process.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| bundleNames | Array<string> | Yes| No| Names of all bundles running in the process.| diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 23f759d5e556d4bb382b1939f5545a79cfad4b69..ae271f2dca80df5c76b96c0e62e32ad7c8285c7e 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,6 +1,7 @@ # Prompt -> ![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 diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 6080fafdb81553615954ce2365fe1bf7de548ae1..256be1a80f2dce94e12538ad5c5c97876bdac634 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -14,8 +14,8 @@ import request from '@ohos.request'; ## Constraints -- HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. - +HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. + ``` "deviceConfig": { "default": { @@ -30,7 +30,7 @@ import request from '@ohos.request'; ## Constants -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -64,7 +64,7 @@ upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -99,7 +99,7 @@ upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -127,7 +127,7 @@ Uploads files. This API uses an asynchronous callback to return the result. ## UploadTask -Implements file uploads. Before using a method of this class, you must obtain an **UploadTask** object. +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. ### on('progress') @@ -136,7 +136,7 @@ on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => vo Subscribes to the upload progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -170,7 +170,7 @@ on(type: 'headerReceive', callback: (header: object) => void): void Subscribes to the **headerReceive** event, which is triggered when an HTTP response header is received. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -203,7 +203,7 @@ off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&g Unsubscribes from the upload progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -237,7 +237,7 @@ off(type: 'headerReceive', callback?: (header: object) => void): void Unsubscribes from the **headerReceive** event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -270,7 +270,7 @@ remove(): Promise<boolean> Removes this upload task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -301,7 +301,7 @@ remove(callback: AsyncCallback<boolean>): void Removes this upload task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -335,10 +335,10 @@ Removes this upload task. This API uses an asynchronous callback to return the r | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | url | string | Yes | Resource URL. | -| header | object | No | HTTP or HTTPS header added to an upload request. | -| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| header | object | Yes | HTTP or HTTPS header added to an upload request. | +| method | string | Yes | Request methods available: **POST** and **PUT**. The default value is **POST**. | | files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<[RequestData](#requestdata)> | No | Form data in the request body. | +| data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | ## File @@ -349,7 +349,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | No | File name in the header when **multipart** is used. | | name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. The following is an example:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | | type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | @@ -369,7 +369,7 @@ download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -403,7 +403,7 @@ download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): v Downloads files. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -440,7 +440,7 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) => vo Subscribes to the download progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -475,7 +475,7 @@ off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => Unsubscribes from the download progress event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -510,7 +510,7 @@ on(type: 'complete'|'pause'|'remove', callback:() => void): void Subscribes to a download event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -538,7 +538,7 @@ off(type: 'complete'|'pause'|'remove', callback?:() => void): void Unsubscribes from the download event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -546,7 +546,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** @@ -566,7 +566,7 @@ on(type: 'fail', callback: (err: number) => void): void Subscribes to the download task failure event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -600,7 +600,7 @@ off(type: 'fail', callback?: (err: number) => void): void Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -634,7 +634,7 @@ remove(): Promise<boolean> Removes this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -665,7 +665,7 @@ remove(callback: AsyncCallback<boolean>): void Removes this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -698,7 +698,7 @@ query(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -725,7 +725,7 @@ query(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -754,7 +754,7 @@ queryMimeType(): Promise<string> Queries **MimeType** of this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -781,7 +781,7 @@ queryMimeType(callback: AsyncCallback<string>): void; Queries **MimeType** of this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -810,7 +810,7 @@ pause(): Promise<void> Pauses this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -841,7 +841,7 @@ pause(callback: AsyncCallback<void>): void Pauses this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -874,7 +874,7 @@ resume(): Promise<void> Resumes this download task. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -906,7 +906,7 @@ resume(callback: AsyncCallback<void>): void Resumes this download task. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -944,7 +944,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 value 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. | +| 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. | | 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-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 2effb8b20a713c2c1f9a27baa8c12cabdcd37cda..335e31cdb21bacd975db26b726f503c0a44e431d 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -2,7 +2,7 @@ The resource management module provides APIs to obtain information about the current device configuration (including the language, region, screen direction, and MCC/MNC) and device capability (including the device type and resolution). -> ![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. @@ -12,31 +12,41 @@ The resource management module provides APIs to obtain information about the cur import resourceManager from '@ohos.resourceManager'; ``` +## Usage + +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its APIs without first importing the required bundle. This method, however, is not applicable to the FA model. + +``` +this.context.resourceManager; +``` + ## resourceManager.getResourceManager getResourceManager(callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of this application. This API uses a callback to return the result. +Obtains the **ResourceManager** object of this application. This API uses an asynchronous callback to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { if (error != null) { - console.log("error occurs" + error); + console.log("error is " + error); return; } mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -47,7 +57,9 @@ Obtains the **ResourceManager** object of this application. This API uses a call getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManager>): void -Obtains the **ResourceManager** object of an application. This API uses an asynchronous callback to return the result. +Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses an asynchronous callback to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager @@ -55,7 +67,7 @@ Obtains the **ResourceManager** object of an application. This API uses an async | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------------- | | bundleName | string | Yes | Bundle name of the target application. | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the **ResourceManager** object obtained.| +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Asynchronous callback used to return the result.| **Example** ``` @@ -70,25 +82,27 @@ getResourceManager(): Promise<ResourceManager> Obtains the **ResourceManager** object of this application. This API uses a promise to return the result. +This API is used only in the FA model. + **System capability**: SystemCapability.Global.ResourceManager **Return value** | Type | Description | | ---------------------------------------- | ----------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager().then(mgr => { mgr.getString(0x1000000, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }).catch(error => { - console.log(error); + console.log("error is " + error); }); ``` @@ -97,7 +111,9 @@ Obtains the **ResourceManager** object of this application. This API uses a prom getResourceManager(bundleName: string): Promise<ResourceManager> -Obtains the **ResourceManager** object of an application. This API uses a promise to return the result. +Obtains the **ResourceManager** object of an application based on the specified bundle name. This API uses a promise to return the result. + +This API is used only in the FA model. **System capability**: SystemCapability.Global.ResourceManager @@ -109,7 +125,7 @@ Obtains the **ResourceManager** object of an application. This API uses a promis **Return value** | Type | Description | | ---------------------------------------- | ------------------ | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| **Example** ``` @@ -129,8 +145,8 @@ Enumerates the screen directions. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DIRECTION_VERTICAL | 0 | Portrait | -| DIRECTION_HORIZONTAL | 1 | Landscape | +| DIRECTION_VERTICAL | 0 | Portrait. | +| DIRECTION_HORIZONTAL | 1 | Landscape. | ## DeviceType @@ -141,12 +157,12 @@ Enumerates the device types. | Name | Default Value | Description | | -------------------- | ---- | ---- | -| DEVICE_TYPE_PHONE | 0x00 | Phone | -| DEVICE_TYPE_TABLET | 0x01 | Tablet | -| DEVICE_TYPE_CAR | 0x02 | Head unit | -| DEVICE_TYPE_PC | 0x03 | PC | -| DEVICE_TYPE_TV | 0x04 | TV | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable | +| DEVICE_TYPE_PHONE | 0x00 | Phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Head unit. | +| DEVICE_TYPE_PC | 0x03 | PC. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -182,8 +198,8 @@ Defines the device configuration. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { - console.log(value.direction); - console.log(value.locale); + let direction = value.direction; + let locale = value.locale; }); }); ``` @@ -205,8 +221,8 @@ Defines the device capability. ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { - console.log(value.screenDensity); - console.log(value.deviceType); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }); }); ``` @@ -227,7 +243,7 @@ Defines the descriptor information of the raw file.
Defines the capability of accessing application resources. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm. > > - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**. @@ -245,16 +261,16 @@ Obtains the string corresponding to the specified resource ID. This API uses an | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------- | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the obtained string.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -277,15 +293,15 @@ Obtains the string corresponding to the specified resource ID. This API uses a p **Return value** | Type | Description | | --------------------- | ----------- | -| Promise<string> | Promise used to return the string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getString($r('app.string.test').id).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getstring promise error is " + error); }); }); ``` @@ -295,7 +311,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p getStringArray(resId: number, callback: AsyncCallback<Array<string>>): void -Obtains the array of strings corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -303,16 +319,16 @@ Obtains the array of strings corresponding to the specified resource ID. This AP | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the obtained array of strings.| +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let strArray = value; } }); }); @@ -323,7 +339,7 @@ Obtains the array of strings corresponding to the specified resource ID. This AP getStringArray(resId: number): Promise<Array<string>> -Obtains the array of strings corresponding to the specified resource ID. This API uses a promise to return the result. +Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -335,15 +351,15 @@ Obtains the array of strings corresponding to the specified resource ID. This AP **Return value** | Type | Description | | ---------------------------------- | ------------- | -| Promise<Array<string>> | Promise used to return the array of strings obtained.| +| Promise<Array<string>> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getStringArray($r('app.strarray.test').id).then(value => { - console.log(value); + let strArray = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getStringArray promise error is " + error); }); }); ``` @@ -361,16 +377,16 @@ Obtains the content of the media file corresponding to the specified resource ID | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------------ | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the content of the media file obtained.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -393,15 +409,15 @@ Obtains the content of the media file corresponding to the specified resource ID **Return value** | Type | Description | | ------------------------- | -------------- | -| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMedia($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMedia promise error is " + error); }); }); ``` @@ -419,16 +435,16 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ------------------------ | | resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the Base64 code of the image obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let media = value; } }); }); @@ -451,15 +467,15 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **Return value** | Type | Description | | --------------------- | -------------------- | -| Promise<string> | Promise used to return the Base64 code of the image obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getMediaBase64($r('app.media.test').id).then(value => { - console.log(value); + let media = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getMediaBase64 promise error is " + error); }); }); ``` @@ -476,16 +492,17 @@ Obtains the device configuration. This API uses an asynchronous callback to retu **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------- | -| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the obtained device configuration.| +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let direction = value.direction; + let locale = value.locale; } }); }); @@ -503,15 +520,16 @@ Obtains the device configuration. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ---------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| +| Promise<[Configuration](#configuration)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getConfiguration().then(value => { - console.log(value); + let direction = value.direction; + let locale = value.locale; }).catch(error => { - console.log("getstring promise " + error); + console.log("getConfiguration promise error is " + error); }); }); ``` @@ -528,16 +546,17 @@ Obtains the device capability. This API uses an asynchronous callback to return **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the obtained device capability.| +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability((error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; } }); }); @@ -555,15 +574,16 @@ Obtains the device capability. This API uses a promise to return the result. **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getDeviceCapability().then(value => { - console.log(value); + let screenDensity = value.screenDensity; + let deviceType = value.deviceType; }).catch(error => { - console.log("getstring promise " + error); + console.log("getDeviceCapability promise error is " + error); }); }); ``` @@ -582,16 +602,16 @@ Obtains the specified number of singular-plural strings corresponding to the spe | -------- | --------------------------- | ---- | ------------------------------- | | resId | number | Yes | Resource ID. | | num | number | Yes | Number that determines the plural or singular form. | -| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the singular-plural string obtained.| +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let str = value; } }); }); @@ -615,15 +635,15 @@ Obtains the specified number of singular-plural strings corresponding to the spe **Return value** | Type | Description | | --------------------- | ------------------------- | -| Promise<string> | Promise used to return the singular-plural string obtained.| +| Promise<string> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getPluralString($r("app.plural.test").id, 1).then(value => { - console.log(value); + let str = value; }).catch(error => { - console.log("getstring promise " + error); + console.log("getPluralString promise error is " + error); }); }); ``` @@ -632,7 +652,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void -Obtains the content of rawfile in the specified path. This API uses an asynchronous callback to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -640,16 +660,16 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ----------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the raw file content, in byte arrays.| +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { - console.log(value); + let rawFile = value; } }); }); @@ -659,7 +679,7 @@ Obtains the content of rawfile in the specified path. This API uses an asynchron getRawFile(path: string): Promise<Uint8Array> -Obtains the content of the raw file in the specified path. This API uses a promise to return the result. +Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -671,15 +691,15 @@ Obtains the content of the raw file in the specified path. This API uses a promi **Return value** | Type | Description | | ------------------------- | ----------- | -| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| +| Promise<Uint8Array> | Promise used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFile("test.xml").then(value => { - console.log(value); + let rawFile = value; }).catch(error => { - console.log("getrawfile promise " + error); + console.log("getRawFile promise error is " + error); }); }); ``` @@ -688,7 +708,7 @@ Obtains the content of the raw file in the specified path. This API uses a promi getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor>): void -Obtains the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -696,14 +716,14 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the raw file descriptor.| +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Asynchronous callback used to return the result.| **Example** ``` resourceManager.getResourceManager((error, mgr) => { mgr.getRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } else { let fd = value.fd; let offset = value.offset; @@ -717,7 +737,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses an a getRawFileDescriptor(path: string): Promise<RawFileDescriptor> -Obtains the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -729,7 +749,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr **Return value** | Type | Description | | ---------------------------------------- | ------------------- | -| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the raw file descriptor.| +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| **Example** ``` @@ -739,7 +759,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr let offset = value.offset; let length = value.length; }).catch(error => { - console.log("getRawFileDescriptor promise " + error); + console.log("getRawFileDescriptor promise error is " + error); }); }); ``` @@ -748,7 +768,7 @@ Obtains the descriptor of the raw file in the specified path. This API uses a pr closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void -Closes the descriptor of the raw file in the specified path. This API uses an asynchronous callback to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -763,7 +783,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml", (error, value) => { if (error != null) { - console.log(value); + console.log("error is " + error); } }); }); @@ -773,7 +793,7 @@ Closes the descriptor of the raw file in the specified path. This API uses an as closeRawFileDescriptor(path: string): Promise<void> -Closes the descriptor of the raw file in the specified path. This API uses a promise to return the result. +Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager @@ -791,9 +811,9 @@ Closes the descriptor of the raw file in the specified path. This API uses a pro ``` resourceManager.getResourceManager((error, mgr) => { mgr.closeRawFileDescriptor("test.xml").then(value => { - console.log(value); + let result = value; }).catch(error => { - console.log("closeRawFileDescriptor promise " + error); + console.log("closeRawFileDescriptor promise error is " + error); }); }); ``` @@ -809,10 +829,408 @@ Releases the created **resourceManager**. **Example** ``` resourceManager.getResourceManager((error, mgr) => { - mgr.release((error, value) => { - if (error != null) { - console.log(value); - } - }); + mgr.release(); + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let string = value; + } + }); + ``` + +### getStringByName9+ + +getStringByName(resName: string): Promise<string> + +Obtains the string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByName("test").then(value => { + let string = value; + }).catch(error => { + console.log("getStringByName promise error is " + error); + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void + +Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Array<string>> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let strArray = value; + } + }); + ``` + +### getStringArrayByName9+ + +getStringArrayByName(resName: string): Promise<Array<string>> + +Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getStringArrayByName("test").then(value => { + let strArray = value; + }).catch(error => { + console.log("getStringArrayByName promise error is " + error); + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void + +Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<Uint8Array> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } + }); + ``` + +### getMediaByName9+ + +getMediaByName(resName: string): Promise<Uint8Array> + +Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaByName promise error is " + error); + }); + ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resName | string | Yes | Resource name. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getMediaBase64ByName("test", (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let media = value; + } }); ``` + +### getMediaBase64ByName9+ + +getMediaBase64ByName(resName: string): Promise<string> + +Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getMediaByName("test").then(value => { + let media = value; + }).catch(error => { + console.log("getMediaBase64ByName promise error is " + error); + }); + ``` + +### getPluralStringByName9+ + +getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void + +Obtains the plural string corresponding to the specified resource name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resName | string | Yes | Resource name. | +| num | number | Yes | Number that determines the plural or singular form. | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the result.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let str = value; + } + }); + ``` + +### getPluralStringByName9+ + +getPluralStringByName(resName: string, num: number): Promise<string> + +Obtains the plural string corresponding to the specified resource name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| +| num | number | Yes | Number that determines the plural or singular form. | + +**Return value** +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the result.| + +**Example** + ``` + resourceManager.getPluralStringByName("test", 1).then(value => { + let str = value; + }).catch(error => { + console.log("getPluralStringByName promise error is " + error); + }); + ``` + +### getStringSync9+ + +getStringSync(resId: number): string + +Obtains the string corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getStringSync($r('app.string.test').id); + ``` + +### getStringByNameSync9+ + +getStringByNameSync(resName: string): string + +Obtains the string corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| string | String corresponding to the resource name.| + +**Example** + ``` + resourceManager.getStringByNameSync("test"); + ``` + + ### getBoolean9+ + +getBoolean(resId: number): boolean + +Obtains the Boolean result corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getBoolean($r('app.boolean.boolean_test').id); + ``` + +### getBooleanByName9+ + +getBooleanByName(resName: string): boolean + +Obtains the Boolean result corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| boolean | Boolean result corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getBooleanByName("boolean_test"); + ``` + + ### getNumber9+ + +getNumber(resId: number): number + +Obtains the integer or float value corresponding to the specified resource ID. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource ID.| + +**Example** + ``` + resourceManager.getNumber($r('app.integer.integer_test').id); + resourceManager.getNumber($r('app.float.float_test').id); + ``` + +### getNumberByName9+ + +getNumberByName(resName: string): number + +Obtains the integer or float value corresponding to the specified resource name. This API returns the result synchronously. + +**System capability**: SystemCapability.Global.ResourceManager + +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resName | string | Yes | Resource name.| + +**Return value** +| Type | Description | +| --------------------- | ----------- | +| number | Integer or float value corresponding to the specified resource name.| + +**Example** + ``` + resourceManager.getNumberByName("integer_test"); + resourceManager.getNumberByName("float_test"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md index 47bd7a14e1ba47c23fe1e610fdd9e135837393ef..1581838feadc1fc7ee462145b1bcd12ccedc98ac 100644 --- a/en/application-dev/reference/apis/js-apis-rpc.md +++ b/en/application-dev/reference/apis/js-apis-rpc.md @@ -78,7 +78,7 @@ writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -119,7 +119,7 @@ Reads the remote object from this **MessageParcel** object. You can use this met ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -1698,7 +1698,7 @@ Writes information to this **MessageParcel** object indicating that no exception ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -1901,7 +1901,7 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -1947,7 +1947,7 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -1994,7 +1994,7 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -2456,7 +2456,7 @@ Called to perform subsequent operations when a death notification of the remote ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } ``` @@ -2652,7 +2652,7 @@ Provides methods to implement **IRemoteObject**. ### sendRequest(deprecated) > **NOTE**
-> This API is deprecated since API Version 8. You are advised to use [sendRequest8+ ](#sendrequest8-2). +> This API is deprecated since API Version 8. You are advised to use [sendRequest8+](#sendrequest8-2). sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean @@ -2931,7 +2931,7 @@ Adds a callback for receiving the death notifications of the remote object, incl FA.connectAbility(want, connect); class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } let deathRecipient = new MyDeathRecipient(); @@ -2982,7 +2982,7 @@ Removes the callback used to receive death notifications of the remote object. FA.connectAbility(want, connect); class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } let deathRecipient = new MyDeathRecipient(); @@ -3362,7 +3362,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3497,7 +3497,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3561,7 +3561,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3627,7 +3627,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3694,7 +3694,7 @@ Provides a response to **sendRequest()**. The server processes the request and r ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3743,7 +3743,7 @@ Obtains the UID of the remote process. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3784,7 +3784,7 @@ Obtains the PID of the remote process. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3830,7 +3830,7 @@ Checks whether the remote object corresponding to the specified interface descri ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3871,7 +3871,7 @@ Obtains the interface descriptor. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -3914,7 +3914,7 @@ Binds an interface descriptor to an **IRemoteBroker** object. ``` class MyDeathRecipient { onRemoteDied() { - console.log("server is died"); + console.log("server died"); } } class TestRemoteObject extends rpc.RemoteObject { @@ -4076,7 +4076,7 @@ Creates the shared file mapping on the virtual address space of this process. Th **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | mapType | number | Yes| Protection level of the memory region to which the shared file is mapped.| @@ -4189,6 +4189,8 @@ Writes data to the shared file associated with this **Ashmem** object. ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let mapResult = ashmem.mapReadAndWriteAshmem(); + console.info("RpcTest map ashmem result is " + mapResult); var ByteArrayVar = [1, 2, 3, 4, 5]; let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0); console.log("RpcTest: write to Ashmem result is : " + writeResult); @@ -4204,7 +4206,7 @@ Reads data from the shared file associated with this **Ashmem** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | size | number | Yes| Size of the data to read.| | offset | number | Yes| Start position of the data to read in the memory region associated with this **Ashmem** object.| @@ -4219,6 +4221,8 @@ Reads data from the shared file associated with this **Ashmem** object. ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let mapResult = ashmem.mapReadAndWriteAshmem(); + console.info("RpcTest map ashmem result is " + mapResult); var ByteArrayVar = [1, 2, 3, 4, 5]; let writeResult = ashmem.writeToAshmem(ByteArrayVar, 5, 0); console.log("RpcTest: write to Ashmem result is : " + writeResult); diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 446fe758e88ffc4345942cbafdc9ffc636eda702..f9e0dc56a201863394209db59095b0d04628045b 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -57,7 +57,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** @@ -68,26 +68,26 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal **Example** -```js -var ScreenshotOptions = { - "screenRect": { - "left": 200, - "top": 100, - "width": 200, - "height": 200}, - "imageSize": { - "width": 300, - "height": 300}, - "rotation": 0 -}; -screenshot.save(ScreenshotOptions, (err, data) => { - if (err) { - console.error('Failed to save the screenshot. Error: ' + JSON.stringify(err)); - return; - } - console.info('Screenshot saved. Data: ' + JSON.stringify(data)); -}); -``` + ```js + var ScreenshotOptions = { + "screenRect": { + "left": 200, + "top": 100, + "width": 200, + "height": 200}, + "imageSize": { + "width": 300, + "height": 300}, + "rotation": 0 + }; + screenshot.save(ScreenshotOptions, (err, data) => { + if (err) { + console.error('Failed to save the screenshot. Error: ' + JSON.stringify(err)); + return; + } + console.info('Screenshot saved. Data: ' + JSON.stringify(data)); + }); + ``` ## screenshot.save @@ -97,7 +97,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN +**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** @@ -113,22 +113,22 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro **Example** -```js -var ScreenshotOptions = { - "screenRect": { - "left": 200, - "top": 100, - "width": 200, - "height": 200}, - "imageSize": { - "width": 300, - "height": 300}, - "rotation": 0 -}; -let promise = screenshot.save(ScreenshotOptions); -promise.then(() => { - console.log('screenshot save success'); -}).catch((err) => { - console.log('screenshot save fail: ' + JSON.stringify(err)); -}); -``` \ No newline at end of file + ```js + var ScreenshotOptions = { + "screenRect": { + "left": 200, + "top": 100, + "width": 200, + "height": 200}, + "imageSize": { + "width": 300, + "height": 300}, + "rotation": 0 + }; + let promise = screenshot.save(ScreenshotOptions); + promise.then(() => { + console.log('screenshot save success'); + }).catch((err) => { + console.log('screenshot save fail: ' + JSON.stringify(err)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index c04e503414020d5c0b6107ef2313df58d91b52f5..aab544f7f78bd2b755ab24443aa1d0acd5d683c1 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,17 +1,19 @@ # Sensor -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import sensor from '@ohos.sensor'; ``` +## sensor.on -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void @@ -30,7 +32,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -40,8 +42,7 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, options?: Options): void @@ -59,7 +60,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -69,8 +70,7 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void @@ -88,7 +88,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -101,8 +101,7 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>,options?: Options): void @@ -118,7 +117,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -128,8 +127,7 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>, options?: Options): void @@ -147,7 +145,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -157,8 +155,7 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<GyroscopeUncalibratedResponse>, options?: Options): void @@ -176,7 +173,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -189,8 +186,7 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void @@ -206,7 +202,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -214,8 +210,7 @@ Subscribes to data changes of the significant motion sensor. If this API is call ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void @@ -233,7 +228,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); }, @@ -241,8 +236,7 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>, options?: Options): void @@ -260,7 +254,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); }, @@ -268,8 +262,7 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<AmbientTemperatureResponse>, options?: Options): void @@ -285,7 +278,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); }, @@ -293,8 +286,7 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void @@ -310,7 +302,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -320,8 +312,7 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void @@ -337,7 +328,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -350,8 +341,7 @@ Subscribes to data changes of the uncalibrated magnetic field sensor. If this AP ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>,options?: Options): void @@ -367,7 +357,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); }, @@ -375,8 +365,7 @@ Subscribes to data changes of the proximity sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>,options?: Options): void @@ -392,7 +381,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); }, @@ -400,8 +389,7 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>,options?: Options): void @@ -417,7 +405,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); }, @@ -425,8 +413,7 @@ Subscribes to data changes of the barometer sensor. If this API is called multip ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_HALL) +### HALL on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, options?: Options): void @@ -442,7 +429,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); }, @@ -450,8 +437,7 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>, options?: Options): void @@ -467,7 +453,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); }, @@ -475,8 +461,7 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>, options?: Options): void @@ -492,7 +477,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -502,7 +487,7 @@ Subscribes to data changes of the orientation sensor. If this API is called mult ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, options?: Options): void @@ -521,7 +506,7 @@ Subscribes to only one data change of the heart rate sensor. **Example** -``` +```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ console.info("Heart rate: " + data.heartRate); }, @@ -529,7 +514,7 @@ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void @@ -545,7 +530,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -556,8 +541,7 @@ Subscribes to data changes of the rotation vector sensor. If this API is called ); ``` - -## sensor.on(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>,options?: Options): void @@ -573,7 +557,7 @@ Subscribes to data changes of the wear detection sensor. If this API is called m | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | **Example** - ``` + ```js sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); }, @@ -581,8 +565,9 @@ Subscribes to data changes of the wear detection sensor. If this API is called m ); ``` +## sensor.once -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +### ACCELEROMETER once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<AccelerometerResponse>): void @@ -599,7 +584,7 @@ Subscribes to only one data change of the acceleration sensor. | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -608,8 +593,7 @@ Subscribes to only one data change of the acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void @@ -626,7 +610,7 @@ Subscribes to only one data change of the linear acceleration sensor. | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -635,8 +619,7 @@ Subscribes to only one data change of the linear acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void @@ -665,8 +648,7 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityResponse>): void @@ -681,7 +663,7 @@ Subscribes to only one data change of the gravity sensor. | callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -690,8 +672,7 @@ Subscribes to only one data change of the gravity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeResponse>): void @@ -708,7 +689,7 @@ Subscribes to only one data change of the gyroscope sensor. | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -717,8 +698,7 @@ Subscribes to only one data change of the gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback<GyroscopeUncalibratedResponse>): void @@ -735,7 +715,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -747,8 +727,7 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<SignificantMotionResponse>): void @@ -763,15 +742,14 @@ Subscribes to only one data change of the significant motion sensor. | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void @@ -788,15 +766,14 @@ Subscribes to only one data change of the pedometer detection sensor. | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void @@ -813,15 +790,14 @@ Subscribes to only one data change of the pedometer sensor. | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void @@ -836,15 +812,14 @@ Subscribes to only one data change of the ambient temperature sensor. | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void @@ -859,7 +834,7 @@ Subscribes to only one data change of the magnetic field sensor. | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -868,8 +843,7 @@ Subscribes to only one data change of the magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>): void @@ -884,7 +858,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -896,8 +870,7 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityResponse>): void @@ -912,7 +885,7 @@ Subscribes to only one data change of the proximity sensor. | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); @@ -923,8 +896,7 @@ Subscribes to only one data change of the proximity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityResponse>): void @@ -939,15 +911,14 @@ Subscribes to only one data change of the humidity sensor. | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { console.info('Humidity: ' + data.humidity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void @@ -962,15 +933,14 @@ Subscribes to only one data change of the barometer sensor. | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { console.info('Atmospheric pressure: ' + data.pressure); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) +### HALL once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void @@ -985,15 +955,14 @@ Subscribes to only one data change of the Hall effect sensor. | callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { console.info('Status: ' + data.status); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void @@ -1008,15 +977,14 @@ Subscribes to only one data change of the ambient light sensor. | callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { console.info(' Illumination: ' + data.intensity); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void @@ -1031,7 +999,7 @@ Subscribes to only one data change of the orientation sensor. | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1040,8 +1008,7 @@ Subscribes to only one data change of the orientation sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void @@ -1056,7 +1023,7 @@ Subscribes to only one data change of the rotation vector sensor. | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1066,8 +1033,7 @@ Subscribes to only one data change of the rotation vector sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void @@ -1084,15 +1050,14 @@ Subscribes to only one data change of the heart rate sensor. | callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { console.info("Heart rate: " + data.heartRate); } ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void @@ -1107,14 +1072,16 @@ Subscribes to only one data change of the wear detection sensor. | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| **Example** - ``` + ```js sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { console.info("Wear status: "+ data.value); } ); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.off + +### ACCELEROMETER off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void @@ -1133,7 +1100,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('x-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1142,7 +1109,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +### ACCELEROMETER_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void @@ -1161,7 +1128,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1173,7 +1140,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightResponse>): void @@ -1190,14 +1157,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info(' Illumination: ' + data.intensity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void @@ -1214,14 +1181,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Temperature: ' + data.temperature); } sensor.off( sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerResponse>): void @@ -1238,14 +1205,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Atmospheric pressure: ' + data.pressure); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GRAVITY) +### GRAVITY off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityResponse>): void @@ -1262,7 +1229,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1271,7 +1238,7 @@ function callback(data) { sensor.off( sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +### GYROSCOPE off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeResponse>): void @@ -1290,7 +1257,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1299,7 +1266,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +### GYROSCOPE_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void @@ -1318,7 +1285,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1327,7 +1294,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HALL) +### HALL off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse>): void @@ -1344,14 +1311,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Status: ' + data.status); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HEART_RATE) +### HEART_RATE off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void @@ -1370,14 +1337,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info("Heart rate: " + data.heartRate); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_HUMIDITY) +### HUMIDITY off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void @@ -1396,14 +1363,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Humidity: ' + data.humidity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +### LINEAR_ACCELERATION off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback<LinearAccelerometerResponse>): void @@ -1422,7 +1389,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1431,7 +1398,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void @@ -1450,7 +1417,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1459,7 +1426,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +### MAGNETIC_FIELD_UNCALIBRATED off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticFieldUncalibratedResponse>): void @@ -1476,7 +1443,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1488,7 +1455,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION off(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback?: Callback<OrientationResponse>): void @@ -1505,7 +1472,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the Y axis: ' + data.gamma); @@ -1514,7 +1481,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerResponse>): void @@ -1529,16 +1496,16 @@ Unsubscribes from sensor data changes. | type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -**Return value** +**Example** -``` +```js function callback(data) { console.info('Steps: ' + data.steps); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void @@ -1557,14 +1524,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_PROXIMITY) +### PROXIMITY off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityResponse>): void @@ -1581,14 +1548,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Distance: ' + data.distance); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +### ROTATION_VECTOR off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<RotationVectorResponse>): void @@ -1605,7 +1572,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); @@ -1615,7 +1582,7 @@ function callback(data) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +### SIGNIFICANT_MOTION off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void @@ -1632,14 +1599,14 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void @@ -1656,7 +1623,7 @@ Unsubscribes from sensor data changes. **Example** -``` +```js function accCallback(data) { console.info('Wear status: ' + data.value); } @@ -1681,13 +1648,13 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}, function(err, data) { +```js +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(err, data) { if (err) { console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); return; } - console.info("Operation successed. Data obtained: " + data.x); + console.info("Operation successed. Data obtained: " + data); for (var i=0; i < data.length; i++) { console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); } @@ -1716,8 +1683,8 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **Example** -``` -const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}); +```js +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); promise.then((data) => { console.info("Operation successed."); for (var i=0; i < data.length; i++) { @@ -1744,8 +1711,8 @@ Obtains the geomagnetic field of a geographic location. This API uses a callback | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | **Example** -``` -sensor.getGeomagneticField([80, 0, 0], 1580486400000, function(err, data) { +```js +sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { if (err) { console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); return; @@ -1772,11 +1739,11 @@ 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. | -**Return value** - ``` - const promise = sensor.getGeomagneticField([80, 0, 0], 1580486400000); +**Example** + ```js + const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + @@ -1802,9 +1769,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| | callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -**Return value** +**Example** - ``` + ```js sensor.getAltitude(0, 200, function(err, data) { if (err) { console.error( @@ -1836,9 +1803,9 @@ Obtains the altitude at which the device is located based on the sea-level atmos | --------------------- | ------------------ | | Promise<number> | Promise used to return the altitude, in meters.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAltitude(0, 200); promise.then((data) => { console.info(' sensor_getAltitude_Promise success', data); @@ -1863,12 +1830,12 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba | inclinationMatrix | Array<number> | Yes | Inclination matrix. | | callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } @@ -1896,9 +1863,9 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis | --------------------- | -------------- | | Promise<number> | Promise used to return the magnetic dip, in radians.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { console.info(' getGeomagneticDip_promise successed', data); @@ -1923,18 +1890,18 @@ Obtains the angle change between two rotation matrices. This API uses a callback | preRotationMatrix | Array<number> | Yes | The other rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { if (err) { - console.error(LABEL + 'Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('Failed to register data, error code is: ' + err.code + ', message: ' + 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(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -1961,17 +1928,17 @@ Obtains the angle change between two rotation matrices. This API uses a promise | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); promise.then((data) => { - console.info(LABEL + 'getAngleModifiy_promise success'); + console.info('getAngleModifiy_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -1991,18 +1958,18 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + 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(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2028,17 +1995,17 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re | ---------------------------------- | ------- | | Promise<Array<number>> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise success'); + console.info('createRotationMatrix_promise success'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((reason) => { - console.info(LABEL + "promise::catch", reason); + console.info("promise::catch", reason); }) ``` @@ -2058,18 +2025,18 @@ Converts a rotation vector into a quaternion. This API uses a callback to return | rotationVector | Array<number> | Yes | Rotation vector to convert.| | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | -**Return value** +**Example** - ``` + ```js sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + 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(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }) ``` @@ -2095,14 +2062,14 @@ Converts a rotation vector into a quaternion. This API uses a promise to return | ---------------------------------- | ------ | | Promise<Array<number>> | Promise used to return the quaternion.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); promise.then((data) => { console.info('createQuaternion_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2125,18 +2092,18 @@ Obtains the device direction based on the rotation matrix. This API uses a callb | rotationMatrix | Array<number> | Yes | Rotation matrix. | | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + err.message); return; } - console.info(LABEL + "SensorJsAPI--->Successed to get getDirection interface get data: " + data.x); + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_callback" + data[i]); + console.info("sensor_getDirection_callback" + data[i]); } }) ``` @@ -2162,14 +2129,14 @@ Obtains the device direction based on the rotation matrix. This API uses a promi | ---------------------------------- | ------------------ | | Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| -**Return value** +**Example** - ``` + ```js const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info(' sensor_getAltitude_Promise success', data.x); + console.info('sensor_getAltitude_Promise success', data); for (var i = 1; i < data.length; i++) { - console.info(TAG +"sensor_getDirection_promise" + data[i]); + console.info("sensor_getDirection_promise" + data[i]); } }).catch((err) => { console.info('promise failed'); @@ -2193,18 +2160,18 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | geomagnetic | Array<number> | Yes | Geomagnetic vector.| | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { if (err) { - console.error(LABEL + 'SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + 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(LABEL + "data[" + i + "]: " + data[i]) + console.info("data[" + i + "]: " + data[i]) } }) ``` @@ -2231,17 +2198,17 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th | ---------------------------------------- | ------- | | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| -**Return value** +**Example** - ``` + ```js const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); promise.then((data) => { - console.info(LABEL + 'createRotationMatrix_promise successed'); + console.info('createRotationMatrix_promise successed'); for (var i=0; i < data.length; i++) { - console.info(LABEL + "data[" + i + "]: " + data[i]); + console.info("data[" + i + "]: " + data[i]); } }).catch((err) => { - console.info(LABEL + 'promise failed'); + console.info('promise failed'); }) ``` @@ -2355,11 +2322,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ----------------- | | alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in degrees.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees. | -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees. | +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in degrees.| +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in degrees.| ## RotationVectorResponse diff --git a/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md b/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md index 6ae73bc916dc23ab08df4ed57bf1c8c7b5b0e164..c45388554dee3107ee10ffcdaa3a5a8c22ad60c6 100644 --- a/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md +++ b/en/application-dev/reference/apis/js-apis-serviceExtAbilityContext.md @@ -1,7 +1,7 @@ # ServiceExtAbilityContext -> **NOTE**
+> **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. @@ -10,9 +10,9 @@ **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extensionAbilityInfo | ExtensionAbilityInfo | Yes| No| Extension ability information. | +| extensionAbilityInfo | ExtensionAbilityInfo | Yes| No| Extension ability information. | ## startAbility @@ -25,10 +25,10 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -53,11 +53,11 @@ Starts an ability with **options** specified. This API uses an asynchronous call **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| | options | StartOptions | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -86,16 +86,16 @@ Starts an ability with **options** specified. This API uses a promise to return **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| +| 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.| **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** ```js @@ -125,11 +125,11 @@ Starts an ability based on an account. This API uses an asynchronous callback to **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| Account ID. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -155,12 +155,12 @@ Starts an ability based on an account and **options**. This API uses an asynchro **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| Account ID. | +| want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| +| accountId | number | Yes| Account ID. | | options | StartOptions | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -190,17 +190,17 @@ Starts an ability based on an account and **options**. This API uses a promise t **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| | accountId | number | Yes| Account ID. | | options | StartOptions | No| Parameters used for starting the ability.| **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** ```js @@ -231,9 +231,9 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -253,9 +253,9 @@ Terminates this ability. This API uses a promise to return the result. **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** @@ -278,14 +278,14 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| | options | ConnectOptions | Yes| Connection channel.| **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | | number | ID of the connection between the two abilities.| @@ -322,15 +322,15 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-featureAbility.md#want)| Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| | accountId | number | Yes| Account ID.| | options | ConnectOptions | Yes| Connection channel.| **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | | number | ID of the connection between the two abilities.| @@ -368,7 +368,7 @@ Disconnects this ability from another ability. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | connection | number | Yes| ID of the connection to be disconnected.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -392,15 +392,15 @@ Disconnects this ability from another ability. This API uses a promise to return **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | connection | number | Yes| ID of the connection to be disconnected.| **Return value** -| Type| Description| +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md index b1029f29ebf254adac5b6b350fd309a464df7328..f95061b6337585954abacae035e0b1554376b9bd 100644 --- a/en/application-dev/reference/apis/js-apis-statfs.md +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -1,28 +1,15 @@ # statfs -> **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. -This module provides information related to the file system. It provides JS APIs to obtain 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. ## Modules to Import ```js import statfs from '@ohos.statfs'; ``` - -## Guidelines - -Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the application sandbox. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). - -Application sandbox path of a file or directory = Application directory + File name or directory name - -For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the application sandbox path of the file is as follows: - -```js -let path = dir + "xxx.txt"; -``` - ## statfs.getFreeBytes getFreeBytes(path:string):Promise<number> @@ -72,8 +59,12 @@ Obtains the number of free bytes of the specified file system in asynchronous mo - Example ```js - statfs.getFreeBytes(path, function(err, number){ - console.info("getFreeBytes callback successfully:"+ number); + import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); + context.getFilesDir().then(function (path) { + statfs.getFreeBytes(path, function(err, number){ + console.info("getFreeBytes callback successfully:"+ number); + }); }); ``` @@ -126,7 +117,11 @@ Obtains the total number of bytes of the specified file system in asynchronous m - Example ```js - statfs.getTotalBytes(path, function(err, number){ - console.info("getTotalBytes callback successfully:"+ number); + import featureAbility from '@ohos.ability.featureAbility'; + let context = featureAbility.getContext(); + context.getFilesDir().then(function (path) { + statfs.getTotalBytes(path, function(err, number){ + console.info("getTotalBytes callback successfully:"+ number); + }); }); ``` 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 b952a91eabffa710b5f622acb54a84a9536ec297..22aeb61ce6a2a1184c3e9b978073f504953534c3 100644 --- a/en/application-dev/reference/apis/js-apis-system-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-system-bluetooth.md @@ -1,7 +1,7 @@ # Bluetooth -> ![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.bluetooth`](js-apis-bluetooth.md). > @@ -15,7 +15,6 @@ import bluetooth from '@system.bluetooth'; ``` - ## bluetooth.startBLEScan(OBJECT) Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes system resources. Call [bluetooth.stopBLEScan](#bluetoothstopblescanobject) to stop the scan after a BLE device is detected and connected. @@ -38,6 +37,7 @@ Scans for Bluetooth Low Energy (BLE) devices nearby. This operation consumes sys ``` bluetooth.startBLEScan({ + interval:0, success() { console.log('call bluetooth.startBLEScan success.'); }, @@ -120,7 +120,7 @@ Subscribes to the newly detected BLE device. If this API is called multiple time **Example** ``` - bluetooth.startaBLEScan({ + bluetooth.startBLEScan({ success() { bluetooth.subscribeBLEFound({ success(data) { 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 b0dc3c5b117f5256020aa0cc5073e662c62cb6c9..b29842197c897d8dcb50d120f9f6c5a8a8ecce17 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,15 +1,14 @@ # Encryption Algorithm -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE**
> -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. +> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import cipher from '@system.cipher' ``` @@ -24,27 +23,27 @@ Encrypts or decrypts data using RSA. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Keys encrypted using RSA. During encryption, this parameter is a public key. During decryption, it is a private key. | -| transformation | string | No | RSA algorithm padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| 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.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { rsa() { cipher.rsa({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded public key used for encryption + // Base64-encoded public key used for encryption. key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + 'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + @@ -58,14 +57,14 @@ export default { } }); cipher.rsa({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // The text to be decrypted is a Base64-encoded binary value, and the decrypted text is "hello". + // 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=', - // Base64-encoded public key used for encryption + // Base64-encoded private key used for decryption. key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + '7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + @@ -103,30 +102,30 @@ Encrypts or decrypts data using AES. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | -| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text. The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | -| key | string | Yes | Key used for encryption or decryption, which is a character string encrypted using Base64. | -| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | -| iv | string | No | Initial vector for AES-based encryption and decryption. The value is a character string encoded using Base64. The default value is the key value. | -| ivOffset | string | No | Offset of the initial vector for AES-based encryption and decryption. The default value is **0**. | -| ivLen | string | No | Length of the initial vector for AES-based encryption and decryption. The default value is **16**. | -| success | Function | No | Called when data is encrypted or decrypted successfully. | -| fail | Function | No | Called when data fails to be encrypted or decrypted. | -| complete | Function | No | Called when the execution is complete. | +| 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**.| +| success | Function | No| Called when data is encrypted or decrypted successfully.| +| fail | Function | No| Called when data fails to be encrypted or decrypted.| +| complete | Function | No| Called when the execution is complete.| **Example** -``` +```js export default { aes() { cipher.aes({ - // Encrypt data. + // Encrypt data. action: 'encrypt', - // Text content to be encrypted + // Text to be encrypted. text: 'hello', - // Base64-encoded key used for encryption + // Base64-encoded key used for encryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -139,13 +138,13 @@ export default { } }); cipher.aes({ - // Decrypt data. + // Decrypt data. action: 'decrypt', - // Text to be decrypted, which is a Base64-encoded binary value + // 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 + // Base64-encoded key used for decryption. key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', transformation: 'AES/CBC/PKCS5Padding', ivOffset: 0, @@ -162,4 +161,4 @@ export default { } } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md index d1564c4213f98d48187231dbdd960561b10f27c7..a46571ff7fc4caf83fface874c561e75529584c1 100644 --- a/en/application-dev/reference/apis/js-apis-system-configuration.md +++ b/en/application-dev/reference/apis/js-apis-system-configuration.md @@ -17,7 +17,7 @@ import configuration from '@system.configuration'; ## configuration.getLocale -getLocale(): LocaleResponse +static getLocale(): LocaleResponse Obtains the current locale of the application, which is the same as the system locale. diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md index f05357dbe766366e8653c51b85544d12317385ce..1ae0fb6e908f96e0c86ecef973a79252ce88ea86 100644 --- a/en/application-dev/reference/apis/js-apis-system-file.md +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -1,9 +1,7 @@ # File Storage - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.fileio`](js-apis-fileio.md) instead. +> **NOTE**
+> - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.fileio`](js-apis-fileio.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -26,21 +24,21 @@ Moves a specified file to a given location. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcUri | string | Yes | URI of the file to move. | -| dstUri | string | Yes | URI of the location to which the file is to move. | -| success | Function | No | Called when the source file is moved to the specified location successfully. This function returns the URI of the destination location. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| srcUri | string | Yes| Uniform resource identifier (URI) of the file to move.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| dstUri | string | Yes| URI of the location to which the file is to move.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| success | Function | No| Called when the file is moved to the specified location. This API returns the URI of the destination location.| +| fail | Function | No| Called when the file fails to be moved.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -66,27 +64,27 @@ export default { copy(Object): void -Copies a file and saves the copy to a specified location. +Copies a file to the given URI. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| srcUri | string | Yes | URI of the file to copy. | -| dstUri | string | Yes | URI of the location to which the copy is to save.
The directory of application resources and URI of the **tmp** type are not supported. | -| success | Function | No | Called when the source file is copied and saved to the specified location successfully. This function returns the URI of the destination location. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| srcUri | string | Yes| URI of the file to copy.| +| dstUri | string | Yes| URI of the location to which the copy is to be saved.
The directory of application resources and URI of the **tmp** type are not supported.| +| success | Function | No| Called when the file is copied and saved to the specified location. This API returns the URI of the destination location.| +| fail | Function | No| Called when the file fails to be copied.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -112,41 +110,41 @@ export default { list(Object): void -Obtains the list of all files in a specified directory. +Obtains all files in the specified directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory.
The URI can contain a maximum of 128 characters, excluding the following characters: "\*+,:;<=>?[]\|\x7F | +| success | Function | No| Called when the file list is obtained.| +| fail | Function | No| Called when the file list fails to be obtained.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +Return values of the **success** callback: -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | +| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | -**Table1** FileInfo +**Table 1** FileInfo -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| uri | string | File URI. | -| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | -| length | number | File size, in bytes. | -| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | +| uri | string | URI of the file.| +| lastModifiedTime | number | Timestamp when the file is saved the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT.| +| length | number | File size, in bytes.| +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -156,7 +154,7 @@ export default { file.list({ uri: 'internal://app/pic', success: function(data) { - console.log(data.fileList); + console.log(JSON.stringify(data.fileList)); }, fail: function(data, code) { console.error('call fail callback fail, code: ' + code + ', data: ' + data); @@ -171,37 +169,37 @@ export default { get(Object): void -Obtains information about a specified local file. +Obtains information about a local file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | File URI. | -| recursive | boolean | No | Whether to recursively obtain the file list under a subdirectory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the file.| +| recursive | boolean | No| Whether to recursively obtain the file list under a subdirectory. The default value is **false**.| +| success | Function | No| Called when the file information is obtained.| +| fail | Function | No| Called when the file information fails to be obtained.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +Return values of the **success** callback: -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| uri | string | File URI. | -| length | number | File size, in bytes. | -| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | -| type | string | File type. The values are as follows:
- **dir**: directory
- **file**: file | -| subFiles | Array | File list. | +| uri | string | URI of the file.| +| length | number | File size, in bytes.| +| lastModifiedTime | number | Timestamp when the file is saved the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT.| +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | +| subFiles | Array | List of files.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -226,26 +224,26 @@ export default { delete(Object): void -Deletes local files. +Deletes a local file. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the file to delete, which cannot be an application resource path. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the file to delete. It cannot be an application resource path.| +| success | Function | No| Called when the file is deleted.| +| fail | Function | No| Called when the file fails to be deleted.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Incorrect parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -270,28 +268,28 @@ export default { writeText(Object): void -Writes text into a specified file. +Writes text into a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | -| text | string | Yes | Character string to write into the local file. | -| encoding | string | No | Encoding format. The default format is UTF-8. | -| append | boolean | No | Whether to enable the append mode. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file. If it does not exist, a file will be created.| +| text | string | Yes| Text to write into the file. | +| encoding | string | No| Encoding format. The default format is **UTF-8**.| +| append | boolean | No| Whether to enable the append mode. The default value is **false**.| +| success | Function | No| Called when the text is written into the specified file.| +| fail | Function | No| Called when the text fails to be written into the file.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Incorrect parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -317,28 +315,28 @@ export default { writeArrayBuffer(Object): void -Writes buffer data into a specified file. +Writes buffer data into a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | -| buffer | Uint8Array | Yes | Buffer from which the data is derived. | -| position | number | No | Offset to the position where the writing starts. The default value is **0**. | -| append | boolean | No | Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file. If it does not exist, a file will be created.| +| buffer | Uint8Array | Yes| Buffer from which the data is derived.| +| position | number | No| Offset to the position where the writing starts. The default value is **0**.| +| append | boolean | No| Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid.| +| success | Function | No| Called when buffer data is written into the file. | +| fail | Function | No| Called when buffer data fails to be written into the file.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -347,7 +345,7 @@ export default { writeArrayBuffer() { file.writeArrayBuffer({ uri: 'internal://app/test', - buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. + buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. success: function() { console.log('call writeArrayBuffer success.'); }, @@ -364,36 +362,36 @@ export default { readText(Object): void -Reads text from a specified file. +Reads text from a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. | -| encoding | string | No | Encoding format. The default format is UTF-8. | -| position | number | No | Position where the reading starts. The default value is the start position of the file. | -| length | number | No | Length of the text to be read (in bytes). The default value is **4096**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file.| +| encoding | string | No| Encoding format. The default format is **UTF-8**.| +| position | number | No| Position where the reading starts. The default value is the start position of the file.| +| length | number | No| Length of the text to read, in bytes. The default value is **4096**.| +| success | Function | No| Called when the text is read successfully.| +| fail | Function | No| Called when the text failed to be read.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +Return values of the **success** callback: -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| text | string | Text read from the specified file. | +| text | string | Text read from the specified file.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | The file or directory does not exist. | -| 302 | The size of text to read exceeds 4096 bytes. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| +| 302 | The text to read exceeds 4 KB.| **Example** @@ -418,34 +416,34 @@ export default { readArrayBuffer(Object): void -Reads buffer data from a specified file. +Reads buffer data from a file. Only text files can be read and written. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of a local file. | -| position | number | No | Position where the reading starts. The default value is the start position of the file. | -| length | number | No | Length of data to read. If this parameter is not set, the reading proceeds until the end of the file. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of a local file.| +| position | number | No| Position where the reading starts. The default value is the start position of the file.| +| length | number | No| Length of data to read. If this parameter is not set, the reading proceeds until the end of the file.| +| success | Function | No| Called when the buffer data is read successfully.| +| fail | Function | No| Called when the buffer data fails to be read.| +| complete | Function | No| Called when the execution is complete.| -Return values of the **success** callback +Return values of the **success** callback: -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| buffer | Uint8Array | File content that is read | +| buffer | Uint8Array | Data read.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -472,26 +470,26 @@ export default { access(Object): void -Checks whether a specified file or directory exists. +Checks whether a file or directory exists. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory or file. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory or file to check.| +| success | Function | No| Called when the operation is successful.| +| fail | Function | No| Called when the operation fails.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -516,26 +514,26 @@ export default { mkdir(Object): void -Creates a specified directory. +Creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| recursive | boolean | No | Whether to recursively create upper-level directories of the specified directory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory to create.| +| recursive | boolean | No| Whether to recursively create upper-level directories of the specified directory. The default value is **false**.| +| success | Function | No| Called when the directory is created.| +| fail | Function | No| Called when the directory fails to be created.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| **Example** @@ -560,27 +558,27 @@ export default { rmdir(Object): void -Deletes a specified directory. +Deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes | URI of the directory. | -| recursive | boolean | No | Whether to recursively delete subfiles and subdirectories of the specified directory. The default value is **false**. | -| success | Function | No | Called when the operation is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| uri | string | Yes| URI of the directory to delete.| +| recursive | boolean | No| Whether to recursively delete files and subdirectories of the specified directory. The default value is **false**.| +| success | Function | No| Called when the directory is deleted.| +| fail | Function | No| Called when the directory fails to be deleted.| +| complete | Function | No| Called when the execution is complete.| -One of the following error codes will be returned if the operation fails. +Error code returned: -| Error Code | Description | +| Error Code| Description| | -------- | -------- | -| 202 | Invalid parameter. | -| 300 | I/O error. | -| 301 | File or directory not exist. | +| 202 | Incorrect parameters are detected.| +| 300 | An I/O error occurs.| +| 301 | The file or directory does not exist.| **Example** @@ -598,4 +596,4 @@ export default { }); } } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md index c9b37ef403d7e6f958f91f2747710ad53ad4f983..e37601dbfa3ec72d13a7722fb4dc56a8b3fe6fef 100644 --- a/en/application-dev/reference/apis/js-apis-system-prompt.md +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -1,8 +1,8 @@ # Prompt -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 8. You are advised to use ['@ohos.prompt](js-apis-prompt.md)' instead. +> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.prompt`](js-apis-prompt.md) instead. > > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import prompt from '@system.prompt'; ``` @@ -25,13 +25,13 @@ Shows the toast. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------------------------------- | --------- | ------------------------------ | -| options | [ShowToastOptions](#showtoastoptions) | Yes | Options for showing the toast. | +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | --------------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Options for showing the toast.| **Example** -``` +```js export default { showToast() { prompt.showToast({ @@ -53,14 +53,14 @@ Shows the dialog box. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | --------------------------------------- | --------- | ----------------------------------- | -| options | [ShowDialogOptions](#showdialogoptions) | Yes | Options for showing the dialog box. | +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ----------- | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Options for showing the dialog box.| **Example** -``` +```js export default { showDialog() { prompt.showDialog({ @@ -93,14 +93,14 @@ Shows the action menu. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | --------- | ------------------------------------ | -| options | [ShowActionMenuOptions](#showactionmenuoptions) | Yes | Options for showing the action menu. | +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| options | [ShowActionMenuOptions](#showactionmenuoptions) | Yes | Options for showing the action menu.| **Example** -``` +```js export default { showActionMenu() { prompt.showActionMenu({ @@ -115,11 +115,11 @@ export default { color: '#000000', }, ], - success: function(data) { + success: function(tapIndex) { console.log('dialog success callback, click button : ' + data.tapIndex); }, - fail: function(data) { - console.log('dialog fail callback' + data.errMsg); + fail: function(errMsg) { + console.log('dialog fail callback' + errMsg); }, }); } @@ -131,11 +131,11 @@ Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------------------- | -------------- | --------- | ---------------------------------------- | -| message | string | Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. | -| bottom5+ | string\|number | No | Distance between the toast frame and the bottom of the screen. | +| Name | Type | Mandatory | Description | +| ------------------- | -------------- | ---- | ---------------------------------------- | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom5+ | string\|number | No | Distance between the toast border and the bottom of the screen. | ## Button @@ -143,10 +143,10 @@ Defines the prompt information of a button. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ----------------------------- | -| text | string | Yes | Text displayed on the button. | -| color | string | Yes | Color of the button. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------- | +| text | string | Yes | Text displayed on the button.| +| color | string | Yes | Color of the button.| ## ShowDialogSuccessResponse @@ -154,9 +154,9 @@ Defines the dialog box response result. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ----------- | -| index | number | Yes | Data index. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------- | +| index | number | Yes | Data index.| ## ShowDialogOptions @@ -164,14 +164,14 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| message | string | No | Text body. | -| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed. | -| success | (data: [ShowDialogSuccessResponse](#showdialogsuccessresponse)) => void | No | Callback upon success. | -| cancel | (data: string, code: string) => void | No | Callback upon failure. | -| complete | (data: string) => void | No | Called when the API call is complete. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| message | string | No | Text body. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| +| success | (data: [ShowDialogSuccessResponse](#showdialogsuccessresponse)) => void | No | Callback upon success. | +| cancel | (data: string, code: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Called when the API call is complete. | ## ShowActionMenuOptions6+ @@ -179,10 +179,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?] | Yes | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported. | -| success | (tapIndex: number, errMsg: string) => void | No | Invoked when a dialog box is displayed. | -| fail | (errMsg: string) => void | No | Callback upon failure. | -| complete | (data: string) => void | No | Invoked when a dialog box is closed. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?] | Yes | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported.| +| success | (tapIndex: number, errMsg: string) => void | No | Invoked when a dialog box is displayed. | +| fail | (errMsg: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Invoked when a dialog box is closed. | diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index a93ffdfa68f6406c6290221d4c5fe757fd7c906b..0f1f932efe54af1337ce19354d19343b6f637687 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,6 +1,6 @@ # Page Routing -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > > - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.router`](js-apis-router.md) instead. > @@ -11,7 +11,7 @@ ## Modules to Import -``` +```js import router from '@system.router'; ``` @@ -31,7 +31,7 @@ Navigates to a specified page in the application. **Example** -``` +```js // Current page export default { pushPage() { @@ -49,7 +49,7 @@ export default { ``` -``` +```js // routerpage2 page export default { data: { @@ -85,7 +85,7 @@ Replaces the current page with another one in the application and destroys the c **Example** -``` +```js // Current page export default { replacePage() { @@ -100,7 +100,7 @@ export default { ``` -``` +```js // detail page export default { data: { @@ -128,7 +128,7 @@ Returns to the previous page or a specified page. **Example** -``` +```js // index page export default { indexPushPage() { @@ -140,7 +140,7 @@ export default { ``` -``` +```js // detail page export default { detailPushPage() { @@ -152,7 +152,7 @@ export default { ``` -``` +```js // Navigate from the mall page to the detail page through router.back(). export default { mallBackPage() { @@ -162,7 +162,7 @@ export default { ``` -``` +```js // Navigate from the detail page to the index page through router.back(). export default { defaultBack() { @@ -172,7 +172,7 @@ export default { ``` -``` +```js // Return to the detail page through router.back(). export default { backToDetail() { @@ -208,7 +208,7 @@ Clears all historical pages in the stack and retains only the current page at th **Example** -``` +```js export default { clearPage() { router.clear(); @@ -232,7 +232,7 @@ Obtains the number of pages in the current stack. **Example** -``` +```js export default { getLength() { var size = router.getLength(); @@ -257,7 +257,7 @@ Obtains state information about the current page. **Example** -``` +```js export default { getState() { var page = router.getState(); @@ -284,7 +284,7 @@ Enables the display of a confirm dialog box before returning to the previous pag **Example** -``` +```js export default { enableAlertBeforeBackPage() { router.enableAlertBeforeBackPage({ @@ -292,8 +292,8 @@ export default { success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } @@ -316,15 +316,15 @@ Disables the display of a confirm dialog box before returning to the previous pa **Example** -``` +```js export default { disableAlertBeforeBackPage() { router.disableAlertBeforeBackPage({ success: function() { console.log('success'); }, - fail: function() { - console.log('fail'); + cancel: function() { + console.log('cancel'); }, }); } diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 74beca3c0aacbabd628f99f7987b96caf5988f61..4e35097eef25a1e7276efef9d477cf0abc8c4022 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,7 +1,8 @@ # Setting the System Time -> ![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 is used to set and obtain the current system date, time, and time zone. + +> **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 @@ -199,7 +200,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(callback: AsyncCallback<number>): void +getRealTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. @@ -227,7 +228,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(): Promise<number> +getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index e85037469d3dd0d931ea7de0a37df77d35880bae..d144a95db8f59ca0605fd228b351380afe6feac8 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -1,50 +1,45 @@ # Timer -> **NOTE:** The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Module to Import - -None +## setTimeout -## Required Permissions +## Modules to Import -None -## setTimeout +``` +import Time from '@ohos.Time'; +``` -setTimeout(handler[,delay[, ...args]]): number +setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. -- Parameters +**Parameters** - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called after the timer goes off.| +| delay | number | No| Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Function to be called after the timer goes off. | - | delay | number | No | Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible. | - | ...args | Array\ | No | Additional parameter to pass to the handler after the timer goes off. | +**Return value** -- Return Value +| Type| Description| +| -------- | -------- | +| number | Timer ID.| - +**Example** - | Type | Description | - | ------ | ----------- | - | number | Timer ID. | - -- Example - - ``` - 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 @@ -52,26 +47,25 @@ clearTimeout(timeoutID: number): void Cancels the timer created via **setTimeout()**. -- Parameter +**Parameters** - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| timeoutID | number | Yes| ID of the timer to cancel, which is returned by **setTimeout()**| - | Name | Type | Mandatory | Description | - | --------- | ------ | --------- | ------------------------------------------------------------ | - | timeoutID | number | Yes | ID of the timer to cancel, which is returned by **setTimeout()** | +**Example** -- Example - - ``` - 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 @@ -79,35 +73,32 @@ setInterval(handler[, delay[, ...args]]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. -- Parameters - - +**Parameters** - | Name | Type | Mandatory | Description | - | ------- | ----------- | --------- | ------------------------------------------------------------ | - | handler | Function | Yes | Function to be called repeatedly | - | delay | number | No | Number of milliseconds delayed before the execution | - | ...args | Array\ | No | Additional parameter to pass to the handler after the timer goes off | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| handler | Function | Yes| Function to be called repeatedly.| +| delay | number | No| Number of milliseconds delayed before the execution.| +| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| -- Return Value +**Return value** - +| Type| Description| +| -------- | -------- | +| number | ID of the repeating timer.| - | Type | Description | - | ------ | ------------------------- | - | number | ID of the repeated timer. | +**Example** -- Example - - ``` - 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 @@ -115,23 +106,21 @@ clearInterval(intervalID: number): void Cancels the repeating timer set via **setInterval()**. -- Parameter - - +**Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | --------- | ------------------------------------------------------------ | - | intervalID | number | Yes | ID of the repeating timer to cancel, which is returned by **setInterval()**. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| intervalID | number | Yes| ID of the repeating timer to cancel, which is returned by **setInterval()**.| -- Example +**Example** - ``` - 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 +} +``` \ 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 577a110c9457e69682bdbfa21a495e163207d640..971d25f95d622ee681abff44ffb97ff9b3524572 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,8 +1,7 @@ # UiTest ->**NOTE** +>**NOTE**
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > ->The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,46 +12,27 @@ import {UiDriver,BY,MatchPattern} from '@ohos.uitest' ## By -The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. -The API capabilities provided by the **By** class exhibit the following features: +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. -- Allows one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - -- Provides multiple match patterns for component attributes. - -- Supports absolute positioning and relative positioning for components. APIs such as **isBefore** and **isAfter** can be used to specify the features of adjacent components to assist positioning. - -All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode, for example, **BY.text('123').type('button')**. - -### enum MatchPattern - -Enumerates the match patterns supported for component attributes. - -**System capability**: SystemCapability.Test.UiTest - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| EQUALS | 0 | Equal to the given value. | -| CONTAINS | 1 | Contain the given value. | -| STARTS_WITH | 2 | Start with the given value.| -| ENDS_WITH | 3 | End with the given value.| +```js +BY.text('123').type('button') +``` ### By.text -text(txt:string,pattern?:MatchPattern):By +text(txt: string, pattern?: MatchPattern): By Specifies the text attribute of the target component. Multiple match patterns are supported. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------ | ---- | ---------------------------------- | -| txt | string | Yes | Component text, used to match the target component.| -| pattern | MatchPattern | No | Match pattern. The default value is **EQUALS**. | +| Name | Type | Mandatory| Description | +| ------- | ------------ | ---- | ------------------------------------------------- | +| txt | string | Yes | Component text, used to match the target component. | +| pattern | MatchPattern | No | Match pattern. The default value is [EQUALS](#matchpattern).| **Return value** @@ -62,324 +42,291 @@ Specifies the text attribute of the target component. Multiple match patterns ar **Example** -``` -let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute - of the target component. +```js +let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute of the target component. ``` ### By.key -key(key:string):By; +key(key: string): By Specifies the key attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | --------------- | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | | key | string | Yes | Component key.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute - of the target component. +```js +let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute of the target component. ``` ### By.id -id(id:number):By; - -Specifies the ID property of the target component. +id(id: number): By -**Required permissions**: none +Specifies the ID attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | | id | number | Yes | Component ID.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.id(123) // Use the static constructor BY to create a By object and specify the ID attribute - of the target component. +```js +let by = BY.id(123) // Use the static constructor BY to create a By object and specify the id attribute of the target component. ``` ### By.type -type(tp:string):By; - -Specifies the type property of the target component. +type(tp: string): By -**Required permissions**: none +Specifies the type attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | | tp | string | Yes | Component type.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute - of the target component. +```js +let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute of the target component. ``` ### By.clickable -clickable(b?:bool):By; +clickable(b?: bool): By Specifies the clickable attribute of the target component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Clickable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable attribute - of the target component. +```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. ``` ### By.scrollable -scrollable(b?:bool):By; - -Specifies the scrollable attribute of the target component. +scrollable(b?: bool): By -**Required permissions**: none +Specifies the scrollable status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | | b | bool | No | Scrollable status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable attribute - of the target component. +```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. ``` ### By.enabled -enabled(b?:bool):By; +enabled(b?: bool): By -Specifies the enable attribute of the target component. - -**Required permissions**: none +Specifies the enabled status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| b | bool | No | Enable status of the target component. The default value is **true**.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Enabled status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enable attribute - of the target component. +```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. ``` ### By.focused -focused(b?:bool):By; +focused(b?: bool): By -Specifies the focused attribute of the target component. - -**Required permissions**: none +Specifies the focused status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | | b | bool | No | Focused status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the focused attribute - of the target component. +```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. ``` ### By.selected -selected(b?:bool):By; - -Specifies the selected attribute of the target component. +selected(b?: bool): By -**Required permissions**: none +Specifies the selected status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------------- | | b | bool | No | Selected status of the target component. The default value is **true**.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected attribute - of the target component. +```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. ``` ### By.isBefore -isBefore(by:By):By; +isBefore(by: By): By Specifies the attributes of the component before which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component before which the target component is located. +```js +let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component before which the target component is located. ``` ### By.isAfter -isAfter(by:By):By; +isAfter(by: By): By Specifies the attributes of the component after which the target component is located. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------- | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | | by | By | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | -------------- | +| Type| Description | +| ---- | ---------------- | | By | Returns the **By** object itself.| **Example** -``` -let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes - of the component after which the target component is located. +```js +let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component after which the target component is located. ``` ## UiComponent In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. -All APIs provided by this class use a promise to return the result and must be invoked using **await**. +All APIs provided in this class use a promise to return the result and must be invoked using **await**. ### UiComponent.click -click():Promise\; +click(): Promise\ Clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -389,37 +336,33 @@ async function demo() { ### UiComponent.doubleClick -doubleClick():Promise\; +doubleClick(): Promise\ Double-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) - await buttont.doubleClick() + await button.doubleClick() } ``` ### UiComponent.longClick -longClick():Promise\; +longClick(): Promise\ Long-clicks this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -429,23 +372,21 @@ async function demo() { ### UiComponent.getId -getId():Promise\; +getId(): Promise\ Obtains the ID of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\; | Promise used to return the component ID.| +| Type | Description | +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the ID of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -455,23 +396,21 @@ async function demo() { ### UiComponent.getKey -getKey():Promise\; +getKey(): Promise\ Obtains the key of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | -------------------------- | -| Promise\; | Promise used to return the component key.| +| Type | Description | +| ---------------- | ------------------------------ | +| Promise\ | Promise used to return the key of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -481,23 +420,21 @@ async function demo() { ### UiComponent.getText -getText():Promise\; +getText(): Promise\ Obtains the text information of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise\; | Promise used to return the text information of the component.| +| Type | Description | +| ---------------- | --------------------------------- | +| Promise\ | Promise used to return the text information of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -507,23 +444,21 @@ async function demo() { ### UiComponent.getType -getType():Promise\; +getType(): Promise\ Obtains the type of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ---------------- | ------------------------------- | -| Promise\; | Promise used to return the component type.| +| Type | Description | +| ---------------- | ----------------------------- | +| Promise\ | Promise used to return the type of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -533,23 +468,21 @@ async function demo() { ### UiComponent.isClickable -isClickable():Promise\; +isClickable(): Promise\ Obtains the clickable status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise\; | Promise used to return the clickable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the clickable status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -564,23 +497,21 @@ async function demo() { ### UiComponent.isScrollable -isScrollable():Promise\; +isScrollable(): Promise\ Obtains the scrollable status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise\; | Promise used to return the scrollable status of the component.| +| Type | Description | +| -------------- | ------------------------------------- | +| Promise\ | Promise used to return the scrollable status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let scrollBar = await driver.findComponent(BY.scrollable(true)) @@ -596,23 +527,21 @@ async function demo() { ### UiComponent.isEnabled -isEnabled():Promise\; - -Obtains the enable status of this component. +isEnabled(): Promise\ -**Required permissions**: none +Obtains the enabled status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------- | -| Promise\; | Promise used to return the enable status of the component.| +| Type | Description | +| -------------- | ------------------------------- | +| Promise\ | Promise used to return the enabled status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -628,23 +557,21 @@ async function demo() { ### UiComponent.isFocused -isFocused():Promise\; +isFocused(): Promise\ Obtains the focused status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | --------------------------------- | -| Promise\; | Promise used to return the focused status of the component.| +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the focused status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -659,23 +586,21 @@ async function demo() { ### UiComponent.isSelected -isSelected():Promise\; +isSelected(): Promise\ Obtains the selected status of this component. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise\; | Promise used to return the selected status of the component.| +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the selected status of the component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.type('button')) @@ -690,37 +615,33 @@ async function demo() { ### UiComponent.inputText -inputText(text: string):Promise\; +inputText(text: string): Promise\ Enters text into this component (available for text boxes). -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------- | -| text | string | Yes | Text to be entered to the component.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Text to enter.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.inputText('next page') + let text = await driver.findComponent(BY.text('hello world')) + await text.inputText('123') } ``` ### UiComponent.scrollSearch -scrollSearch(by:By):Promise\; +scrollSearch(by: By): Promise\ -Scrolls on this component to search for the target component (available for lists). - -**Required permissions**: none +Scrolls on this component to search for the target component (applicable to component that support scrolling, such as **\**). **System capability**: SystemCapability.Test.UiTest @@ -732,16 +653,16 @@ Scrolls on this component to search for the target component (available for list **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise\; | Promise used to return the target component.| +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise\ | Promise used to return the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let scrollBar = await driver.findComponent(BY.type('Scroll')) let button = await scrollBar.scrollSearch(BY.text('next page')) } ``` @@ -753,23 +674,21 @@ All APIs provided by this class, except for **UiDriver.create()**, use a promise ### UiDriver.create -static create():UiDriver; +static create(): UiDriver Creates a **UiDriver** object and returns the object created. This API is a static API. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| ------- | ---------------------- | +| Type | Description | +| ------- | ------------------------ | | UiDrive | Returns the **UiDriver** object created.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() } @@ -777,23 +696,21 @@ async function demo() { ### UiDriver.delayMs -delayMs(duration:number):Promise\; +delayMs(duration: number): Promise\ Delays this **UiDriver** object within the specified duration. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------- | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | | duration | number | Yes | Duration of time.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.delayMs(1000) @@ -802,29 +719,27 @@ async function demo() { ### UiDriver.findComponent -findComponent(by:By):Promise\; +findComponent(by: By): Promise\ -Searches this **UiDriver** object for the target component that has the given attributes. - -**Required permissions**: none +Searches this **UiDriver** object for the target component that matches the given attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | -| Promise\; | Promise used to return the found component.| +| Type | Description | +| --------------------- | --------------------------------- | +| Promise\ | Promise used to return the found component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let button = await driver.findComponent(BY.text('next page')) @@ -833,29 +748,27 @@ async function demo() { ### UiDriver.findComponents -findComponents(by:By):Promise\>; +findComponents(by: By): Promise\> Searches this **UiDriver** object for all components that match the given attributes. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------------------- | -| Promise\>; | Promise used to return a list of found components.| +| Type | Description | +| ----------------------------- | --------------------------------------- | +| Promise\> | Promise used to return a list of found components.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() let buttonList = await driver.findComponents(BY.text('next page')) @@ -864,23 +777,21 @@ async function demo() { ### UiDriver.assertComponentExist -assertComponentExist(by:By):Promise\; +assertComponentExist(by: By): Promise\ Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------ | +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | | by | By | Yes | Attributes of the target component.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.assertComponentExist(BY.text('next page')) @@ -889,17 +800,15 @@ async function demo() { ### UiDriver.pressBack -pressBack():Promise\; +pressBack(): Promise\ Presses the Back button on this **UiDriver** object. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.pressBack() @@ -908,23 +817,21 @@ async function demo() { ### UiDriver.triggerKey -triggerKey(keyCode:number):Promise\; +triggerKey(keyCode: number): Promise\ Triggers the key of this **UiDriver** object that matches the given key code. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------- | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------- | | keyCode | number | Yes | Key code.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.triggerKey(123) @@ -933,23 +840,22 @@ async function demo() { ### UiDriver.click -click(x:number,y:number):Promise\; +click(x: number, y: number): Promise\ Clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.click(100,100) @@ -958,23 +864,22 @@ async function demo() { ### UiDriver.doubleClick -doubleClick(x:number,y:number):Promise\; +doubleClick(x: number, y: number): Promise\ Double-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.doubleClick(100,100) @@ -983,23 +888,22 @@ async function demo() { ### UiDriver.longClick -longClick(x:number,y:number):Promise\; +longClick(x: number, y: number): Promise\ Long-clicks a specific point of this **UiDriver** object based on the given coordinates. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------- | ---- | ------------------------------------------- | -| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X coordinate of the target point.| +| y | number | Yes | Y coordinate of the target point.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.longClick(100,100) @@ -1008,24 +912,24 @@ async function demo() { ### UiDriver.swipe -swipe(startx:number,starty:number,endx:number,endy:number):Promise\; - -Swipes from the start point to the end point of this **UiDriver** object based on the given coordinates. +swipe(startx: number, starty: number, endx: number, endy: number): Promise\ -**Required permissions**: none +Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------- | ---- | ------------------------------------------- | -| startx,starty | number,number | Yes | Coordinate information of the start point in the (number,number) format.| -| endx,endy | number,number | Yes | Coordinate information of the end point in the (number,number) format.| +| 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.| **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.swipe(100,100,200,200) @@ -1034,25 +938,44 @@ async function demo() { ### UiDriver.screenCap -screenCap(savePath:string):Promise\; +screenCap(savePath: string): Promise\ Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. -**Required permissions**: none - **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | | savePath | string | Yes | File save path.| +**Return value** + +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| + **Example** -``` +```js async function demo() { let driver = UiDriver.create() await driver.screenCap('/local/tmp/') } ``` + +## MatchPattern + +Enumerates the match patterns supported for component attributes. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | 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-update.md b/en/application-dev/reference/apis/js-apis-update.md index d84b4bdcd5acbe6169c8172961f935f254f5a7d2..251c1d59b610f4d01372186d0e40d0521cf62ca8 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -134,11 +134,11 @@ Obtains the new version information. This function uses an asynchronous callback **Example** ``` -update.getNewVersionInfo(info => { +updater.getNewVersionInfo(info => { console.log("getNewVersionInfo success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -160,9 +160,9 @@ Obtains the new version information. This function uses a promise to return the ``` updater.getNewVersionInfo().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); + console.log(`info versionName = ` + value.checkResult[0].versionName); + console.log(`info versionCode = ` + value.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); }).catch(err => { console.log("getNewVersionInfo promise error: " + err.code); }); @@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro **Example** ``` -update.checkNewVersion(info => { +updater.checkNewVersion(info => { console.log("checkNewVersion success " + info.status); - console.log(`info versionName = ` + info.result[0].versionName); - console.log(`info versionCode = ` + info.result[0].versionCode); - console.log(`info verifyInfo = ` + info.result[0].verifyInfo); + console.log(`info versionName = ` + info.checkResult[0].versionName); + console.log(`info versionCode = ` + info.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); }); ``` @@ -210,10 +210,10 @@ Checks whether the current version is the latest. This function uses a promise t **Example** ``` -update.checkNewVersion().then(value => { - console.log(`info versionName = ` + value.result[0].versionName); - console.log(`info versionCode = ` + value.result[0].versionCode); - console.log(`info verifyInfo = ` + value.result[0].verifyInfo); +updater.checkNewVersion().then(value => { + console.log(`info versionName = ` + value.checkResult[0].versionName); + console.log(`info versionCode = ` + value.checkResult[0].versionCode); + console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); }).catch(err => { console.log("checkNewVersion promise error: " + err.code); }); @@ -237,13 +237,13 @@ Verifies whether the update package is valid. **Example** ``` -update.on("verifyProgress", callback => { +updater.on("verifyProgress", callback => { console.info('on verifyProgress ' + callback.percent); }); update.verifyUpdatePackage("XXX", "XXX"); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(): Promise\ @@ -260,14 +260,14 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData().then(result => { +updater.rebootAndCleanUserData().then(result => { console.log("rebootAndCleanUserData " + result); }).catch(err => { console.info("rebootAndCleanUserData promise error: " + err.code); }); ``` -### rebootAndCleanUserData +### rebootAndCleanUserData8+ rebootAndCleanUserData(callback: AsyncCallback\): void @@ -284,7 +284,7 @@ Reboots the device and clears the user partition data. This function uses a prom **Example** ``` -update.rebootAndCleanUserData(result => { +updater.rebootAndCleanUserData(result => { console.log("rebootAndCleanUserData ", result) }); ``` @@ -306,7 +306,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion().then(result => { +updater.applyNewVersion().then(result => { console.log("appVewVersion ", result) }).catch(err => { console.info("applyNewVersion promise error: " + err.code); @@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result. **Example** ``` -update.applyNewVersion(result => { +updater.applyNewVersion(result => { console.log("applyNewVersion ", result) }); ``` @@ -399,7 +399,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy, result => { +updater.setUpdatePolicy(policy, result => { console.log("setUpdatePolicy ", result) }); ``` @@ -434,7 +434,7 @@ let policy = { autoUpgradeInterval: [ 2, 3 ], autoUpgradeCondition: 2 } -update.setUpdatePolicy(policy).then(result => +updater.setUpdatePolicy(policy).then(result => console.log("setUpdatePolicy ", result) ).catch(err => { console.log("setUpdatePolicy promise error: " + err.code); @@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return **Example** ``` -update.getUpdatePolicy(policy => { +updater.getUpdatePolicy(policy => { console.log("getUpdatePolicy success"); console.log(`policy autoDownload = ` + policy.autoDownload); console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); @@ -483,7 +483,7 @@ Obtains the update policy. This function uses a promise to return the result. **Example** ``` -update.getUpdatePolicy().then(value => { +updater.getUpdatePolicy().then(value => { console.log(`info autoDownload = ` + value.autoDownload); console.log(`info autoDownloadNet = ` + value.autoDownloadNet); console.log(`info mode = ` + value.mode); diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 1251c4b6d0a6cb4b9f88b555101e230972906b05..fa467916b3a3d81eb0e23bbdc03c737fcf96b7f0 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -1,12 +1,13 @@ # Vibrator -> ![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 vibrator from '@ohos.vibrator'; ``` @@ -23,18 +24,18 @@ Triggers vibration with a specific duration. This API uses a promise to return t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ------ | ---- | ------------ | -| duration | number | Yes | Vibration duration.| +| duration | number | Yes | Vibration duration. | **Return value** -| Type | Description | +| Type | Description | | ------------------- | ----------- | -| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully. | **Example** - ``` + ```js vibrator.vibrate(1000).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -54,13 +55,13 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ----------------------- | -| duration | number | Yes | Vibration duration. | -| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| +| duration | number | Yes | Vibration duration. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully. | **Example** - ``` + ```js vibrator.vibrate(1000,function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); @@ -82,17 +83,17 @@ Triggers vibration with a specific effect. This API uses a promise to return the **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | ------------- | -| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect.| +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | **Return value** -| Type | Description | +| Type | Description | | ------------------- | ----------- | -| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully. | **Example** - ``` + ```js vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -112,13 +113,13 @@ Triggers vibration with a specific effect. This API uses an asynchronous callbac **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ----------------------- | -| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | -| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully. | **Example** - ``` + ```js vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); @@ -140,17 +141,17 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ------------------------------------- | ---- | --------------- | -| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop.| +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | **Return value** -| Type | Description | +| Type | Description | | ------------------- | ----------- | -| Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| +| Promise<void> | Promise used to indicate whether the vibration is stopped successfully. | **Example** - ``` + ```js vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ console.log("Promise returned to indicate a successful vibration."); }, (error)=>{ @@ -170,18 +171,18 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ------------------------------------- | ---- | ----------------------- | -| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | -| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully.| +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully. | **Example** - ``` + ```js vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ if(error){ console.log("error.code"+error.code+"error.message"+error.message); }else{ - console.log("Callback returned to indicate a successful stop."); + console.log("Callback returned to indicate successful."); } }) ``` @@ -193,9 +194,9 @@ Describes the vibration effect. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value | Description | -| ------------------ | -------------------- | --------------- | -| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| +| Name | Default Value | Description | +| ------------------ | -------------------- | --------------------------------------------------------------- | +| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer. | ## VibratorStopMode @@ -204,7 +205,7 @@ Describes the vibration mode to stop. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value | Description | +| Name | Default Value | Description | | ------------------------- | -------- | ---------------------------------------- | -| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| -| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| +| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type. | +| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type. | diff --git a/en/application-dev/reference/apis/js-apis-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index bac1ca14ac8c99b1dd223a31e916218fbbb6d377..fbe459992c0eff76a99d15ad8116913f761ad892 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -6,7 +6,7 @@ > - 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 APIs to implement volume and disk management, including obtaining volume information, mounting and unmounting volumes, partitioning disks, and formatting volumes. +Performs volume and disk management, including obtaining volume information, mounting and unmounting volumes, partitioning disks, and formatting volumes. ## Modules to Import @@ -54,7 +54,7 @@ Asynchronously obtains information about all available volumes. This API uses a ```js let uuid = ""; - volumemanager.getAllVolumes(uuid, function(error, volumes){ + volumemanager.getAllVolumes(function(error, volumes){ // do something }); ``` diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 8e0038daacc3d195b5642c2518dfa926afaff517..f0f1f6aae440f88f613f82862fcc34e33ed9d8e9 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,8 +1,7 @@ # Wallpaper -> ![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. -> +> **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 @@ -29,18 +28,18 @@ Defines the wallpaper type. getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void -Obtains the main color information of the wallpaper of a specified type. +Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper -- Parameters - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | - | callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes | Callback used to return the main color information of the wallpaper. | +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes | Callback used to return the main color information of the wallpaper. | + +**Example** -- Example - ```js wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { if (error) { @@ -56,7 +55,7 @@ Obtains the main color information of the wallpaper of a specified type. getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> -Obtains the main color information of the wallpaper of a specified type. +Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -74,20 +73,20 @@ Obtains the main color information of the wallpaper of a specified type. **Example** -```js -wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getColors.`); -}).catch((error) => { - console.error(`failed to getColors because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getColors.`); + }).catch((error) => { + console.error(`failed to getColors because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getId getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Obtains the ID of the wallpaper of the specified type. +Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -100,25 +99,26 @@ Obtains the ID of the wallpaper of the specified type. **Example** -```js -wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getId because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getId: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getId because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getId: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getId getId(wallpaperType: WallpaperType): Promise<number> -Obtains the ID of the wallpaper of the specified type. +Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper + **Parameters** | Name | Type | Mandatory | Description | @@ -133,20 +133,20 @@ Obtains the ID of the wallpaper of the specified type. **Example** -```js -wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getId: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getId because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getId: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getId because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getMinHeight getMinHeight(callback: AsyncCallback<number>): void -Obtains the minimum height of the wallpaper. +Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -158,25 +158,26 @@ Obtains the minimum height of the wallpaper. **Example** -```js -wallpaper.getMinHeight((error, data) => { - if (error) { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinHeight: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getMinHeight((error, data) => { + if (error) { + console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getMinHeight: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getMinHeight getMinHeight(): Promise<number> -Obtains the minimum height of the wallpaper. +Obtains the minimum height of this wallpaper. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper + **Return value** | Type | Description | @@ -185,20 +186,20 @@ Obtains the minimum height of the wallpaper. **Example** -```js -wallpaper.getMinHeight().then((data) => { - console.log(`success to getMinHeight: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getMinHeight().then((data) => { + console.log(`success to getMinHeight: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.getMinWidth getMinWidth(callback: AsyncCallback<number>): void -Obtains the minimum width of the wallpaper. +Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -210,22 +211,22 @@ Obtains the minimum width of the wallpaper. **Example** -```js -wallpaper.getMinWidth((error, data) => { - if (error) { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinWidth: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getMinWidth((error, data) => { + if (error) { + console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getMinWidth: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getMinWidth getMinWidth(): Promise<number> -Obtains the minimum width of the wallpaper. +Obtains the minimum width of this wallpaper. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -237,20 +238,20 @@ Obtains the minimum width of the wallpaper. **Example** -```js -wallpaper.getMinWidth().then((data) => { - console.log(`success to getMinWidth: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getMinWidth().then((data) => { + console.log(`success to getMinWidth: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.isChangePermitted isChangePermitted(callback: AsyncCallback<boolean>): void -Checks whether to allow the application to change the wallpaper for the current user. +Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -258,26 +259,26 @@ Checks whether to allow the application to change the wallpaper for the current | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the queried result. Returns **true** if it is allowed; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | **Example** -```js -wallpaper.isChangePermitted((error, data) => { - if (error) { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.isChangePermitted((error, data) => { + if (error) { + console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); + return; + } + console.log(`success to isChangePermitted: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.isChangePermitted isChangePermitted(): Promise<boolean> -Checks whether to allow the application to change the wallpaper for the current user. +Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -285,24 +286,24 @@ Checks whether to allow the application to change the wallpaper for the current | Type | Description | | -------- | -------- | -| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. Returns **true** if it is allowed; returns **false** otherwise. | +| Promise<boolean> | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | **Example** -```js -wallpaper.isChangePermitted().then((data) => { - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.isChangePermitted().then((data) => { + console.log(`success to isChangePermitted: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.isOperationAllowed isOperationAllowed(callback: AsyncCallback<boolean>): void -Checks whether the user is allowed to set wallpapers. +Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -310,26 +311,26 @@ Checks whether the user is allowed to set wallpapers. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the user is allowed to set wallpapers. Returns **true** if it is allowed; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | **Example** -```js -wallpaper.isOperationAllowed((error, data) => { - if (error) { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.isOperationAllowed((error, data) => { + if (error) { + console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); + return; + } + console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.isOperationAllowed isOperationAllowed(): Promise<boolean> -Checks whether the user is allowed to set wallpapers. +Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -337,26 +338,26 @@ Checks whether the user is allowed to set wallpapers. | Type | Description | | -------- | -------- | -| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. Returns **true** if it is allowed; returns **false** otherwise. | +| Promise<boolean> | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | **Example** -```js -wallpaper.isOperationAllowed().then((data) => { - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.isOperationAllowed().then((data) => { + console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.reset reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Removes a wallpaper of the specified type and restores the default one. +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -365,28 +366,28 @@ Removes a wallpaper of the specified type and restores the default one. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | **Example** -```js -wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to reset because: ` + JSON.stringify(error)); - return; - } - console.log(`success to reset.`); -}); -``` + ```js + wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to reset because: ` + JSON.stringify(error)); + return; + } + console.log(`success to reset.`); + }); + ``` ## wallpaper.reset reset(wallpaperType: WallpaperType): Promise<void> -Removes a wallpaper of the specified type and restores the default one. +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -400,26 +401,26 @@ Removes a wallpaper of the specified type and restores the default one. | Type | Description | | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned. | +| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | **Example** -```js -wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to reset.`); -}).catch((error) => { - console.error(`failed to reset because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to reset.`); + }).catch((error) => { + console.error(`failed to reset because: ` + JSON.stringify(error)); + }); + ``` ## wallpaper.setWallpaper setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Sets a specified source as the wallpaper of a specified type. +Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -427,7 +428,7 @@ Sets a specified source as the wallpaper of a specified type. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | Uri path of the JPEG or PNG file, or bitmap of the PNG file. | +| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI of a JPEG or PNG file, or bitmap of a PNG file. | | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned. | @@ -471,9 +472,9 @@ imageSource.createPixelMap(opts).then((pixelMap) => { setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -Sets a specified source as the wallpaper of a specified type. +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -**Required permission**: ohos.permission.SET_WALLPAPER +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -481,7 +482,7 @@ Sets a specified source as the wallpaper of a specified type. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | Uri path of the JPEG or PNG file, or bitmap of the PNG file. | +| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI path of the JPEG or PNG file, or bitmap of the PNG file. | | wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | **Return value** @@ -525,7 +526,7 @@ imageSource.createPixelMap(opts).then((pixelMap) => { getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Obtains the wallpaper of the specified type. +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 @@ -540,21 +541,21 @@ Obtains the wallpaper of the specified type. **Example** -```js -wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getFile: ` + JSON.stringify(data)); -}); -``` + ```js + wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getFile because: ` + JSON.stringify(error)); + return; + } + console.log(`success to getFile: ` + JSON.stringify(data)); + }); + ``` ## wallpaper.getFile8+ getFile(wallpaperType: WallpaperType): Promise<number> -Obtains the wallpaper of the specified type. +Obtains the wallpaper of the specified type. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE @@ -574,13 +575,75 @@ Obtains the wallpaper of the specified type. **Example** -```js -wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getFile: ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to getFile because: ` + JSON.stringify(error)); -}); -``` + ```js + wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getFile: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to getFile because: ` + JSON.stringify(error)); + }); + ``` + + +## wallpaper.getPixelMap + +getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; + +Obtains the pixel image for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| + +**Example** + + ```js + wallpaper.getPixelMap(WALLPAPER_SYSTEM, function (err, data) { + console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err)); + console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data)); + }); + ``` + + +## wallpaper.getPixelMap + +getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> + +Obtains the pixel image for the wallpaper of the specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WALLPAPER and ohos.permission.READ_USER_STORAGE + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| + +**Example** + + ```js + wallpaper.getPixelMap(WALLPAPER_SYSTEM).then((data) => { + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); + }).catch((err) => { + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err); + console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err)); + }); + ``` ## wallpaper.on('colorChange') @@ -596,7 +659,7 @@ Subscribes to the wallpaper color change event. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Type of the event to subscribe to. The value **colorChange** indicates subscribing to the wallpaper color change event. | -| callback | function | Yes | Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| callback | function | Yes | Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | **Example** @@ -621,7 +684,7 @@ Unsubscribes from the wallpaper color change event. | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | | type | string | Yes | Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event. | -| callback | function | No | Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| callback | function | No | Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index d3d17810360c3ffa6074118413daddcb67fce31f..49cc55c70d32de63dcb415abcf359d93f351253d 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,4 +1,4 @@ -# WantAgent Module +# WantAgent >**NOTE** > @@ -916,6 +916,135 @@ WantAgent.equal(wantAgent1, wantAgent2).then((data) => { ``` +## WantAgent.getOperationType9+ + +getOperationType(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the operation type of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Readable | Writable | Type | Mandatory | Description | +| ---------- | --- | ---- | --------- | ---- | ------------- | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the operation type. | + +**Example** + +```js +import WantAgent from '@ohos.wantAgent'; + +//wantAgent���� +var wantAgent; + +//WantAgentInfo���� +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.getOperationType(wantAgent, (OperationType) => { + console.log('----------- getOperationType ----------, OperationType: ' + OperationType); +}) +``` + + +## WantAgent.getOperationType9+ + +getOperationType(agent: WantAgent): Promise\ + +Obtains the operation type of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Readable | Writable | Type | Mandatory | Description | +| ---------- | --- | ---- | --------- | ---- | ------------- | +| agent | Yes | No | WantAgent | Yes | WantAgent���� | + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------ | +| Promise\ | Promise used to return the operation type. | + + +**Example** + +```js +import WantAgent from '@ohos.wantAgent'; + +//wantAgent���� +var wantAgent; + +//WantAgentInfo���� +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.getOperationType(wantAgent).then((OperationType) => { + console.log('getOperationType success, OperationType: ' + OperationType); +}).catch((err) => { + console.log('getOperationType fail, err: ' + err); +}) +``` + ## WantAgentInfo diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 14bb5717368e047abb3c68775799b056071a607e..1192097ac4b6daa8b88331ae09fb98d6c8697384 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,4 +1,4 @@ -# Zip Module (JavaScript SDK APIs) +# Zip ## Constraints None @@ -9,7 +9,7 @@ import zlib from '@ohos.zlib'; ``` ## zlib.zipFile -zipFile(inFile:string, outFile:string, options: Options): Promise\; +zipFile(inFile:string, outFile:string, options: Options): Promise\ Zips a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib @@ -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\ Unzips a file. This API uses a promise to return the result. 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 1371eb6a7d7057f30804b8e65aea6ed8b42fc76f..be89c5eafdfd65d36cccf0338c7e10523322a68e 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 @@ -2,7 +2,7 @@ An entrance piece that can contain images and text. It is usually used to display receivers, for example, email recipients or message recipients. -## Child Component +## Child Components None 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 708a05414599781f9489b912961e4857464e7a32..7b69be3ec4127e4b416314452f4d4ded85cd67bd 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 @@ -2,7 +2,7 @@ The **\** component is used to quickly adjust settings, such as volume and brightness. -## Child Component +## Child Components Not supported 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 f849e001599c599eac36e698f71b855874d722dc..9dceb0f89dc7d0c9ae4f4c9db57d4380b0c29b96 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 @@ -6,7 +6,7 @@ The **\** component is used to enable or disable a function. None -## Child Component +## Child Components None 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 34e0439b5c0fb19a0d7e48b37ed00c23ed9fa1a7..e5a4846b529559a756505a69d23c4a1427329083 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 @@ -6,7 +6,7 @@ The **\