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/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/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/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index edfd0cdebacd91718def3e8f5c474ef714ad6c15..651ac2b64fa7d7e7cd815e09cd0e9d0514179755 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -8,7 +8,7 @@ In Host mode, you can obtain the list of connected devices, enable or disable th The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. -The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). +The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md). **Table 1** Open USB APIs 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-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 28de5b5c1a3e6d9df575ea430d69a15b5bce8e23..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. 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-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-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 07190f596f3c87a8b89e570b6462ccbb574ea286..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 @@ -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 | 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**.| + | 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) }); ``` @@ -211,8 +236,8 @@ Creates a file in the specified path in asynchronous mode. This API uses a callb | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------- | - | filename | string | Yes | Name of the file to create. | - | path | string | 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) => { 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 22fa37bc3944adfccc45b02b30c17c2a04eb2558..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. 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-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index 15b389bc3a7a989af6a43c852c52e539b79f2fca..4d45271a8791a8370ed4950c75ac96c0fb408b8c 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,7 +1,6 @@ # HiLog The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. -This document describes only API functions. For details about log printing requirements, see [Logging Guide](../../../contribute/OpenHarmony-Log-guide.md). > **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. @@ -42,7 +41,7 @@ hilog.isLoggable(0x0001, "testTag", hilog.LogLevel.INFO); ## LogLevel -Log level. +Enumerates the log levels. **System capability**: SystemCapability.HiviewDFX.HiLog @@ -70,7 +69,7 @@ DEBUG logs are not recorded in official versions by default. They are available | ------ | ------ | ---- | ------------------------------------------------------------ | | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| -| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by \.| +| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -101,7 +100,7 @@ Prints INFO logs. | ------ | ------ | ---- | ------------------------------------------------------------ | | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| -| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by \.| +| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -132,7 +131,7 @@ Prints WARN logs. | ------ | ------ | ---- | ------------------------------------------------------------ | | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| -| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by \.| +| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -163,7 +162,7 @@ Prints ERROR logs. | ------ | ------ | ---- | ------------------------------------------------------------ | | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| -| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by \.| +| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -194,7 +193,7 @@ Prints FATAL logs. | ------ | ------ | ---- | ------------------------------------------------------------ | | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| -| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by \.| +| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.
Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by ****.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index eca20fafe0a0510de5543a7fc777839c0c99862b..b5d06d979b5a7a6d29a3bff59cf5d91792bc1562 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -34,19 +34,9 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to **Example** ```js -export default { - data: { - deviceIds: Array, - }, - callback: function(ids) { - this.deviceIds = ids; - }, - testGetDeviceIds: function () { - console.info("InputDeviceJsTest---start---testGetDeviceIds"); - inputDevice.getDeviceIds(this.callback); - console.info("InputDeviceJsTest---end---testGetDeviceIds"); - } -} +inputDevice.getDeviceIds((ids)=>{ + console.log("The device ID list is: " + ids); +}); ``` ## inputDevice.getDeviceIds @@ -61,22 +51,14 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu | Parameter | Description | | ---------------------- | ------------------ | -| Promise> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** ```js -export default { - testGetDeviceIds: function () { - console.info("InputDeviceJsTest---start---testGetDeviceIds"); - let promise = inputDevice.getDeviceIds(); - promise.then((data)=> { - console.info('GetDeviceIds successed, Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed GetDeviceIds. Cause: ' + JSON.stringify(err)); - }); - } -} +inputDevice.getDeviceIds().then((ids)=>{ + console.log("The device ID list is: " + ids); +}); ``` @@ -101,23 +83,10 @@ Obtains the information about an input device. This API uses an asynchronous cal **Example** ```js -export default { - InputDeviceData: { - deviceId : 0, - name : "NA", - sources : Array, - axisRanges : Array, - }, - callback: function(deviceData) { - this.InputDeviceData = deviceData; - }, - testGetDevice: function () { - // The example is used to obtain the information about the device whose ID is 1. - console.info("InputDeviceJsTest---start---testGetDevice"); - inputDevice.getDevice(1, this.callback); - console.info("InputDeviceJsTest---end---testGetDevice"); - } -} +// This example obtains the information about the device whose ID is 1. +inputDevice.getDevice(1, (inputDevice)=>{ + console.log("The device name is: " + inputDevice.name); +}); ``` ## inputDevice.getDevice @@ -137,24 +106,10 @@ Obtains the information about an input device. This API uses a promise to return **Example** ```js -export default { - InputDeviceData: { - deviceId : 0, - name : "NA", - sources : Array, - axisRanges : Array, - }, - testGetDevice: function () { - // The example is used to obtain the information about the device whose ID is 1. - console.info("InputDeviceJsTest---start---testGetDevice"); - let promise = inputDevice.getDevice(1); - promise.then((data)=> { - console.info('GetDeviceId successed, Data: ' + JSON.stringify(data)) - }).catch((err)=>{ - console.error('Failed GetDeviceId. Cause: ' + JSON.stringify(err)); - }); - } -} +// This example obtains the information about the device whose ID is 1. +inputDevice.getDevice(1).then((inputDevice)=>{ + console.log("The device name is: " + inputDevice.name); +}); ``` @@ -191,7 +146,7 @@ Defines the axis information of an input device. | Name | Type | Description | | ------ | ------------------------- | -------- | | source | [SourceType](#sourcetype) | Input source type of the axis.| -| axis | [AxisType](axistype) | Axis type. | +| axis | [AxisType](#axistype) | Axis type. | | max | number | Maximum value reported by the axis. | | min | number | Minimum value reported by the axis. | 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 99c01b7456afd94b571ad3bb3d7dd1ced3a37953..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 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-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-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 468091db605fd24ac24887c126238cea264c3a52..86d29eebedf8fb206589a7770a92362a79873c69 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -7,7 +7,7 @@ ## Modules to Import -``` +```js import radio from '@ohos.telephony.radio' ``` @@ -30,7 +30,7 @@ Obtains the radio access technology (RAT) used by the CS and PS domains. This AP **Example** -``` +```js let slotId = 0; radio.getRadioTech(slotId, (err, data) =>{ console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -62,7 +62,7 @@ Obtains the RAT used by the CS and PS domains. This API uses a promise to return **Example** -``` +```js let slotId = 0; let promise = radio.getRadioTech(slotId); promise.then(data => { @@ -91,7 +91,7 @@ Obtains the network status. This API uses an asynchronous callback to return the **Example** -``` +```js radio.getNetworkState((err, data) =>{ console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -117,7 +117,7 @@ Obtains the network status. This API uses an asynchronous callback to return the **Example** -``` +```js let slotId = 0; radio.getNetworkState(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -149,7 +149,7 @@ Obtains the network status of the SIM card in the specified slot. This API uses **Example** -``` +```js let slotId = 0; let promise = radio.getNetworkState(slotId); promise.then(data => { @@ -177,7 +177,7 @@ Obtains the network selection mode of the SIM card in the specified slot. This A **Example** -``` +```js let slotId = 0; radio.getNetworkSelectionMode(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -207,7 +207,7 @@ Obtains the network selection mode of the SIM card in the specified slot. This A **Example** -``` +```js let slotId = 0; let promise = radio.getNetworkSelectionMode(slotId); promise.then(data => { @@ -235,7 +235,7 @@ Obtains the ISO country code of the network with which the SIM card in the speci **Example** -``` +```js let slotId = 0; radio.getISOCountryCodeForNetwork(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -265,7 +265,7 @@ Obtains the ISO country code of the network with which the SIM card in the speci **Example** -``` +```js let slotId = 0; let promise = radio.getISOCountryCodeForNetwork(slotId); promise.then(data => { @@ -292,7 +292,7 @@ Obtains the ID of the slot in which the primary card is located. This API uses a **Example** -``` +```js radio.getPrimarySlotId((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -315,7 +315,7 @@ Obtains the ID of the slot in which the primary card is located. This API uses a **Example** -``` +```js let promise = radio.getPrimarySlotId(); promise.then(data => { console.log(`getPrimarySlotId success, promise: data->${JSON.stringify(data)}`); @@ -342,7 +342,7 @@ Obtains a list of signal strengths of the network with which the SIM card in the **Example** -``` +```js let slotId = 0; radio.getSignalInformation(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -372,7 +372,7 @@ Obtains a list of signal strengths of the network with which the SIM card in the **Example** -``` +```js let slotId = 0; let promise = radio.getSignalInformation(slotId); promise.then(data => { @@ -405,10 +405,10 @@ Checks whether the current device supports 5G \(NR\). **Example** -``` +```js let slotId = 0; let result = radio.isNrSupported(slotId); -console.log(result); +console.log("Result: "+ result); ``` @@ -430,7 +430,7 @@ Checks whether the radio service is enabled on the primary SIM card. This API us **Example** -``` +```js radio.isRadioOn((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -456,7 +456,7 @@ Checks whether the radio service is enabled on the SIM card in the specified slo **Example** -``` +```js let slotId = 0; radio.isRadioOn(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -488,7 +488,7 @@ Checks whether the radio service is enabled. This API uses a promise to return t **Example** -``` +```js let slotId = 0; let promise = radio.isRadioOn(slotId); promise.then(data => { @@ -516,7 +516,7 @@ Obtains the carrier name. This API uses an asynchronous callback to return the r **Example** -``` +```js let slotId = 0; radio.getOperatorName(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -546,7 +546,7 @@ Obtains the carrier name. This API uses a promise to return the result. **Example** -``` +```js let slotId = 0; let promise = radio.getOperatorName(slotId); promise.then(data => { diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index fec9be3f8e6b9e7cf42f741f357710c99650c2c3..256be1a80f2dce94e12538ad5c5c97876bdac634 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -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. | diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index b038cd0f9b2e376b6e2d76fe096c1d4d9aefec13..aab544f7f78bd2b755ab24443aa1d0acd5d683c1 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -11,8 +11,9 @@ 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 @@ -41,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 @@ -70,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 @@ -102,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 @@ -129,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 @@ -158,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 @@ -190,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 @@ -215,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 @@ -242,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 @@ -269,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 @@ -294,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 @@ -321,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 @@ -351,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 @@ -376,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 @@ -401,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 @@ -426,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 @@ -451,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 @@ -476,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 @@ -503,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 @@ -530,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 @@ -557,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 @@ -582,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 @@ -609,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 @@ -636,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 @@ -666,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 @@ -691,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 @@ -718,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 @@ -748,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 @@ -771,8 +749,7 @@ Subscribes to only one data change of the significant motion sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +### PEDOMETER_DETECTION once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<PedometerDetectionResponse>): void @@ -796,8 +773,7 @@ Subscribes to only one data change of the pedometer detection sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) +### PEDOMETER once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerResponse>): void @@ -821,8 +797,7 @@ Subscribes to only one data change of the pedometer sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +### AMBIENT_TEMPERATURE once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<AmbientTemperatureResponse>): void @@ -844,8 +819,7 @@ Subscribes to only one data change of the ambient temperature sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +### MAGNETIC_FIELD once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void @@ -869,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 @@ -897,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 @@ -924,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 @@ -947,8 +918,7 @@ Subscribes to only one data change of the humidity sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) +### BAROMETER once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerResponse>): void @@ -970,8 +940,7 @@ Subscribes to only one data change of the barometer sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) +### HALL once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>): void @@ -993,8 +962,7 @@ Subscribes to only one data change of the Hall effect sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +### AMBIENT_LIGHT once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightResponse>): void @@ -1016,8 +984,7 @@ Subscribes to only one data change of the ambient light sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) +### ORIENTATION once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<OrientationResponse>): void @@ -1041,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 @@ -1067,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 @@ -1092,8 +1057,7 @@ Subscribes to only one data change of the heart rate sensor. ); ``` - -## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +### WEAR_DETECTION once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void @@ -1115,7 +1079,9 @@ Subscribes to only one data change of the wear detection sensor. ); ``` -## sensor.off(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.off + +### ACCELEROMETER off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void @@ -1143,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 @@ -1174,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 @@ -1198,7 +1164,7 @@ function callback(data) { 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 @@ -1222,7 +1188,7 @@ function callback(data) { 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 @@ -1246,7 +1212,7 @@ function callback(data) { 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 @@ -1272,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 @@ -1300,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 @@ -1328,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 @@ -1352,7 +1318,7 @@ function callback(data) { 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 @@ -1378,7 +1344,7 @@ function callback(data) { 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 @@ -1404,7 +1370,7 @@ function callback(data) { 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 @@ -1432,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 @@ -1460,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 @@ -1489,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 @@ -1515,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 @@ -1539,7 +1505,7 @@ function callback(data) { 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 @@ -1565,7 +1531,7 @@ function callback(data) { 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 @@ -1589,7 +1555,7 @@ function callback(data) { 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 @@ -1616,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 @@ -1640,7 +1606,7 @@ function callback(data) { 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 @@ -1773,10 +1739,9 @@ 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.| - -**Example** +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field. | +**Example** ```js const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); promise.then((data) => { @@ -1936,7 +1901,7 @@ Obtains the angle change between two rotation matrices. This API uses a callback } 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]); } }) ``` @@ -1970,10 +1935,10 @@ Obtains the angle change between two rotation matrices. This API uses a promise promise.then((data) => { 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); }) ``` @@ -2004,7 +1969,7 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r } 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]); } }) ``` @@ -2037,10 +2002,10 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re promise.then((data) => { 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); }) ``` @@ -2071,7 +2036,7 @@ Converts a rotation vector into a quaternion. This API uses a callback to 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]); } }) ``` @@ -2136,7 +2101,7 @@ Obtains the device direction based on the rotation matrix. This API uses a callb err.message); return; } - console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data.x); + console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data); for (var i = 1; i < data.length; i++) { console.info("sensor_getDirection_callback" + data[i]); } @@ -2169,7 +2134,7 @@ Obtains the device direction based on the rotation matrix. This API uses a promi ```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("sensor_getDirection_promise" + data[i]); } @@ -2240,7 +2205,7 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th promise.then((data) => { 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('promise failed'); @@ -2357,11 +2322,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ----- | ------ | ---- | ---- | ------------------------ | -| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in rad.| -| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in rad. | -| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in rad. | +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ----------------- | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in 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-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 85e895952f7d9eeafa395b9e3337806e0213f250..3344e47d14f8d615b1f81e75f92251dc4e8c8287 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -7,7 +7,7 @@ ## Modules to Import -``` +```js import sim from '@ohos.telephony.sim'; ``` @@ -28,7 +28,7 @@ Checks whether the SIM card in the specified slot is activated. This API uses an **Example** -``` +```js sim.isSimActive(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -57,7 +57,7 @@ Checks whether the SIM card in the specified slot is activated. This API uses a **Example** -``` +```js let promise = sim.isSimActive(0); promise.then(data => { console.log(`isSimActive success, promise: data->${JSON.stringify(data)}`); @@ -83,7 +83,7 @@ Obtains the default slot ID of the SIM card that provides voice services. This A **Example** -``` +```js sim.getDefaultVoiceSlotId((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -106,7 +106,7 @@ Obtains the default slot ID of the SIM card that provides voice services. This A **Example** -``` +```js let promise = sim.getDefaultVoiceSlotId(); promise.then(data => { console.log(`getDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); @@ -132,7 +132,7 @@ Checks whether the application (caller) has been granted the operator permission **Example** -``` +```js sim.hasOperatorPrivileges(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -160,7 +160,7 @@ Checks whether the application (caller) has been granted the operator permission **Example** -``` +```js let promise = sim.hasOperatorPrivileges(0); promise.then(data => { console.log(`hasOperatorPrivileges success, promise: data->${JSON.stringify(data)}`); @@ -186,7 +186,7 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use **Example** -``` +```js sim.getISOCountryCodeForSim(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -215,7 +215,7 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use **Example** -``` +```js let promise = sim.getISOCountryCodeForSim(0); promise.then(data => { console.log(`getISOCountryCodeForSim success, promise: data->${JSON.stringify(data)}`); @@ -242,7 +242,7 @@ Obtains the public land mobile network (PLMN) ID of the SIM card in the specifie **Example** -``` +```js sim.getSimOperatorNumeric(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -271,7 +271,7 @@ Obtains the PLMN ID of the SIM card in the specified slot. This API uses a promi **Example** -``` +```js let promise = sim.getSimOperatorNumeric(0); promise.then(data => { console.log(`getSimOperatorNumeric success, promise: data->${JSON.stringify(data)}`); @@ -298,7 +298,7 @@ Obtains the service provider name (SPN) of the SIM card in the specified slot. T **Example** -``` +```js sim.getSimSpn(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -327,7 +327,7 @@ Obtains the SPN of the SIM card in the specified slot. This API uses a promise t **Example** -``` +```js let promise = sim.getSimSpn(0); promise.then(data => { console.log(`getSimSpn success, promise: data->${JSON.stringify(data)}`); @@ -354,7 +354,7 @@ Obtains the status of the SIM card in the specified slot. This API uses an async **Example** -``` +```js sim.getSimState(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -383,7 +383,7 @@ Obtains the status of the SIM card in the specified slot. This API uses a promis **Example** -``` +```js let promise = sim.getSimState(0); promise.then(data => { console.log(`getSimState success, promise: data->${JSON.stringify(data)}`); @@ -409,7 +409,7 @@ Obtains the type of the SIM card in the specified slot. This API uses an asynchr **Example** -``` +```js sim.getCardType(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -438,7 +438,7 @@ Obtains the type of the SIM card in the specified slot. This API uses a promise **Example** -``` +```js let promise = sim.getCardType(0); promise.then(data => { console.log(`getCardType success, promise: data->${JSON.stringify(data)}`); @@ -465,7 +465,7 @@ Checks whether the SIM card in the specified slot is installed. This API uses an **Example** -``` +```js sim.hasSimCard(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -494,7 +494,7 @@ Checks whether the SIM card in the specified slot is installed. This API uses a **Example** -``` +```js let promise = sim.hasSimCard(0); promise.then(data => { console.log(`hasSimCard success, promise: data->${JSON.stringify(data)}`); @@ -520,8 +520,8 @@ Obtains the number of card slots. **Example** -``` -console.log(sim.getMaxSimCount()) +```js +console.log("Result: "+ sim.getMaxSimCount()) ``` 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 2cc2fa8e75d563784bfc31efcb919619b5738994..b29842197c897d8dcb50d120f9f6c5a8a8ecce17 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -25,11 +25,11 @@ Encrypts or decrypts data using RSA. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| | transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| -| success | Function | No| Called when data is encrypted or decrypted successful.| +| 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.| @@ -104,14 +104,14 @@ Encrypts or decrypts data using AES. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| +| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt| +| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| | transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| | iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| | ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**.| | ivLen | string | No| Length of the IV for AES-based encryption and decryption, in bytes. The default value is **16**.| -| success | Function | No| Called when data is encrypted or decrypted successful.| +| 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.| 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-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-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index edf6be53ac623c5fa4a8f1542bf7222dc42e713c..52f5367110bc35c33075ed291a796a657a468816 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -23,7 +23,7 @@ import webSocket from '@ohos.net.webSocket'; var defaultIpAddress = "ws://"; let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); // When receiving the on('open') event, the client can use the send() API to communicate with the server. ws.send("Hello, server!", (err, value) => { if (!err) { @@ -47,7 +47,7 @@ ws.on('message', (err, value) => { } }); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ws.on('error', (err) => { console.log("on error, error:" + JSON.stringify(err)); @@ -393,7 +393,7 @@ Enables listening for the **open** events of a WebSocket connection. This API us ```js let ws = webSocket.createWebSocket(); ws.on('open', (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); }); ``` @@ -421,7 +421,7 @@ Disables listening for the **open** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); let callback1 = (err, value) => { - console.log("on open, status:" + value.status + ", message:" + value.message); + console.log("on open, status:" + value['status'] + ", message:" + value['message']); } ws.on('open', callback1); // You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. @@ -505,7 +505,7 @@ Enables listening for the **close** events of a WebSocket connection. This API u ```js let ws = webSocket.createWebSocket(); ws.on('close', (err, value) => { - console.log("on close, code is " + value.code + ", reason is " + value.reason); + console.log("on close, code is " + value['code'] + ", reason is " + value['reason']); }); ``` 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 **\