diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 8e42633391269303e5e8d888561281f57d1718ae..5854144672c9a672c58e889857e1697fe4fa1ab2 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -8,14 +8,14 @@ - Quick Start - Getting Started - [Preparations](quick-start/start-overview.md) - - [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) - - [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) - - [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) - - [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md) + - [Getting Started with eTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with eTS in FA Model](quick-start/start-with-ets-fa.md) + - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) - Development Fundamentals - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [SysCap](quick-start/syscap.md) + - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md) - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) @@ -44,5 +44,8 @@ - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) + - Native APIs + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) - Contribution - [How to Contribute](../contribute/documentation-contribution.md) diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability/Readme-EN.md index bd494f0618f105521e83cf3b81deb8de44f9fe69..0589643e0f9426f76ac25d3616a41c3b54910e2a 100644 --- a/en/application-dev/ability/Readme-EN.md +++ b/en/application-dev/ability/Readme-EN.md @@ -17,5 +17,7 @@ - Other - [WantAgent Development](wantagent.md) - [Ability Assistant Usage](ability-assistant-guidelines.md) + - [ContinuationManager Development](continuationmanager.md) - [Test Framework Usage](ability-delegator.md) + diff --git a/en/application-dev/ability/ability-brief.md b/en/application-dev/ability/ability-brief.md index 9943d4d697fa787db084fc14848d37abdad90fe9..0d2303bf4f84c2ddc6f34a13d28b02a3762893b0 100644 --- a/en/application-dev/ability/ability-brief.md +++ b/en/application-dev/ability/ability-brief.md @@ -2,7 +2,7 @@ An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. -The ability framework model has two forms. +The ability framework model has two forms: - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more. @@ -11,10 +11,10 @@ The stage model is designed to make it easier to develop complex applications in | Item | FA Model | Stage Model | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | -| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | +| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Intra-process object sharing| Not supported. | Supported. | -| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.| +| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json5` file is used to describe the HAP and component information. The entry file name can be specified.| | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | In addition, the following differences exist in the development process: @@ -27,5 +27,4 @@ In addition, the following differences exist in the development process: ![lifecycle](figures/lifecycle.png) - For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index ba95ade27a3c7cb846be2d254fd3b75d65dd8701..d3e681244166cafecff86575dd1850db4ebf7f90 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -7,9 +7,11 @@ The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. - FA model + Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. - Stage model + The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). ![contextIntroduction](figures/contextIntroduction.png) diff --git a/en/application-dev/ability/continuationmanager.md b/en/application-dev/ability/continuationmanager.md new file mode 100644 index 0000000000000000000000000000000000000000..a1f5a66478cd53aeabe03ed9be21e08596cb2b6b --- /dev/null +++ b/en/application-dev/ability/continuationmanager.md @@ -0,0 +1,253 @@ +# ContinuationManager Development + +> **NOTE** +> +> Currently, the **ContinuationManager** module is not available for application development. Its APIs are mainly used to start the device selection module. + +## When to Use +Users are using two or more devices to experience an all-scenario, multi-device lifestyle. Each type of device has its unique advantages and disadvantages specific to scenarios. The ability continuation capability breaks boundaries of devices and enables multi-device collaboration, achieving precise control, universal coordination, and seamless hops of user applications. + +As the entry of the ability continuation capability, **continuationManager** is used to start the device selection module for the user to select the target device. After a device is selected, information about the selected device is returned to the user. The user can then initiate cross-device continuation or collaboration based on the device information. + +![continuationManager](figures/continuationManager.png) + +## Available APIs +| API | Description| +| ---------------------------------------------------------------------------------------------- | ----------- | +| register(callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.| +| register(options: ContinuationExtraParams, callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.| +| register(options?: ContinuationExtraParams): Promise\ | Registers the continuation management service and obtains a token. This API uses a promise to return the result.| +| on(type: "deviceConnect", token: number, callback: Callback\>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.| +| on(type: "deviceDisconnect", token: number, callback: Callback\>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.| +| off(type: "deviceConnect", token: number): void | Unsubscribes from device connection events.| +| off(type: "deviceDisconnect", token: number): void | Unsubscribes from device disconnection events.| +| startDeviceManager(token: number, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API does not involve any filter parameters and uses an asynchronous callback to return the result.| +| startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void | Starts the device selection module to show the list of available devices. This API uses an asynchronous callback to return the result.| +| startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | Starts the device selection module to show the list of available devices. This API uses a promise to return the result.| +| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, callback: AsyncCallback\): void | Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.| +| updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState): Promise\ | Instructs the device selection module to update the device connection state. This API uses a promise to return the result.| +| unregister(token: number, callback: AsyncCallback\): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.| +| unregister(token: number): Promise\ | Deregisters the continuation management service. This API uses a promise to return the result.| + +## How to Develop +1. Import the **continuationManager** module. + + ```ts + import continuationManager from '@ohos.continuation.continuationManager'; + ``` + +2. Apply for permissions required for cross-device continuation or collaboration operations. + + The permission application operation varies according to the ability model in use. In the FA mode, add the required permission in the `config.json` file, as follows: + + ```json + { + "module": { + "reqPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ] + } + } + ``` + + This permission must also be granted by the user through a dialog box when the application is started for the first time. The sample code is as follows: + + ```ts + import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; + import bundle from '@ohos.bundle'; + + async function requestPermission() { + let permissions: Array = [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ]; + let needGrantPermission: boolean = false; + let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); + let applicationInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', 0, 100); + for (let i = 0; i < permissions.length; i++) { + let result = await atManager.verifyAccessToken(applicationInfo.accessTokenId, permissions[i]); + // Check whether the permission is granted. + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + needGrantPermission = true; + break; + } + } + // If the permission is not granted, call requestPermissionsFromUser to apply for the permission. + if (needGrantPermission) { + await featureAbility.getContext().requestPermissionsFromUser(permissions, 1); + } else { + console.info('app permission already granted'); + } + } + ``` + + In the stage model, add the required permission in the `module.json5` file. The sample code is as follows: + + ```json + { + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ] + } + } + ``` + + ```ts + import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; + import bundle from '@ohos.bundle'; + + async function requestPermission() { + let permissions: Array = [ + "ohos.permission.DISTRIBUTED_DATASYNC" + ]; + let needGrantPermission: boolean = false; + let atManger: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); + let applicationInfo = await bundle.getApplicationInfo('ohos.samples.continuationmanager', 0, 100); + for (const permission of permissions) { + try { + let grantStatus = await atManger.verifyAccessToken(applicationInfo.accessTokenId, permission); + // Check whether the permission is granted. + if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) { + needGrantPermission = true; + break; + } + } catch (err) { + console.error('app permission query grant status error' + JSON.stringify(err)); + needGrantPermission = true; + break; + } + } + // If the permission is not granted, call requestPermissionsFromUser to apply for the permission. + if (needGrantPermission) { + try { + await globalThis.abilityContext.requestPermissionsFromUser(permissions); + } catch (err) { + console.error('app permission request permissions error' + JSON.stringify(err)); + } + } else { + console.info('app permission already granted'); + } + } + ``` + +3. Register the continuation management service and obtain a token. + + The sample code is as follows: + + ```ts + let token: number = -1; // Used to save the token returned after the registration. The token will be used when listening for device connection/disconnection events, starting the device selection module, and updating the device connection state. + + continuationManager.register().then((data) => { + console.info('register finished, ' + JSON.stringify(data)); + token = data; // Obtain a token and assign a value to the token variable. + }).catch((err) => { + console.error('register failed, cause: ' + JSON.stringify(err)); + }); + ``` + +4. Listen for the device connection/disconnection state. + + The sample code is as follows: + + ```ts + let remoteDeviceId: string = ""; // Used to save the information about the remote device selected by the user, which will be used for cross-device continuation or collaboration. + + // The token parameter is the token obtained during the registration. + continuationManager.on("deviceConnect", token, (continuationResults) => { + console.info('registerDeviceConnectCallback len: ' + continuationResults.length); + if (continuationResults.length <= 0) { + console.info('no selected device'); + return; + } + remoteDeviceId = continuationResults[0].id; // Assign the deviceId of the first selected remote device to the remoteDeviceId variable. + + // Pass the remoteDeviceId parameter to want. + let want = { + deviceId: remoteDeviceId, + bundleName: 'ohos.samples.continuationmanager', + abilityName: 'MainAbility' + }; + // To initiate multi-device collaboration, you must obtain the ohos.permission.DISTRIBUTED_DATASYNC permission. + globalThis.abilityContext.startAbility(want).then((data) => { + console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err)); + }); + }); + ``` + + The preceding multi-device collaboration operation is performed across devices in the stage model. For details about this operation in the FA model, see [Page Ability Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/fa-pageability.md). + + You can also instruct the device selection module to update the device connection state. The sample code is as follows: + + ```ts + // Set the device connection state. + let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.CONNECTED; + + // The token parameter is the token obtained during the registration, and the remoteDeviceId parameter is the remoteDeviceId obtained. + continuationManager.updateConnectStatus(token, remoteDeviceId, deviceConnectStatus).then((data) => { + console.info('updateConnectStatus finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err)); + }); + ``` + + Listen for the device disconnection state so that the user can stop cross-device continuation or collaboration in time. The sample code is as follows: + + ```ts + // The token parameter is the token obtained during the registration. + continuationManager.on("deviceDisconnect", token, (deviceIds) => { + console.info('onDeviceDisconnect len: ' + deviceIds.length); + if (deviceIds.length <= 0) { + console.info('no unselected device'); + return; + } + + // Update the device connection state. + let unselectedDeviceId: string = deviceIds[0]; // Assign the deviceId of the first deselected remote device to the unselectedDeviceId variable. + let deviceConnectStatus: continuationManager.DeviceConnectState = continuationManager.DeviceConnectState.DISCONNECTING; // Device disconnected. + + // The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained. + continuationManager.updateConnectStatus(token, unselectedDeviceId, deviceConnectStatus).then((data) => { + console.info('updateConnectStatus finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('updateConnectStatus failed, cause: ' + JSON.stringify(err)); + }); + }); + ``` + +5. Start the device selection module to show the list of available devices on the network. + + The sample code is as follows: + + ```ts + // Filter parameters. + let continuationExtraParams = { + deviceType: ["00E"], // Device type. + continuationMode: continuationManager.ContinuationMode.COLLABORATION_SINGLE // Single-choice mode of the device selection module. + }; + + // The token parameter is the token obtained during the registration. + continuationManager.startDeviceManager(token, continuationExtraParams).then((data) => { + console.info('startDeviceManager finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('startDeviceManager failed, cause: ' + JSON.stringify(err)); + }); + ``` + +6. If you do not need to perform cross-device migration or collaboration operations, you can deregister the continuation management service, by passing the token obtained during the registration. + + The sample code is as follows: + + ```ts + // The token parameter is the token obtained during the registration. + continuationManager.unregister(token).then((data) => { + console.info('unregister finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('unregister failed, cause: ' + JSON.stringify(err)); + }); + ``` diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 354945ff4e6dcc79f71c8d16693ce660e4270868..c1cadebe652dbd9f195e96ed1dec221df0eff849 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -3,7 +3,7 @@ ## Widget Overview A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: - Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users. @@ -157,8 +157,8 @@ Configure the **config.json** file for the widget. | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | - | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | - | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
This parameter has a lower priority than **updateDuration**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) | + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.
This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | @@ -189,7 +189,6 @@ Configure the **config.json** file for the widget. "scheduledUpdateTime": "10:30", "supportDimensions": ["2*2"], "type": "JS", - "updateDuration": 1, "updateEnabled": true }] }] @@ -208,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; // Persistently store widget information for subsequent use, such as widget instance retrieval or update. - // The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". + // The storeFormInfo API is not implemented here. storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -227,7 +226,7 @@ You should override **onDestroy** to delete widget data. console.log('FormAbility onDestroy'); // You need to implement the code for deleting the persistent widget instance. - // The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples". + // The deleteFormInfo API is not implemented here. deleteFormInfo(formId); } ``` @@ -336,7 +335,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.MyApplication.hmservice.FormAbility", + "abilityName": "com.example.entry.MainAbility", "params": { "message": "add detail" } @@ -349,3 +348,57 @@ Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) +### Developing Widget Events + +You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: + +1. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. +2. For the router event, set the following attributes: + - **action**: **"router"**. + - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model. + - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. +3. For the message event, set the following attributes: + - **action**: **"message"**. + - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. + +The code snippet is as follows: + + - In the HML file: + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + + - In the JSON file: + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "com.example.entry.MainAbility", + "params": { + "message": "add detail" + } + }, + "messageEvent": { + "action": "message", + "params": { + "message": "add detail" + } + } + } + } + ``` \ No newline at end of file diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability/figures/contextIntroduction.png index 9f49f270750549a5326724dc0db1560dbda07c44..7345a1a5a6a3471782e9399129c98f3d529bbfd5 100644 Binary files a/en/application-dev/ability/figures/contextIntroduction.png and b/en/application-dev/ability/figures/contextIntroduction.png differ diff --git a/en/application-dev/ability/figures/continuationManager.png b/en/application-dev/ability/figures/continuationManager.png new file mode 100644 index 0000000000000000000000000000000000000000..8447f339a8fc2e911aaf7d3f86557c980eecac44 Binary files /dev/null and b/en/application-dev/ability/figures/continuationManager.png differ diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index 97e6caee0ca331c4fbc3ca6af309f006c5e4a325..fcd7a5dcfdde6547237f34f83dbb9bf2488d2255 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -1,6 +1,6 @@ # Ability Development ## When to Use -Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.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 an ability based on the stage model, implement the following logic: +Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json5` and `app.json5` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Call abilities. For details, see [Call Development](stage-call.md). @@ -8,7 +8,7 @@ Ability development in the [stage model](stage-brief.md) is significantly differ - Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). ### Launch Type -An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json` file. Depending on the launch type, the action performed when the ability is started differs, as described below. +An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json5` file. Depending on the launch type, the action performed when the ability is started differs, as described below. | Launch Type | Description |Action | | ----------- | ------- |---------------- | @@ -16,7 +16,7 @@ An ability can be launched in the **standard**, **singleton**, or **specified** | singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| -By default, the singleton mode is used. The following is an example of the `module.json` file: +By default, the singleton mode is used. The following is an example of the `module.json5` file: ```json { "module": { @@ -87,7 +87,7 @@ To create Page abilities for an application in the stage model, you must impleme onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - windowStage.loadContent("pages/index").then((data) => { + windowStage.loadContent("pages/index").then(() => { console.log("MainAbility load content succeed") }).catch((error) => { console.error("MainAbility load content failed with error: " + JSON.stringify(error)) @@ -149,9 +149,9 @@ 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 respective 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 permission for calendar access as an example. +If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json5`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. -Declare the required permission in the `module.json` file. +Declare the required permission in the `module.json5` file. ```json "requestPermissions": [ { @@ -231,8 +231,8 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -context.startAbility(want).then((data) => { - console.log("Succeed to start ability with data: " + JSON.stringify(data)) +context.startAbility(want).then(() => { + console.log("Succeed to start ability") }).catch((error) => { console.error("Failed to start ability with error: "+ JSON.stringify(error)) }) @@ -248,8 +248,8 @@ var want = { "bundleName": "com.example.MyApplication", "abilityName": "MainAbility" }; -context.startAbility(want).then((data) => { - console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) +context.startAbility(want).then(() => { + console.log("Succeed to start remote ability") }).catch((error) => { console.error("Failed to start remote ability with error: " + JSON.stringify(error)) }) diff --git a/en/application-dev/ability/stage-formextension.md b/en/application-dev/ability/stage-formextension.md index 1037c88b76370d92a27153b25784327f78fe4ced..fa90f267c13c0fa002233f585ca7c6b3c9904637 100644 --- a/en/application-dev/ability/stage-formextension.md +++ b/en/application-dev/ability/stage-formextension.md @@ -4,7 +4,7 @@ A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message. Basic concepts: @@ -49,10 +49,10 @@ The **FormExtension** class also has a member context, that is, the **FormExtens **Table 2** FormExtensionContext APIs -| API | Description | -| :----------------------------------------------------------- | :------------------------ | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void | Updates a widget. This API uses an asynchronous callback to return the result. | -| updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\ | Updates a widget. This API uses a promise to return the result.| +| API | Description | +| :----------------------------------------------------------- | :----------------------------------------------------------- | +| startAbility(want: Want, callback: AsyncCallback<void>): void | Starts an ability. This API uses an asynchronous callback to return the result. (This is a system API and cannot be called by third-party applications.)| +| startAbility(want: Want): Promise<void> | Starts an ability. This API uses a promise to return the result. (This is a system API and cannot be called by third-party applications.)| For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -86,7 +86,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo export default class FormAbility extends FormExtension { onCreate(want) { console.log('FormAbility onCreate'); - // Persistently store widget information for subsequent use, such as during widget instance retrieval or update. + // Persistently store widget information for subsequent use, such as widget instance retrieval or update. let obj = { "title": "titleOnCreate", "detail": "detailOnCreate" @@ -176,8 +176,8 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo | supportDimensions | Grid styles supported by the widget. Available values are as follows:
**1 * 2**: indicates a grid with one row and two columns.
**2 * 2**: indicates a grid with two rows and two columns.
**2 * 4**: indicates a grid with two rows and four columns.
**4 * 4**: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | - | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | - | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | + | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
This parameter has a lower priority than **updateDuration**. If both are specified, the value specified by **updateDuration** is used.| String | Yes (initial value: **0:0**) | + | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.
This parameter has a higher priority than **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number | Yes (initial value: **0**) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | @@ -200,7 +200,6 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo "defaultDimension": "2*2", "updateEnabled": true, "scheduledUpdateTime": "10:30", - "updateDuration": 1, "formConfigAbility": "ability://ohos.samples.FormApplication.MainAbility" }] } @@ -218,8 +217,8 @@ Mostly, the widget provider is started only when it needs to obtain information let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formName = want.parameters["ohos.extra.param.key.form_name"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; - // Persistently store widget data for subsequent use, such as widget instance retrieval and update. - // The storeFormInfo API is not implemented here. For details about the implementation, see "Samples" below. + // Persistently store widget data for subsequent use, such as widget instance retrieval or update. + // The storeFormInfo API is not implemented here. storeFormInfo(formId, formName, tempFlag, want); let obj = { @@ -238,7 +237,7 @@ You should override **onDestroy** to delete widget data. console.log('FormAbility onDestroy'); // You need to implement the code for deleting the persistent widget data. - // The deleteFormInfo API is not implemented here. For details about the implementation, see "Samples" below. + // The deleteFormInfo API is not implemented here. deleteFormInfo(formId); } ``` @@ -277,10 +276,11 @@ onUpdate(formId) { You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. - - hml: + - In the HML file: ```html
@@ -295,7 +295,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
``` - - css: + - In the CSS file: ```css .container { @@ -336,7 +336,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme } ``` - - json: + - In the JSON file: ```json { "data": { @@ -346,7 +346,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme "actions": { "routerEvent": { "action": "router", - "abilityName": "com.example.MyApplication.hmservice.FormAbility", + "abilityName": "MainAbility", "params": { "message": "add detail" } @@ -358,3 +358,58 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) + +### Developing Widget Events + +You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: + +1. Set **onclick** in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. +2. For the router event, set the following attributes: + - **action**: **"router"**. + - **abilityName**: target ability name, for example, **MainAbility**, which is the default main ability name in DevEco Studio for the stage model. + - **params**: custom parameters of the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. +3. For the message event, set the following attributes: + - **action**: **"message"**. + - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. + +The following is an example: + + - In the HML file: + ```html +
+ +
+ +
+
+ {{title}} + {{detail}} +
+
+
+ ``` + + - In the JSON file: + ```json + { + "data": { + "title": "TitleDefault", + "detail": "TextDefault" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "MainAbility", + "params": { + "message": "add detail" + } + }, + "messageEvent": { + "action": "message", + "params": { + "message": "add detail" + } + } + } + } + ``` \ No newline at end of file diff --git a/en/application-dev/ability/stage-serviceextension.md b/en/application-dev/ability/stage-serviceextension.md index 5154a97d6a65bc787596f54466e7983a60a8bb11..0d634ebe67ef9e332f658a0efb0f7ffdb0e1f2b7 100644 --- a/en/application-dev/ability/stage-serviceextension.md +++ b/en/application-dev/ability/stage-serviceextension.md @@ -1,20 +1,20 @@ # Service Extension Ability Development ## When to Use -**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. **ServiceExtensionAbility** is extended from **ExtensionAbility**. +`ExtensionAbility` is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. `ServiceExtensionAbility` is extended from `ExtensionAbility`. -You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. +You can customize a class that inherits from `ServiceExtensionAbility` and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. ## Available APIs **Table 1** ServiceExtensionAbility lifecycle APIs |API|Description| |:------|:------| -|onCreate(want: Want): void|Called for the initialization when **startAbility** or **connectAbility** is invoked for a given ability for the first time.| -|onRequest(want: Want, startId: number): void|Called each time **startAbility** is invoked for a given ability. The initial value of **startId** is **1**, and the value is incremented by one each time **startAbility** is invoked for that ability.| -|onConnect(want: Want): rpc.RemoteObject|Called when **connectAbility** is invoked for a given ability. This callback is not invoked for repeated calling of **connectAbility** for a specific ability. However, it will be invoked unless **connectAbility** is called after the ability has been disconnected using **disconnectAbility**. The returned result is a **RemoteObject**.| -|onDisconnect(want: Want): void|Called when **disconnectAbility** is called for a given ability. If the Extension ability is started by **connectAbility** and is not bound to other applications, the **onDestroy** callback will also be triggered to destroy the Extension ability.| -|onDestroy(): void|Called when **terminateSelf** is invoked to terminate the ability.| +|onCreate(want: Want): void|Called for the initialization when `startAbility` or `connectAbility` is invoked for a given ability for the first time.| +|onRequest(want: Want, startId: number): void|Called each time `startAbility` is invoked for a given ability. The initial value of `startId` is `1`, and the value is incremented by one each time `startAbility` is invoked for that ability.| +|onConnect(want: Want): rpc.RemoteObject|Called when `connectAbility` is invoked for a given ability. This callback is not invoked for repeated calling of `connectAbility` for a specific ability. However, it will be invoked unless `connectAbility` is called after the ability has been disconnected using `disconnectAbility`. The returned result is a `RemoteObject`.| +|onDisconnect(want: Want): void|Called when `disconnectAbility` is called for a given ability. If the Extension ability is started by `connectAbility` and is not bound to other applications, the `onDestroy` callback will also be triggered to destroy the Extension ability.| +|onDestroy(): void|Called when `terminateSelf` is invoked to terminate the ability.| ## Constraints @@ -24,7 +24,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ## How to Develop -1. Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. The following is a configuration example of the **module.json** file: +1. Declare the Service Extension ability in the `module.json5` file by setting its `type` attribute to `service`. The following is a configuration example of the `module.json5` file: ```json @@ -39,7 +39,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ``` -2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined (**entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts** by default) and override the lifecycle callbacks of the base class. The code sample is as follows: +2. Customize a class that inherits from `ServiceExtensionAbility` in the .ts file in the directory where the Service Extension ability is defined (`entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts` by default) and override the lifecycle callbacks of the base class. The code sample is as follows: ```js import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility' diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md index b43d1961722f6e6265f0a8b649208c1737f05726..6ddf26b87022c8bf098efc72de9ae4b4c0e28779 100644 --- a/en/application-dev/connectivity/http-request.md +++ b/en/application-dev/connectivity/http-request.md @@ -10,6 +10,8 @@ The HTTP request function is mainly implemented by the HTTP module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. +For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). + The following table describes the related APIs. | API | Description | @@ -65,7 +67,7 @@ httpRequest.request( console.info('cookies:' + data.cookies); // 8+ } else { console.info('error:' + JSON.stringify(err)); - // Call the destroy() method to release resources after the call is complete. + // Call the destroy() method to destroy the request if it is no longer needed. httpRequest.destroy(); } } diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md index e9d669f7973dce4360c617a6872fa3c86adf481f..fc2a79e0990457a483c7dc75d3ab1fd88c55f126 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md @@ -4,7 +4,7 @@ With device usage statistics APIs, you can have a better understanding of the ap ## Introduction -Currently you can have access to statistics on the application usage, and notification and system usage statistics feature will be available for use in later versions. +Currently you can have access to statistics on the application usage, and the notification and system usage statistics feature will be available for use in later versions. - **The application usage statistics is updated**: 1. Every 30 minutes @@ -21,7 +21,7 @@ Currently you can have access to statistics on the application usage, and notifi 7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used. 8. Number of notifications from applications based on the specified start time and end time 9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time -9. Priority group of the invoker application or a specified application +10. Priority group of the invoker application or a specified application - **The setters can be used to:** diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index c61c9288eecb35ce4235fb00ce91b595b9160b44..4c51f50e9c29c9df846011e80c06a46a59045794 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -20,7 +20,7 @@ The following table describes APIs available for obtaining device location infor | off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted. | | on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events. | | off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events. | -| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLoactionsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. | +| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports. | | off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports. | | on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events. | | off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events. | diff --git a/en/application-dev/device/device-location-overview.md b/en/application-dev/device/device-location-overview.md index 99bfb6805d952a6f336c0c0b4453211dc0e2fe78..aa619c4549083521dd6ac5bcc05795074adc9af4 100644 --- a/en/application-dev/device/device-location-overview.md +++ b/en/application-dev/device/device-location-overview.md @@ -37,3 +37,9 @@ Location awareness is offered by the system as a basic service for applications. Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application. Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information. + +## Samples + +The following sample is provided to help you better understand how to develop location services: + +-[`Location`: Location (eTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 37b2ed13a6285096b0c6683851c39b85e519ad4d..ae40bcddfd756caf88d1bc506bfba4b9a8d01a6d 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -1,13 +1,13 @@ # USB Service Development +The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. + ## When to Use In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer. ## APIs -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). **Table 1** Open USB APIs @@ -21,7 +21,7 @@ The following table lists the USB APIs currently available. For details, see the | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface | -| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\ | Performs bulk transfer. | +| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\ | Performs bulk transfer. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | diff --git a/en/application-dev/device/vibrator-overview.md b/en/application-dev/device/vibrator-overview.md index 889f6b823cc0bbff99cd9bc9cbb2dde641766420..62e0d0d7b99e8bc4eaf5c38b4fc3006a19264df2 100644 --- a/en/application-dev/device/vibrator-overview.md +++ b/en/application-dev/device/vibrator-overview.md @@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ## Constraints -When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**. +When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 0e34d66d523abea51e259bbcea5d7be08e755e3e..4c293fdee7114866ebd969151c0914d29a144941 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,7 +1,6 @@ # Internationalization Development (I18N) -This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. -The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N interfaces defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. +This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md). ## Obtaining System Language and Region Information @@ -90,7 +89,7 @@ You can use APIs provided in the following table to obtain the system language a ## Obtaining Calendar Information -[Calendar](../reference/apis/js-apis-intl.md) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. +[Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. ### Available APIs @@ -119,7 +118,7 @@ You can use APIs provided in the following table to obtain the system language a ```js - var calendar = i18n.getCalendar("zh-CN", "gregory); + var calendar = i18n.getCalendar("zh-CN", "gregory"); ``` 2. Set the time for the **Calendar** object. @@ -192,7 +191,7 @@ You can use APIs provided in the following table to obtain the system language a ## Formatting a Phone Number -[PhoneNumberFormat](../reference/apis/js-apis-intl.md) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. +[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. ### Available APIs @@ -245,7 +244,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ### How to Develop 1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-intl.md) method to convert a measurement unit and format the display result. + Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert8) method to convert a measurement unit and format the display result. ```js @@ -260,7 +259,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ## Alphabet Index -[IndexUtil](../reference/apis/js-apis-intl.md) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. +[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. ### Available APIs @@ -281,7 +280,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ```js - var indexUtil = getInstance("zh-CN"); + var indexUtil = i18n.getInstance("zh-CN"); ``` 2. Obtain the index list. @@ -312,7 +311,7 @@ The **unitConvert** API is provided to help you implement measurement conversion ## Obtaining Line Breaks of Text -When a text is displayed in more than one line, [BreakIterator](../reference/apis/js-apis-intl.md) APIs are used to obtain the line break positions of the text. +When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text. ### Available APIs diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index 44748056f7886d4817cda2d9d0504f6966c32700..424320dcc17f3dc0eb6d3e30970869da83874408 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,7 +1,6 @@ # Internationalization Development (Intl) -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. -The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. +This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md). > **NOTE** > @@ -9,7 +8,7 @@ The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities throug ## Setting Locale Information -Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize locale information. +Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information. ### Available APIs @@ -27,7 +26,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc 1. Instantiate a **Locale** object. - Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list. + Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list. A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. @@ -46,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ```js var locale = "zh-CN"; - var options = {caseFirst: false, calendar: "chinese", collation: pinyin}; + var options = {caseFirst: false, calendar: "chinese", collation: "pinyin"}; var localeObj = new intl.Locale(locale, options); ``` @@ -77,7 +76,7 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ## Formatting the Date and Time -Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date and time for a specific locale. +Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale. ### Available APIs @@ -102,7 +101,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date var dateTimeFormat = new intl.DateTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). ```js var options = {dateStyle: "full", timeStyle: "full"}; @@ -114,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. ```js - Date date = new Date(); + var date = new Date(); var formatResult = dateTimeFormat.format(date); ``` @@ -123,9 +122,10 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. ```js - Date startDate = new Date(); - Date endDate = new Date(); - var formatResult = dateTimeFormat.formatRange(startDate, endDate); + var startDate = new Date(2021, 11, 17, 3, 24, 0); + var endDate = new Date(2021, 11, 18, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.formatRange(startDate, endDate); ``` 4. Obtain attributes of the **DateTimeFormat** object. @@ -139,7 +139,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ## Formatting Numbers -Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for a specific locale. +Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale. ### Available APIs @@ -163,7 +163,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for var numberFormat = new intl.NumberFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). ```js var options = {compactDisplay: "short", notation: "compact"}; @@ -190,7 +190,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ## Sorting Strings -Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. +Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. ### Available APIs @@ -214,7 +214,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on var collator = new intl.Collator(); ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). ```js var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); @@ -222,7 +222,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on 2. Compare two strings. - Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. + Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. ```js var str1 = "first string"; @@ -241,7 +241,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ## Determining the Singular-Plural Type -Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. +Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. ### Available APIs @@ -264,10 +264,10 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu var pluralRules = new intl.PluralRules(); ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). ```js - var plurals = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); ``` 2. Determine the singular-plural type. @@ -282,7 +282,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ## Formatting the Relative Time -Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the relative time for a specific locale. +Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale. ### Available APIs @@ -307,7 +307,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r var relativeTimeFormat = new intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [ RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). ```js var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); @@ -335,8 +335,16 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r 4. Obtain attributes of the **RelativeTimeFormat** object. - Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). + Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). ```js var options = numberFormat.resolvedOptions(); ``` + +## Samples + +The following sample is provided to help you better understand how to develop internationalization capabilities: + +-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) + +-[`International`: Internationalization (eTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md index 5af14112df2959acbcfc606c9cd2938860ad6f85..bdbccf975c64a6df4cef6845c850cc8de1b2de26 100644 --- a/en/application-dev/media/camera.md +++ b/en/application-dev/media/camera.md @@ -54,7 +54,7 @@ await cameraManager.getCameras((err, cameras) => { cameraArray = cameras }) -for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { +for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. diff --git a/en/application-dev/media/remote-camera.md b/en/application-dev/media/remote-camera.md new file mode 100644 index 0000000000000000000000000000000000000000..b63946d6a03a9fbb4d4e6b8e20c3e4920364523b --- /dev/null +++ b/en/application-dev/media/remote-camera.md @@ -0,0 +1,72 @@ +# Distributed Camera Development + +## When to Use + +You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. + +## How to Develop +Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnctionType** of the **Camera** objects. If **ConnctionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). + +For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). + +### Connecting to a Distributed Camera + +Connect the calculator and the distributed device to the same LAN. + +Open the calculator and click the arrow icon in the upper right corner. A new window is displayed. Enter the verification code as prompted, and the calculator will be connected to the distributed device. + +### Creating an Instance + +```js +import camera from '@ohos.multimedia.camera' +import image from '@ohos.multimedia.image' +import media from '@ohos.multimedia.media' +import featureAbility from '@ohos.ability.featureAbility' + +// Create a CameraManager object. +let cameraManager +await camera.getCameraManager(globalThis.Context, (err, manager) => { + if (err) { + console.error('Failed to get the CameraManager instance ${err.message}'); + return; + } + console.log('Callback returned with the CameraManager instance'); + cameraManager = manager +}) + +// Register a callback to listen for camera status changes and obtain the updated camera status information. +cameraManager.on('cameraStatus', (cameraStatusInfo) => { + console.log('camera : ' + cameraStatusInfo.camera.cameraId); + console.log('status: ' + cameraStatusInfo.status); +}) + +// Obtain the camera list. +let cameraArray +let remoteCamera +await cameraManager.getCameras((err, cameras) => { + if (err) { + console.error('Failed to get the cameras. ${err.message}'); + return; + } + console.log('Callback returned with an array of supported cameras: ' + cameras.length); + cameraArray = cameras +}) + +for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { + console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. + console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. + console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. + console.log('connectionType : ' + cameraArray[cameraIndex].connectionType) // Obtain the camera connection type. + if (cameraArray[cameraIndex].connectionType == CAMERA_CONNECTION_REMOTE) { + remoteCamera = cameraArray[cameraIndex].cameraId + } +} + +// Create a camera input stream. +let cameraInput +await cameraManager.createCameraInput(remoteCamera).then((input) => { + console.log('Promise returned with the CameraInput instance'); + cameraInput = input +}) +``` +For details about the subsequent steps, see [Camera Development](./camera.md). diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index d5297e9374fdf42b1b50fa2ac6e545fe9766971b..280efd8afa5fa845dab0d607ed94b33e2a75e6d3 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -2,6 +2,7 @@ - [Using Native APIs in Application Projects](napi-guidelines.md) - [Drawing Development](drawing-guidelines.md) -- [Native Window Development](native-window-guidelines.md) - [Raw File Development](rawfile-guidelines.md) +- [Native Window Development](native-window-guidelines.md) + diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index 86854eb072b19c7ee359dcb70413ce22580cb8f7..f471f4a6eed7d3eb2c96dab8cae4cb7480a13616 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -89,7 +89,7 @@ Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSyn /*********************************************** * Module export and register ***********************************************/ -static napi_value StorgeExport(napi_env env, napi_value exports) +static napi_value StorageExport(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("get", JSStorageGet), @@ -110,7 +110,7 @@ static napi_value StorgeExport(napi_env env, napi_value exports) static napi_module storage_module = {.nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, - .nm_register_func = StorgeExport, + .nm_register_func = StorageExport, .nm_modname = "storage", .nm_priv = ((void*)0), .reserved = {0}}; diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md index 0757c602c2857156cad0ec65b7377355181bd4b2..1894942945c53a4d36bc2f9c892de28359faa9ff 100644 --- a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md @@ -7,139 +7,33 @@ You can set your application to call the **ReminderRequest** class to create sch ## Available APIs -**reminderAgent** encapsulates the methods for publishing and canceling reminders. +**reminderAgent** encapsulates the APIs for publishing and canceling reminders. -**Table 1** Major APIs in reminderAgent - -| Name| Description| -| -------- | -------- | -| function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void;
function publishReminder(reminderReq: ReminderRequest): Promise<number>; | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | -| function cancelReminder(reminderId: number, callback: AsyncCallback<void>): void;
function cancelReminder(reminderId: number): Promise<void>; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| -| function getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void;
function getValidReminders(): Promise<Array<ReminderRequest>>; | Obtains all valid reminders set by the current application.| -| function cancelAllReminders(callback: AsyncCallback<void>): void;
function cancelAllReminders(): Promise<void>; | Cancels all reminders set by the current application.| -| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void;
function addNotificationSlot(slot: NotificationSlot): Promise<void>; | Registers a **NotificationSlot** instance to be used by the reminder. | -| function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void;
function removeNotificationSlot(slotType: notification.SlotType): Promise<void>; | Removes a **NotificationSlot** instance of a specified type. | +For details about the APIs, see [reminderAgent](../reference/apis/js-apis-reminderAgent.md). -**ActionButtonType** enumerates types of buttons displayed in a reminder notification. - -**Table 2** ActionButtonType enums - -| Name| Description| -| -------- | -------- | -| ACTION_BUTTON_TYPE_CLOSE | Close button, which can stop the reminder alert tone, close the reminder notification, and cancel the reminder snoozing.| -| ACTION_BUTTON_TYPE_SNOOZE | Snooze button, which can snooze the reminder.| - -**ReminderType** enumerates the reminder types. - -**Table 3** ReminderType enums +**Table 1** Major APIs in reminderAgent | Name| Description| | -------- | -------- | -| REMINDER_TYPE_TIMER | Countdown reminder.| -| REMINDER_TYPE_CALENDAR | Calendar reminder.| -| REMINDER_TYPE_ALARM | Alarm reminder.| - -**ActionButton** defines a button displayed in the reminder notification. - -**Table 4** ActionButton - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| title | string | Yes| Text on the button.| -| type | ActionButtonType | Yes| Button type.| - -**WantAgent** sets the package and ability that are redirected to when the reminder notification is clicked. - -**Table 5** WantAgent - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package redirected to when the reminder notification is clicked.| -| abilityName | string | Yes| Name of the ability redirected to when the reminder notification is clicked.| - -**MaxScreenWantAgent** sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. - -**Table 6** MaxScreenWantAgent - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| -| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| - -**ReminderRequest** defines the reminder to publish. - -**Table 7** ReminderRequest - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| reminderType | ReminderType | Yes| Type of the reminder.| -| actionButton | [ActionButton?,ActionButton?] | No| Action button displayed in the reminder notification.| -| wantAgent | WantAgent | No| Information about the ability that is redirected to when the notification is clicked.| -| maxScreenWantAgent | MaxScreenWantAgent | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| -| ringDuration | number | No| Ring duration.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval.| -| title | string | No| Reminder title.| -| content | string | No| Reminder content.| -| expiredContent | string | No| Extended content to be displayed when the reminder expires.| -| snoozeContent | string | No| Extended content to be displayed when the reminder is snoozing.| -| notificationId | number | No| Notification ID used by the reminder. For details, see **NotificationRequest::SetNotificationId(int32_t id)**.| -| slotType | SlotType | No| Type of the slot used by the reminder. | - -**ReminderRequestCalendar** extends **ReminderRequest** and defines a reminder for a calendar event. - -For the application to run properly, if both **repeatMonths** and **repeatDays** are not specified, the earliest reminder time must be later than the current time. - -**Table 8** ReminderRequestCalendar - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| dateTime | LocalDateTime | Yes| Reminder time, accurate to the minute.| -| repeatMonths | Array<number> | No| Months in which the reminder repeats. The value range is 1 to 12.| -| repeatDays | Array<number> | No| Date on which the reminder repeats. The value range is 1 to 31.| - -**ReminderRequestAlarm** extends **ReminderRequest** and defines a reminder for the alarm clock. - -**Table 9** ReminderRequestAlarm - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| hour | number | Yes| Hour portion of the reminder time. The value range is 0 to 23.| -| minute | number | Yes| Minute portion of the reminder time. The value range is 0 to 59.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats. The value range is 1 to 7.| - -**ReminderRequestTimer** extends **ReminderRequest** and defines a reminder for a scheduled timer. - -**Table 10** ReminderRequestTimer - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| triggerTimeInSeconds | number | Yes| Number of seconds in the countdown timer.| - -**LocalDateTime** defines a **LocalDateTime** instance. - -**Table 11** LocalDateTime - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| year | number | Yes| Year.| -| month | number | Yes| Month.| -| day | number | Yes| Date.| -| hour | number | Yes| Hour.| -| minute | number | Yes| Minute.| -| second | number | No| Second.| - +| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void
publishReminder(reminderReq: ReminderRequest): Promise<number> | Publishes a scheduled reminder.
The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | +| cancelReminder(reminderId: number, callback: AsyncCallback<void>): void
cancelReminder(reminderId: number): Promise<void> | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| +| getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void
getValidReminders(): Promise<Array<ReminderRequest>> | Obtains all valid reminders set by the current application.| +| cancelAllReminders(callback: AsyncCallback<void>): void
cancelAllReminders(): Promise<void> | Cancels all reminders set by the current application.| +| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void
addNotificationSlot(slot: NotificationSlot): Promise<void> | Registers a **NotificationSlot** instance to be used by the reminder.| +| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void
removeNotificationSlot(slotType: notification.SlotType): Promise<void> | Removes a **NotificationSlot** instance of a specified type.| ## How to Develop > **NOTE** > -> To publish a reminder, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. +> 1. To publish a reminder through the reminder agent, your application needs to apply for the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. +> +> 2. Your application must have notification enabled. For details, see [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). -Publish a 10-second countdown reminder. +1. Define a reminder agent. -1. Define a countdown timer instance. - ``` + Sample code for defining a reminder agent for a countdown timer: + ```js import reminderAgent from '@ohos.reminderAgent'; import notification from '@ohos.notification'; export default { @@ -172,8 +66,97 @@ Publish a 10-second countdown reminder. } ``` -2. Publish the reminder. - ``` + Sample code for defining a reminder agent for a calendar event: + + ```js + // For a JS project: + // calendar: { + // For an eTS project: + let calendar : reminderAgent.ReminderRequestCalendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime: { + year: 2050, + month: 7, + day: 30, + hour: 11, + minute: 14, + second: 30 + }, + repeatMonths: [1], + repeatDays: [1], + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: "snooze", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + ringDuration: 5, + snoozeTimes: 2, + timeInterval: 5, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + snoozeContent: "remind later", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION + } + ``` + + Sample code for defining a reminder agent for an alarm: + + ```js + // For a JS project: + // alarm: { + // For an eTS project: + let alarm : reminderAgent.ReminderRequestAlarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 11, + minute: 14, + daysOfWeek: [0], + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: "snooze", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.example.device", + abilityName: "com.example.device.MainAbility" + }, + ringDuration: 5, + snoozeTimes: 2, + timeInterval: 5, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + snoozeContent: "remind later", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION + } + ``` + +2. Publish a countdown reminder. + ```js startTimer() { reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ this.printInfo(JSON.stringify(err)); @@ -183,98 +166,9 @@ Publish a 10-second countdown reminder. ``` HML page code: - ``` + ```html
``` -Sample code for defining a calendar reminder instance: - -``` -// For a JS project: -// calendar: { -// For an eTS project: -let calendar : reminderAgent.ReminderRequestCalendar = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, - dateTime: { - year: 2050, - month: 7, - day: 30, - hour: 11, - minute: 14, - second: 30 - }, - repeatMonths: [1], - repeatDays: [1], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} -``` - -Sample code for defining an alarm reminder instance: - -``` -// For a JS project: -// alarm: { -// For an eTS project: -let alarm : reminderAgent.ReminderRequestAlarm = { - reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, - hour: 11, - minute: 14, - daysOfWeek: [0], - actionButton: [ - { - title: "close", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE - }, - { - title: "snooze", - type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE - }, - ], - wantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - maxScreenWantAgent: { - pkgName: "com.example.device", - abilityName: "com.example.device.MainAbility" - }, - ringDuration: 5, - snoozeTimes: 2, - timeInterval: 5, - title: "this is title", - content: "this is content", - expiredContent: "this reminder has expired", - snoozeContent: "remind later", - notificationId: 100, - slotType: notification.SlotType.SOCIAL_COMMUNICATION -} -``` - diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md index 5630462352d721cb3337bfbe302576dc175e29bd..fb73f274202aafd9ff852201ca2fb8c5116aba50 100644 --- a/en/application-dev/notification/notification-guidelines.md +++ b/en/application-dev/notification/notification-guidelines.md @@ -28,14 +28,14 @@ System applications also support notification-related configuration options, suc ## Available APIs -Certain APIs can be invoked only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md). +Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md). **Table 1** APIs for notification enabling | API | Description | | ------------------------------------------------------------ | ---------------- | -| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void | Checks whether notification is enabled.| -| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void | Sets whether to enable notification. | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.| +| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. | If the notification function of an application is disabled, it cannot send notifications. @@ -45,11 +45,11 @@ If the notification function of an application is disabled, it cannot send notif | API | Description | | ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Unsubscribes from a notification. | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | +| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | -The subscription APIs support subscription to all notifications or notifications from specific applications. +The subscription APIs support subscription to all notifications and notifications from specific applications. @@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications | API | Description | | ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback): void; | Cancels all notifications published by the application.| +| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | +| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | +| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | +| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. @@ -136,7 +136,7 @@ var subscriber = { Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. ```js -Notification.requestEnableNotification() .then((data) => { +Notification.requestEnableNotification().then((data) => { console.info('===>requestEnableNotification success'); }).catch((err) => { console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); @@ -166,7 +166,7 @@ var notificationRequest = { } // Publish the notification. -Notification.publish(notificationRequest) .then((data) => { +Notification.publish(notificationRequest).then((data) => { console.info('===>publish promise success req.id : ' + notificationRequest.id); }).catch((err) => { console.error('===>publish promise failed because ' + JSON.stringify(err)); @@ -235,7 +235,7 @@ var notificationRequest = { } // Publish the notification. -Notification.publish(notificationRequest) .then((data) => { +Notification.publish(notificationRequest).then((data) => { console.info('===>publish promise success req.id : ' + notificationRequest.id); }).catch((err) => { console.error('===>publish promise failed because ' + JSON.stringify(err)); diff --git a/en/application-dev/quick-start/figures/01.png b/en/application-dev/quick-start/figures/01.png index ab9a01795cd6795448b16e53b7400cc7806e455c..cb9ddd68fc3ee2e6e15700a6a7a5d9e6ff1f4cc7 100644 Binary files a/en/application-dev/quick-start/figures/01.png and b/en/application-dev/quick-start/figures/01.png differ diff --git a/en/application-dev/quick-start/figures/02.png b/en/application-dev/quick-start/figures/02.png index 9b06d46ea1285613c00efc7cce55e7dbe2b74a2c..4fd0a6d3e60c0a22a9b69ea9f46fe62050d37a7e 100644 Binary files a/en/application-dev/quick-start/figures/02.png and b/en/application-dev/quick-start/figures/02.png differ diff --git a/en/application-dev/quick-start/figures/04.png b/en/application-dev/quick-start/figures/04.png index ac9dd6594d8d6d3673b0f713288f41dae5b60496..2d66f7513893e83e4e897ed63319316d9f5bd40e 100644 Binary files a/en/application-dev/quick-start/figures/04.png and b/en/application-dev/quick-start/figures/04.png differ diff --git a/en/application-dev/quick-start/figures/06.png b/en/application-dev/quick-start/figures/06.png index bdfc0acf1c46ded2b471894dc20af970f3c50836..37b63e9f1ee245f7403667b03ab89ada0479572f 100644 Binary files a/en/application-dev/quick-start/figures/06.png and b/en/application-dev/quick-start/figures/06.png differ diff --git a/en/application-dev/quick-start/figures/07.png b/en/application-dev/quick-start/figures/07.png index 3749dcb06daed21f87088a9a46afa6d0d87bef3f..1a232454b8485269d473611b126489c87d2f82d9 100644 Binary files a/en/application-dev/quick-start/figures/07.png and b/en/application-dev/quick-start/figures/07.png differ diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index 7d733b1b06c5996fb16cc01cbeb712422edf2b1f..bd1eb5a1a3f52c392a645b8958e02e2f59e39e29 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -501,7 +501,7 @@ Example of the **requestPermissions** attribute structure: "usedScene": { "abilities": [ "AudioAbility", - "VedioAbility", + "VideoAbility", ], "when": "inuse" } diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index 6676177531b6a2aaeac7ffcac59ab3a586b5656c..23af935c5cbb2d66a60ccec431a1737fb9ffb741 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -45,8 +45,8 @@ This document provides an ability with two pages. For more information about abi ## Tool Preparation -1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta). +1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download). 2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443). -When you are done, follow the instructions in [Getting Started with eTS in Stage Model](start-with-ets-stage.md), [Getting Started with eTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](../quick-start/start-with-js-fa.md). +When you are done, follow the instructions in [Getting Started with eTS in Stage Model](start-with-ets-stage.md), [Getting Started with eTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](start-with-js-fa.md). diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index 8eacd7eedaf4fd795ee14c378484298398ef0b63..325f4983f16f0cd48899fb657d3c9e41d2f9c3d8 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -5,7 +5,7 @@ > > To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. > -> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. +> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. ## Creating an eTS Project @@ -128,7 +128,6 @@ ![en-us_image_0000001311334932](figures/en-us_image_0000001311334932.png) > **NOTE** - > > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. - Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows: @@ -140,7 +139,7 @@ "pages": [ "pages/index", "pages/second" - ], + ] } ] } @@ -288,7 +287,7 @@ You can implement page redirection through the page router, which finds the targ 1. Connect the development board running the OpenHarmony standard system to the computer. -2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. +2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure. ![06](figures/06.png) diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index 162f4bf949364c5550b71945f28dac1ca4946707..7703ff56e9336bb5e648a63eb3e7df470f0d88a5 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -5,7 +5,7 @@ > > To use eTS, your DevEco Studio must be V3.0.0.900 Beta3 or later. > -> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. +> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. ## Creating an eTS Project @@ -132,7 +132,6 @@ ![09](figures/09.png) > **NOTE** - > > You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes. - Configure the route for the second page: In the **Project** window, choose **entry** > **src** > **main** > **resources** > **base** > **profile**. In the **main_pages.json** file, set **pages/second** under **src**. The sample code is as follows: @@ -286,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ 1. Connect the development board running the OpenHarmony standard system to the computer. -2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. +2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signaure**. Wait until the automatic signing is complete, and click **OK**. See the following figure. ![06](figures/06.png) diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index b89b8726df8992b45e4f702798633aee4cbc97d5..dbd2931eba6f6de6c6d23777a5c761dc505dc7c4 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -3,7 +3,7 @@ > **NOTE** > -> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development. +> For best possible results, use [DevEco Studio V3.0.0.993](https://developer.harmonyos.com/cn/develop/deveco-studio#download) for your development. ## Creating a JavaScript Project @@ -226,7 +226,7 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin 1. Connect the development board running the OpenHarmony standard system to the computer. -2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure. +2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure. ![06](figures/06.png) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 09a65cea53e545c3afb58924b498512242a9285f..fe77dc5347f70c5cbcef596dbd8c3b57df83d9cc 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -28,6 +28,8 @@ - application/[FormExtensionContext](js-apis-formextensioncontext.md) - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md) + - [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md) + - [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) - FA and Stage Models - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) @@ -136,6 +138,7 @@ - [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - enterpriseDeviceManager/[DeviceSettingsManager](js-apis-enterpriseDeviceManager-DeviceSettingsManager.md) - Security diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index 84e2a71941aeb2b0b78c612ddc204e598d9c6b06..fd15443a5b2ac2b28642a0c89d441cdbee5d6866 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -20,7 +20,7 @@ import Want from '@ohos.application.Want'; | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | deviceId | Read only | string | No | ID of the device running the ability. | | bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| -| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | Read only | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| @@ -73,29 +73,32 @@ import Want from '@ohos.application.Want'; - Passing **RemoteObject** data ``` js + import rpc from '@ohos.rpc'; + import Ability from '@ohos.application.Ability' + class Stub extends rpc.RemoteObject { - constructor(des) { - if (typeof des == 'string') { - super(des); - } else { - return null; - } - } - - onRemoteRequest(code, data, reply, option) { - if (code === 1) { - console.log('onRemoteRequest called') - let token = data.readInterfaceToken(); - let num = data.readInt(); - this.method(); - return true; - } - return false; - } - - method() { - console.log('method called'); - } + constructor(des) { + if (typeof des == 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + if (code === 1) { + console.log('onRemoteRequest called') + let token = data.readInterfaceToken(); + let num = data.readInt(); + this.method(); + return true; + } + return false; + } + + method() { + console.log('method called'); + } } var remoteObject = new Stub('want-test'); @@ -103,15 +106,16 @@ import Want from '@ohos.application.Want'; "deviceId": "", // An empty deviceId indicates the local device. "bundleName": "com.extreme.test", "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. + "moduleName": "entry", // moduleName is optional. "parameters": { - "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} + "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} } }; + this.context.startAbility(want, (error) => { // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. console.log("error.code = " + error.code) }) - ``` - \ No newline at end of file + ``` + diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md index 8a366b1e21bb988c608ba0a5e57251f2bd237d75..c48d33d59a701fb998f82316d5c70a0d86fc5ea1 100644 --- a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @@ -25,56 +25,25 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; ## WindowExtensionAbility.onConnect -onConnect(want: Want): rpc.RemoteObject +onConnect(want: Want): void Called when this Window Extension ability is connected to an ability for the first time. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | - -**Return value** -| Type | Description | -| ----------------------------------------------- | -------------------- | -| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** ```ts -import rpc from '@ohos.rpc'; - -class StubTest extends rpc.RemoteObject { - constructor(des) { - super(des); - } - onRemoteRequest(code, data, reply, option) { - return true; - } - queryLocalInterface(descriptor) { - return null; - } - getInterfaceDescriptor() { - return ""; - } - sendRequest(code, data, reply, options) { - return null; - } - getCallingPid() { - return 1; - } - getCallingUid() { - return 1; - } - attachLocalInterface(localInterface, descriptor){} -} - export default class MyWindowExtensionAbility extends WindowExtensionAbility { - onConnect(want): rpc.RemoteObject { + onConnect(want) { console.info('WindowExtAbility onConnect ' + want.abilityName); - return new StubTest("test"); } } @@ -88,9 +57,11 @@ Called when this Window Extension ability is disconnected from all connected abi **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** @@ -105,7 +76,6 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { } ``` - ## WindowExtensionAbility.onWindowReady onWindowReady(window: Window): void @@ -114,6 +84,8 @@ Called when a window is ready. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | window | [Window](js-apis-window.md) | Yes| Current **Window** instance.| diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index a518c72880e74ad35cc76e2f0f8c15f92a0b764f..f019d61969e28699cc1324a6f8d8af29ba7d60f6 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -14,10 +14,27 @@ This module provides the following common audio-related functions: ## Modules to Import -``` +```js import audio from '@ohos.multimedia.audio'; ``` +## Constants + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------- | ---- | ---- | ------------------ | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.| + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +const localNetworkId = audio.LOCAL_NETWORK_ID; +``` ## audio.getAudioManager @@ -28,31 +45,68 @@ Obtains an **AudioManager** instance. **System capability**: SystemCapability.Multimedia.Audio.Core **Return value** + | Type | Description | | ----------------------------- | ------------ | | [AudioManager](#audiomanager) | **AudioManager** instance.| **Example** -``` +```js var audioManager = audio.getAudioManager(); ``` ## audio.getStreamManager9+ -getStreamManager(): AudioStreamManager +getStreamManager(callback: AsyncCallback\): void -Obtains an **AudioStreamManager** instance. +Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Core -**Return value** -| Type | Description | -| -------------------------------------------------| ------------------------------- | -| [AudioStreamManager](#audiostreammanager9) | **AudioStreamManager** instance. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| **Example** + +```js +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + let audioStreamManager = data; + } +}); ``` -var audioStreamManager = audio.getStreamManager(); + +## audio.getStreamManager9+ + +getStreamManager(): Promise + +Obtains an **AudioStreamManager** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ---------------- | +| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| + +**Example** + +```js +var audioStreamManager; +audio.getStreamManager().then((data) => { + audioStreamManager = data; + console.info('getStreamManager: Success!'); +}).catch((err) => { + console.error(`getStreamManager: ERROR : ${err}`); +}); + ``` ## audio.createAudioRenderer8+ @@ -72,7 +126,7 @@ Obtains an **AudioRenderer** instance. This API uses an asynchronous callback to **Example** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, @@ -94,9 +148,9 @@ var audioRendererOptions = { audio.createAudioRenderer(audioRendererOptions,(err, data) => { if (err) { - console.error(`AudioRenderer Created: Error: ${err.message}`); + console.error(`AudioRenderer Created: Error: ${err}`); } else { - console.info(`AudioRenderer Created: Success: SUCCESS`); + console.info('AudioRenderer Created: Success: SUCCESS'); let audioRenderer = data; } }); @@ -124,7 +178,7 @@ Obtains an **AudioRenderer** instance. This API uses a promise to return the res **Example** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { @@ -148,9 +202,9 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; - console.info(`AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS`); + console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); }).catch((err) => { - console.info(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR :` + err.message); + console.error(`AudioFrameworkRenderLog: AudioRenderer Created : ERROR : ${err}`); }); ``` @@ -171,7 +225,7 @@ Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to **Example** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, @@ -192,9 +246,9 @@ var audioCapturerOptions = { audio.createAudioCapturer(audioCapturerOptions, (err, data) => { if (err) { - console.error(`AudioCapturer Created : Error: ${err.message}`); + console.error(`AudioCapturer Created : Error: ${err}`); } else { - console.info(`AudioCapturer Created : Success : SUCCESS`); + console.info('AudioCapturer Created : Success : SUCCESS'); let audioCapturer = data; } }); @@ -222,7 +276,7 @@ Obtains an **AudioCapturer** instance. This API uses a promise to return the res **Example** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamInfo = { @@ -245,9 +299,9 @@ var audioCapturerOptions = { var audioCapturer; audio.createAudioCapturer(audioCapturerOptions).then((data) => { audioCapturer = data; - console.info(`AudioCapturer Created : Success : Stream Type: SUCCESS`); + console.info('AudioCapturer Created : Success : Stream Type: SUCCESS'); }).catch((err) => { - console.info(`AudioCapturer Created : ERROR : ` + err.message); + console.error(`AudioCapturer Created : ERROR : ${err}`); }); ``` @@ -263,7 +317,7 @@ Enumerates the audio stream types. | RINGTONE | 2 | Audio stream for ringtones. | | MEDIA | 3 | Audio stream for media purpose. | | VOICE_ASSISTANT8+ | 9 | Audio stream for voice assistant.| - +| ALL9+ | 100 | All public audio streams.
This is a system API and cannot be called by third-party applications.| ## InterruptMode9+ @@ -282,11 +336,15 @@ Enumerates the audio device flags. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | -| ------------------- | ------ | ---------- | -| OUTPUT_DEVICES_FLAG | 1 | Output device.| -| INPUT_DEVICES_FLAG | 2 | Input device.| -| ALL_DEVICES_FLAG | 3 | All devices.| +| Name | Default Value | Description | +| ------------------------------- | ------ | ------------------------------------------------- | +| NONE_DEVICES_FLAG9+ | 0 | No flag.
This is a system API and cannot be called by third-party applications. | +| OUTPUT_DEVICES_FLAG | 1 | Output device.| +| INPUT_DEVICES_FLAG | 2 | Input device.| +| ALL_DEVICES_FLAG | 3 | All devices.| +| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API and cannot be called by third-party applications. | +| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API and cannot be called by third-party applications. | +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output devices.
This is a system API and cannot be called by third-party applications. | ## DeviceRole @@ -307,17 +365,18 @@ Enumerates the audio device types. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | -| ---------------- | ------ | --------------------------------------------------------- | -| INVALID | 0 | Invalid device. | -| EARPIECE | 1 | Earpiece. | -| SPEAKER | 2 | Speaker. | -| WIRED_HEADSET | 3 | Wired headset with a microphone. | -| WIRED_HEADPHONES | 4 | Wired headset without microphone. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | -| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.| -| MIC | 15 | Microphone. | -| USB_HEADSET | 22 | USB Type-C headset. | +| Name | Default Value| Description | +| ---------------------| ------ | --------------------------------------------------------- | +| INVALID | 0 | Invalid device. | +| EARPIECE | 1 | Earpiece. | +| SPEAKER | 2 | Speaker. | +| WIRED_HEADSET | 3 | Wired headset with a microphone. | +| WIRED_HEADPHONES | 4 | Wired headset without microphone. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | +| BLUETOOTH_A2DP | 8 | Bluetooth device using Advanced Audio Distribution Profile (A2DP) links.| +| MIC | 15 | Microphone. | +| USB_HEADSET | 22 | USB Type-C headset. | +| DEFAULT9+ | 1000 | Default device type. | ## ActiveDeviceType @@ -431,6 +490,8 @@ Enumerates the audio stream usage. Enumerates the focus types. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Core | Name | Default Value | Description | @@ -539,17 +600,6 @@ Describes audio renderer information. | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| | rendererFlags | number | Yes | Audio renderer flags.| -## AudioRendererFlag9+ - -Enumerates the audio renderer flags that determine the output policy. - -**System capability**: SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| ------------------| ------------ | ---------------------- | -| FLAG_NONE | 0 | There is no special policy. | -| FLAG_LOW_LATENCY | 1 | A low-latency process is used. | - ## AudioRendererOptions8+ Describes audio renderer configurations. @@ -602,7 +652,7 @@ Describes the callback invoked for audio interruption or focus gain events. Describes the event received by the application when the volume is changed. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -611,6 +661,55 @@ This is a system API and cannot be called by third-party applications. | volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | | volume | number | Yes | Volume level. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| | updateUi | boolean | Yes | Whether to show the volume change in UI. | +| volumeGroupId9+ | number | Yes | Volume group ID. It can be used as an input parameter of **getGroupManager**. | +| networkId9+ | string | Yes | Network ID. | + +## ConnectType9+ + +Enumerates the types of connected devices. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Default Value| Description | +| :------------------------------ | :----- | :--------------------- | +| CONNECT_TYPE_LOCAL | 1 | Local device. | +| CONNECT_TYPE_DISTRIBUTED | 2 | Distributed device. | + +## VolumeGroupInfo9+ + +Describes the volume group information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +| Name | Type | Readable| Writable| Description | +| -------------------------- | -------------------------- | ---- | ---- | ---------- | +| networkId9+ | string | Yes | No | Network ID of the device. | +| groupId9+ | number | Yes | No | Group ID of the device.| +| mappingId9+ | number | Yes | No | Group mapping ID.| +| groupName9+ | number | Yes | No | Group name.| +| ConnectType9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| + +## VolumeGroupInfos9+ + +Describes the volume group information. The value is an array of [VolumeGroupInfo](#volumegroupinfo9) and is read-only. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} +getVolumeGroupInfos(); +``` ## DeviceChangeAction @@ -656,17 +755,6 @@ Describes audio capturer information. | source | [SourceType](#sourcetype) | Yes | Audio source type. | | capturerFlags | number | Yes | Audio capturer flags.| -## AudioRendererDataInfo9+ - -Describes the information of the audio renderer. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -| Name | Type | Mandatory | Description | -| ------- | ----------- | -------| ------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be filled in. | -| flags | number | Yes | Extension information of the buffer. | - ## SourceType8+ Enumerates the audio source types. @@ -692,17 +780,70 @@ Enumerates the audio scenes. | AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.| | AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. | + ## AudioManager Implements audio volume and audio device management. Before calling any API in **AudioManager**, you must use [getAudioManager](#audiogetaudiomanager) to create an **AudioManager** instance. +### getRoutingManager9+ + +getRoutingManager(callback: AsyncCallback<AudioRoutingManager>): void + +Obtains an **AudioRoutingManager** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------------------- | ---- | --------------------------------- | +| callback | AsyncCallback<[AudioRoutingManager](#audioroutingmanager9)> | Yes | Callback used to return the **AudioRoutingManager** instance.| + +**Example** +```js +await audioManager.getRoutingManager((err, callback) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } + console.info('getRoutingManager Callback SUCCESS.'); + var audioRoutingManager; + audioRoutingManager = callback; +}); +``` + +### getRoutingManager9+ + +getRoutingManager(): Promise<AudioRoutingManager> + +Obtains an **AudioRoutingManager** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | --------------------------------------- | +| Promise<[AudioRoutingManager](#audioroutingmanager9)> | Promise used to return the **AudioRoutingManager** instance.| + +**Example** +```js +await audioManager.getRoutingManager().then((value) => { + var routingManager = value; + console.info('getRoutingManager Promise SUCCESS.'); +}).catch((err) => { + console.error(`Result ERROR: ${err}`); +}); +``` + ### setVolume setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void Sets the volume for a stream. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -716,13 +857,13 @@ Sets the volume for a stream. This API uses an asynchronous callback to return t **Example** -``` +```js audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { - console.error(`Failed to set the volume. ${err.message}`); + console.error(`Failed to set the volume. ${err}`); return; } - console.log(`Callback invoked to indicate a successful volume setting.`); + console.info('Callback invoked to indicate a successful volume setting.'); }); ``` @@ -732,7 +873,9 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -751,9 +894,9 @@ Sets the volume for a stream. This API uses a promise to return the result. **Example** -``` +```js audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.log(`Promise returned to indicate a successful volume setting.`); + console.info('Promise returned to indicate a successful volume setting.'); }); ``` @@ -774,13 +917,13 @@ Obtains the volume of a stream. This API uses an asynchronous callback to return **Example** -``` +```js audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the volume. ${err.message}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.log(`Callback invoked to indicate that the volume is obtained.`); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` @@ -806,9 +949,9 @@ Obtains the volume of a stream. This API uses a promise to return the result. **Example** -``` +```js audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.log(`Promise returned to indicate that the volume is obtained.` + value); + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); }); ``` @@ -829,13 +972,13 @@ Obtains the minimum volume allowed for a stream. This API uses an asynchronous c **Example** -``` +```js audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the minimum volume. ${err.message}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.log(`Callback invoked to indicate that the minimum volume is obtained.` + value); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` @@ -861,9 +1004,9 @@ Obtains the minimum volume allowed for a stream. This API uses a promise to retu **Example** -``` +```js audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.log(`Promised returned to indicate that the minimum volume is obtained.` + value); + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); }); ``` @@ -884,13 +1027,13 @@ Obtains the maximum volume allowed for a stream. This API uses an asynchronous c **Example** -``` +```js audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err.message}`); + console.error(`Failed to obtain the maximum volume. ${err}`); return; } - console.log(`Callback invoked to indicate that the maximum volume is obtained.` + value); + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` @@ -916,9 +1059,9 @@ Obtains the maximum volume allowed for a stream. This API uses a promise to retu **Example** -``` +```js audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.log(`Promised returned to indicate that the maximum volume is obtained.`); + console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` @@ -928,7 +1071,9 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -942,13 +1087,13 @@ Mutes or unmutes a stream. This API uses an asynchronous callback to return the **Example** -``` +```js audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error(`Failed to mute the stream. ${err.message}`); + console.error(`Failed to mute the stream. ${err}`); return; } - console.log(`Callback invoked to indicate that the stream is muted.`); + console.info('Callback invoked to indicate that the stream is muted.'); }); ``` @@ -958,7 +1103,9 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> Mutes or unmutes a stream. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -978,9 +1125,9 @@ Mutes or unmutes a stream. This API uses a promise to return the result. **Example** -``` +```js audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.log(`Promise returned to indicate that the stream is muted.`); + console.info('Promise returned to indicate that the stream is muted.'); }); ``` @@ -1002,13 +1149,13 @@ Checks whether a stream is muted. This API uses an asynchronous callback to retu **Example** -``` +```js audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status. ${err.message}`); + console.error(`Failed to obtain the mute status. ${err}`); return; } - console.log(`Callback invoked to indicate that the mute status of the stream is obtained.` + value); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` @@ -1035,9 +1182,9 @@ Checks whether a stream is muted. This method uses a promise to return the resul **Example** -``` +```js audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.log(`Promise returned to indicate that the mute status of the stream is obtained.` + value); + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` @@ -1058,13 +1205,13 @@ Checks whether a stream is active. This API uses an asynchronous callback to ret **Example** -``` +```js audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the stream. ${err.message}`); + console.error(`Failed to obtain the active status of the stream. ${err}`); return; } - console.log(`Callback invoked to indicate that the active status of the stream is obtained.` + value); + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` @@ -1090,9 +1237,9 @@ Checks whether a stream is active. This method uses a promise to return the resu **Example** -``` +```js audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.log(`Promise returned to indicate that the active status of the stream is obtained.` + value); + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); ``` @@ -1102,7 +1249,9 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer mode. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer. **System capability**: SystemCapability.Multimedia.Audio.Communication @@ -1115,13 +1264,13 @@ Sets the ringer mode. This API uses an asynchronous callback to return the resul **Example** -``` +```js audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`Failed to set the ringer mode.​ ${err.message}`); + console.error(`Failed to set the ringer mode.​ ${err}`); return; } - console.log(`Callback invoked to indicate a successful setting of the ringer mode.`); + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` @@ -1131,7 +1280,9 @@ setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer mode. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY (This permission is required only for muting or unmuting the ringer.) +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer. **System capability**: SystemCapability.Multimedia.Audio.Communication @@ -1149,9 +1300,9 @@ Sets the ringer mode. This API uses a promise to return the result. **Example** -``` +```js audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.log(`Promise returned to indicate a successful setting of the ringer mode.`); + console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` @@ -1172,13 +1323,13 @@ Obtains the ringer mode. This API uses an asynchronous callback to return the re **Example** -``` +```js audioManager.getRingerMode((err, value) => { if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err.message}`); + console.error(`Failed to obtain the ringer mode.​ ${err}`); return; } - console.log(`Callback invoked to indicate that the ringer mode is obtained.` + value); + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` @@ -1199,9 +1350,9 @@ Obtains the ringer mode. This API uses a promise to return the result. **Example** -``` +```js audioManager.getRingerMode().then((value) => { - console.log(`Promise returned to indicate that the ringer mode is obtained.` + value); + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` @@ -1227,13 +1378,13 @@ This API is used to extend the audio configuration based on the hardware capabil **Example** -``` +```js audioManager.setAudioParameter('key_example', 'value_example', (err) => { if (err) { - console.error(`Failed to set the audio parameter. ${err.message}`); + console.error(`Failed to set the audio parameter. ${err}`); return; } - console.log(`Callback invoked to indicate a successful setting of the audio parameter.`); + console.info('Callback invoked to indicate a successful setting of the audio parameter.'); }); ``` @@ -1264,9 +1415,9 @@ This API is used to extend the audio configuration based on the hardware capabil **Example** -``` +```js audioManager.setAudioParameter('key_example', 'value_example').then(() => { - console.log(`Promise returned to indicate a successful setting of the audio parameter.`); + console.info('Promise returned to indicate a successful setting of the audio parameter.'); }); ``` @@ -1289,13 +1440,13 @@ This API is used to extend the audio configuration based on the hardware capabil **Example** -``` +```js audioManager.getAudioParameter('key_example', (err, value) => { if (err) { - console.error(`Failed to obtain the value of the audio parameter. ${err.message}`); + console.error(`Failed to obtain the value of the audio parameter. ${err}`); return; } - console.log(`Callback invoked to indicate that the value of the audio parameter is obtained.` + value); + console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` @@ -1323,9 +1474,9 @@ This API is used to extend the audio configuration based on the hardware capabil **Example** -``` +```js audioManager.getAudioParameter('key_example').then((value) => { - console.log(`Promise returned to indicate that the value of the audio parameter is obtained.` + value); + console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` @@ -1345,13 +1496,13 @@ Obtains the audio devices with a specific flag. This API uses an asynchronous ca | callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** -``` +```js audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error(`Failed to obtain the device list. ${err.message}`); + console.error(`Failed to obtain the device list. ${err}`); return; } - console.log(`Callback invoked to indicate that the device list is obtained.`); + console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` @@ -1377,9 +1528,9 @@ Obtains the audio devices with a specific flag. This API uses a promise to retur **Example** -``` +```js audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.log(`Promise returned to indicate that the device list is obtained.`); + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` @@ -1401,13 +1552,13 @@ Sets a device to the active state. This API uses an asynchronous callback to ret **Example** -``` +```js audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { if (err) { - console.error(`Failed to set the active status of the device. ${err.message}`); + console.error(`Failed to set the active status of the device. ${err}`); return; } - console.log(`Callback invoked to indicate that the device is set to the active status.`); + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` @@ -1435,9 +1586,9 @@ Sets a device to the active state. This API uses a promise to return the result. **Example** -``` +```js audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.log(`Promise returned to indicate that the device is set to the active status.`); + console.info('Promise returned to indicate that the device is set to the active status.'); }); ``` @@ -1458,13 +1609,13 @@ Checks whether a device is active. This API uses an asynchronous callback to ret **Example** -``` +```js audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err.message}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.log(`Callback invoked to indicate that the active status of the device is obtained.`); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` @@ -1491,9 +1642,9 @@ Checks whether a device is active. This API uses a promise to return the result. **Example** -``` +```js audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.log(`Promise returned to indicate that the active status of the device is obtained.` + value); + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` @@ -1516,13 +1667,13 @@ Mutes or unmutes the microphone. This API uses an asynchronous callback to retur **Example** -``` +```js audioManager.setMicrophoneMute(true, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err.message}`); + console.error(`Failed to mute the microphone. ${err}`); return; } - console.log(`Callback invoked to indicate that the microphone is muted.`); + console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` @@ -1550,9 +1701,9 @@ Mutes or unmutes the microphone. This API uses a promise to return the result. **Example** -``` +```js audioManager.setMicrophoneMute(true).then(() => { - console.log(`Promise returned to indicate that the microphone is muted.`); + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` @@ -1574,13 +1725,13 @@ Checks whether the microphone is muted. This API uses an asynchronous callback t **Example** -``` +```js audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err.message}`); + console.error(`Failed to obtain the mute status of the microphone. ${err}`); return; } - console.log(`Callback invoked to indicate that the mute status of the microphone is obtained.` + value); + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` @@ -1603,9 +1754,9 @@ Checks whether the microphone is muted. This API uses a promise to return the re **Example** -``` +```js audioManager.isMicrophoneMute().then((value) => { - console.log(`Promise returned to indicate that the mute status of the microphone is obtained.`, + value); + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` @@ -1615,7 +1766,7 @@ on(type: 'volumeChange', callback: Callback\): void Subscribes to system volume change events. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. @@ -1630,11 +1781,11 @@ Currently, when multiple **AudioManager** instances are used in a single process **Example** -``` +```js audioManager.on('volumeChange', (volumeEvent) => { - console.log(`VolumeType of stream: ` + volumeEvent.volumeType); - console.log(`Volume level: ` + volumeEvent.volume); - console.log(`Whether to updateUI: ` + volumeEvent.updateUi); + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` @@ -1644,7 +1795,7 @@ on(type: 'ringerModeChange', callback: Callback\): void Subscribes to ringer mode change events. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Audio.Communication @@ -1653,13 +1804,13 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | **Example** -``` +```js audioManager.on('ringerModeChange', (ringerMode) => { - console.log(`Updated ringermode: ` + ringerMode); + console.info(`Updated ringermode: ${ringerMode}`); }); ``` @@ -1680,12 +1831,12 @@ Subscribes to device change events. When a device is connected or disconnected, **Example** -``` +```js audioManager.on('deviceChange', (deviceChanged) => { - console.info(`device change type : ` + deviceChanged.type); - console.info(`device descriptor size : ` + deviceChanged.deviceDescriptors.length); - console.info(`device change descriptor : ` + deviceChanged.deviceDescriptors[0].deviceRole); - console.info(`device change descriptor : ` + deviceChanged.deviceDescriptors[0].deviceType); + console.info(`device change type : ${deviceChanged.type} `); + console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); }); ``` @@ -1706,9 +1857,9 @@ Unsubscribes from device change events. **Example** -``` +```js audioManager.off('deviceChange', (deviceChanged) => { - console.log(`Should be no callback.`); + console.info('Should be no callback.'); }); ``` @@ -1730,7 +1881,7 @@ Subscribes to audio interruption events. When the application's audio is interru **Example** -``` +```js var interAudioInterrupt = { streamUsage:2, contentType:0, @@ -1738,12 +1889,12 @@ var interAudioInterrupt = { }; audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { if (InterruptAction.actionType === 0) { - console.log(`An event to gain the audio focus starts.`); - console.log(`Focus gain event:` + JSON.stringify(InterruptAction)); + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); } if (InterruptAction.actionType === 1) { - console.log(`An audio interruption event starts.`); - console.log(`Audio interruption event:` + JSON.stringify(InterruptAction)); + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); ``` @@ -1766,7 +1917,7 @@ Unsubscribes from audio interruption events. **Example** -``` +```js var interAudioInterrupt = { streamUsage:2, contentType:0, @@ -1774,8 +1925,8 @@ var interAudioInterrupt = { }; audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { if (InterruptAction.actionType === 0) { - console.log(`An event to release the audio focus starts.`); - console.log(`Focus release event:` + JSON.stringify(InterruptAction)); + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); } }); ``` @@ -1786,7 +1937,7 @@ setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void Sets an audio scene. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Audio.Communication @@ -1799,13 +1950,13 @@ This is a system API and cannot be called by third-party applications. **Example** -``` +```js audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { - console.error(`Failed to set the audio scene mode.​ ${err.message}`); + console.error(`Failed to set the audio scene mode.​ ${err}`); return; } - console.log(`Callback invoked to indicate a successful setting of the audio scene mode.`); + console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` @@ -1815,7 +1966,7 @@ setAudioScene\(scene: AudioScene\): Promise Sets an audio scene. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.Audio.Communication @@ -1833,11 +1984,11 @@ This is a system API and cannot be called by third-party applications. **Example** -``` +```js audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { - console.log(`Promise returned to indicate a successful setting of the audio scene mode.`); + console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { - console.log(`Failed to set the audio scene mode`); + console.error(`Failed to set the audio scene mode ${err}`); }); ``` @@ -1857,13 +2008,13 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** -``` +```js audioManager.getAudioScene((err, value) => { if (err) { - console.error(`Failed to obtain the audio scene mode.​ ${err.message}`); + console.error(`Failed to obtain the audio scene mode.​ ${err}`); return; } - console.log(`Callback invoked to indicate that the audio scene mode is obtained.` + value); + console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); }); ``` @@ -1884,388 +2035,1319 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** -``` +```js audioManager.getAudioScene().then((value) => { - console.log(`Promise returned to indicate that the audio scene mode is obtained.` + value); + console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { - console.log(`Failed to obtain the audio scene mode`); + console.error(`Failed to obtain the audio scene mode ${err}`); }); ``` -## AudioStreamManager9+ - -Implements audio stream management. Before calling any API of **AudioStreamManager**, you must use **[getStreamManager](#audiogetstreammanager9)** to obtain an **AudioStreamManager** instance. +### getVolumeGroups9+ -### getCurrentAudioRendererInfoArray9+ +getVolumeGroups(networkId: string, callback: AsyncCallback\): void -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +Obtains the volume groups. This API uses an asynchronous callback to return the result. -Obtains the information about the current audio renderers. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. You can call **getRoutingManager().getDevices()** to obtain all network IDs. | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| **Example** -``` -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info(`getCurrentAudioRendererInfoArray **** Get Callback Called ****`); +```js +audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.log(`getCurrentAudioRendererInfoArray :ERROR: `+ err.message); - resultFlag = false; - } else { - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for` + i + `is:` + AudioRendererChangeInfo.streamId); - console.info(`ClientUid for` + i + `is:` + AudioRendererChangeInfo.clientUid); - console.info(`Content` + i + `is:` + AudioRendererChangeInfo.rendererInfo.content); - console.info(`Stream`+ i + `is:` + AudioRendererChangeInfo.rendererInfo.usage); - console.info(`Flag`+ i + `is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info(`State for` + i + `is:` + AudioRendererChangeInfo.rendererState); - var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCount` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info(`ChannelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } - } - } + console.error(`Failed to obtain the volume group infos list. ${err}`); + return; } + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### getCurrentAudioRendererInfoArray9+ +### getVolumeGroups9+ -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +getVolumeGroups(networkId: string\): Promise -Obtains the information about the current audio renderers. This API uses a promise to return the result. +Obtains the volume groups. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. You can call **getRoutingManager().getDevices()** to obtain all network IDs. | **Return value** -| Type | Description | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information list.| **Example** -``` -await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for` + i + ` is:` + AudioRendererChangeInfo.streamId); - console.info(`ClientUid for` + i + ` is:` + AudioRendererChangeInfo.clientUid); - console.info(`Content` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.content); - console.info(`Stream` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.usage); - console.info(`Flag` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info(`State for` + i + ` is:` + AudioRendererChangeInfo.rendererState); - var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCounts` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info(`ChannnelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } - } - } -}).catch((err) => { - console.log(`getCurrentAudioRendererInfoArray :ERROR: ` + err.message); -}); + +```js +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeGroups(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} ``` -### getCurrentAudioCapturerInfoArray9+ +### getGroupManager9+ -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +getGroupManager(groupId: number, callback: AsyncCallback\): void -Obtains the information about the current audio capturers. This API uses an asynchronous callback to return the result. +Obtains the audio group manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. | +| callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | Yes | Callback used to return the audio group manager.| **Example** -``` -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info(`getCurrentAudioCapturerInfoArray **** Get Callback Called ****`); - if (err) { - console.log(`getCurrentAudioCapturerInfoArray :ERROR: ` + err.message); - } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); - console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); - console.info(`Source for `+ i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); - var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); - } + +```js +async function getGroupManager(){ + let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); + if (value.length > 0) { + let groupid = value[0].groupId; + audioManager.getGroupManager(groupid, (err, value) => { + if (err) { + console.error(`Failed to obtain the volume group infos list. ${err}`); + return; } - } + audioGroupManager = value + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); + }); } -}); +} ``` -### getCurrentAudioCapturerInfoArray9+ +### getGroupManager9+ -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +getGroupManager(groupId: number\): Promise -Obtains the information about the current audio capturers. This API uses a promise to return the result. +Obtains the audio group manager. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | -------------- -- | +| networkId | string | Yes | Network ID of the device. | **Return value** -| Type | Description | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | +| Type | Description | +| ------------------- | ----------------------------- | +| Promise< [AudioGroupManager](#audiogroupmanager9) > | Promise used to return the audio group manager.| **Example** + +```js +async function getGroupManager(){ + let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); + if (value.length > 0) { + let groupid = value[0].groupId; + let audioGroupManager = await audioManager.getGroupManager(audio.LOCAL_NETWORK_ID) + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); + } +} ``` -await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info(`getCurrentAudioCapturerInfoArray **** Get Promise Called ****`); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); - console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); - console.info(`Source for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); - var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; +### requestIndependentInterrupt9+ + +requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void + +Requests independent interruption and obtains an interruption session ID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------- | +| focusType | [FocusType](#focustype) | Yes | Focus type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +async function requestIndependentInterrupt(){ + let value = await audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING); + if (value) { + console.info('requestIndependentInterrupt interface for result callback: SUCCESS'); + } else { + console.error('Result ERROR'); + } +} +``` +### requestIndependentInterrupt9+ + +requestIndependentInterrupt(focusType: FocusType: Promise + +Requests independent interruption and obtains an interruption session ID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| focusType | [FocusType](#focustype) | Yes | Focus type. | + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | ------------ | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +async function requestIndependentInterrupt(){ + audioManager.requestIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => { + console.info('Promise returned to succeed '); + }).catch ((err) => { + console.error('Failed to requestIndependentInterrupt'); + }); +} +``` +### abandonIndependentInterrupt9+ + +abandonIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void + +Abandons independent interruption. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------- | +| focusType | [FocusType](#focustype) | Yes | Focus type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +async function abandonIndependentInterrupt(){ + let value = await audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING); + if (value) { + console.info('abandonIndependentInterrupt interface for result callback: SUCCESS'); + } else { + console.error('Result ERROR'); + } +} +``` +### abandonIndependentInterrupt9+ + +abandonIndependentInterrupt(focusType: FocusType]: Promise + +Abandons independent interruption. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| focusType | [FocusType](#focustype) | Yes | Focus type. | + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | ------------ | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +async function abandonIndependentInterrupt(){ + audioManager.abandonIndependentInterrupt(audio.FocusType.FOCUS_TYPE_RECORDING).then((value) => { + console.info('Promise returned to succeed'); + }).catch ((err) => { + console.error('Failed to abandonIndependentInterrupt'); + }); +} +``` +## AudioGroupManager9+ +Manages the volume of an audio group. Before calling any API in **AudioGroupManager**, you must use [getGroupManager](#getgroupmanager9) to create an **AudioGroupManager** instance. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +### setVolume9+ + +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void + +Sets the volume for a stream. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { + if (err) { + console.error(`Failed to set the volume. ${err}`); + return; + } + console.info('Callback invoked to indicate a successful volume setting.'); +}); +``` + +### setVolume9+ + +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> + +Sets the volume for a stream. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); +``` + +### getVolume9+ + +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void + +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| + +**Example** + +```js +audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the volume. ${err}`); + return; + } + console.info('Callback invoked to indicate that the volume is obtained.'); +}); +``` + +### getVolume9+ + +getVolume(volumeType: AudioVolumeType): Promise<number> + +Obtains the volume of a stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| + +**Example** + +```js +audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); +}); +``` + +### getMinVolume9+ + +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void + +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| + +**Example** + +```js +audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the minimum volume. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); +}); +``` + +### getMinVolume9+ + +getMinVolume(volumeType: AudioVolumeType): Promise<number> + +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| + +**Example** + +```js +audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); +}); +``` + +### getMaxVolume9+ + +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void + +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| + +**Example** + +```js +audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the maximum volume. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); +}); +``` + +### getMaxVolume9+ + +getMaxVolume(volumeType: AudioVolumeType): Promise<number> + +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| + +**Example** + +```js +audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); +}); +``` + +### mute9+ + +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void + +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { + if (err) { + console.error(`Failed to mute the stream. ${err}`); + return; + } + console.info('Callback invoked to indicate that the stream is muted.'); +}); +``` + +### mute9+ + +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> + +Mutes or unmutes a stream. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); +}); +``` + +### isMute9+ + +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void + +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| + +**Example** + +```js +audioGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the mute status. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); +}); +``` + +### isMute9+ + +isMute(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is muted. This method uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| + +**Example** + +```js +audioGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); +}); +``` + +## AudioStreamManager9+ + +Implements audio stream management. Before calling any API of **AudioStreamManager**, you must use **[getStreamManager](#audiogetstreammanager9)** to obtain an **AudioStreamManager** instance. + +### getCurrentAudioRendererInfoArray9+ + +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void + +Obtains the information about the current audio renderers. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { + console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + } else { + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + } +}); +``` + +### getCurrentAudioRendererInfoArray9+ + +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> + +Obtains the information about the current audio renderers. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Return value** + +| Type | Description | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } +}).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); +}); +``` + +### getCurrentAudioCapturerInfoArray9+ + +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void + +Obtains the information about the current audio capturers. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { + console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + } else { + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + } +}); +``` + +### getCurrentAudioCapturerInfoArray9+ + +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> + +Obtains the information about the current audio capturers. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Return value** + +| Type | Description | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name) - console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } } } -}).catch((err) => { - console.log(`getCurrentAudioCapturerInfoArray :ERROR: ` + err.message); +}).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); +}); +``` + +### on('audioRendererChange')9+ + +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void + +Subscribes to audio renderer change events. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } +}); +``` + +### off('audioRendererChange')9+ + +off(type: "audioRendererChange"); + +Unsubscribes from audio renderer change events. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------- | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +audioStreamManager.off('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); +``` + +### on('audioCapturerChange')9+ + +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void + +Subscribes to audio capturer change events. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##'); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } +}); +``` + +### off('audioCapturerChange')9+ + +off(type: "audioCapturerChange"); + +Unsubscribes from audio capturer change events. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| + +**Example** + +```js +let audioStreamManager; +audio.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } }); + +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); + ``` +## AudioRoutingManager9+ -### on('audioRendererChange')9+ +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to create an **AudioRoutingManager** instance. -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void +### getDevices9+ -Subscribes to audio renderer change events. +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------- | --------- | ------------------------------------------------------------------------ | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | -| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** + +```js +audioManager.getRoutingManager((err,AudioRoutingManager)=>{ + if (err) { + console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); + } + else { + AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { + if (err) { + console.error(`Failed to obtain the device list. ${err}`); + return; + } + console.info('Callback invoked to indicate that the device list is obtained.'); + }); + } +}) ``` -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`## RendererChange on is called for ` + i + ` ##`); - console.info(`StreamId for ` + i + ` is:` + AudioRendererChangeInfo.streamId); - console.info(`ClientUid for ` + i + ` is:` + AudioRendererChangeInfo.clientUid); - console.info(`Content for ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.content); - console.info(`Stream for ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.usage); - console.info(`Flag ` + i + ` is:` + AudioRendererChangeInfo.rendererInfo.rendererFlags); - console.info(`State for ` + i + ` is:` + AudioRendererChangeInfo.rendererState); - var devDescriptor = AudioRendererChangeInfo.deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].name); - console.info(`Address:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCounts` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info(`ChannelMask:` + i + `:` + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } + +### getDevices9+ + +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> + +Obtains the audio devices with a specific flag. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| + +**Example** + +```js +audioManager.getRoutingManager((err,AudioRoutingManager)=>{ + if (err) { + console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); + } + else { + AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); + }); } }); ``` -### off('audioRendererChange')9+ +### on9+ -off(type: "audioRendererChange"); +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -Unsubscribes from audio renderer change events. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------- | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | **Example** -``` -audioStreamManager.off('audioRendererChange'); -console.info(`######### RendererChange Off is called #########`); + +```js +audioManager.getRoutingManager((err,AudioRoutingManager)=>{ + if (err) { + console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); + } + else { + AudioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type : ' + deviceChanged.type); + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } +}); ``` -### on('audioCapturerChange')9+ +### off9+ -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +off(type: 'deviceChange', callback?: Callback): void -Subscribes to audio capturer change events. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------------------------------------------------------------------- | -| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback\<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** -``` -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(` ## CapChange on is called for element ' + i + ' ##'); - console.info(`StreamId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); - console.info(`ClientUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); - console.info(`Source for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info(`Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info(`State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info(`Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(`Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(`Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info(`Address:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info(`SampleRates:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(`ChannelCounts` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(`ChannelMask:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); - } + +```js +audioManager.getRoutingManager((err,AudioRoutingManager)=>{ + if (err) { + console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); + } + else { + AudioRoutingManager.off('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('Should be no callback.'); + }); } }); ``` -### off('audioCapturerChange')9+ +### selectOutputDevice9+ -off(type: "audioCapturerChange"); +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Unsubscribes from audio capturer change events. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** +```js +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; +await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +}); ``` -audioStreamManager.off('audioCapturerChange'); -console.info(`######### CapturerChange Off is called #########`); -``` +### selectOutputDevice9+ -### isAudioRendererLowLatencySupported9+ +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> -isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo, callback: Callback<boolean>): void; +**System API**: This is a system API. -Checks whether the system supports the low latency configuration in the audio renderer. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------- | -------- | --------------------------------------- | -| streaminfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information. | -| callback | Callback<boolean> | Yes | Callback used to return the result. If the system supports the low latency configuration, **true** is returned. Otherwise, **false** is returned.| +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** +```js +let outputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; +await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +}); ``` -var audioManager = audio.getAudioManager(); -var AudioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} +### selectOutputDeviceByFilter9+ + +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void + +**System API**: This is a system API. + +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. -var audioStreamManager = audioManager.getStreamManager(); -audioStreamManager.isAudioRendererLowLatencySupported(AudioStreamInfo, (result) => { - console.info(`isAudioRendererLowLatencySupported success var = ` + result); +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; +await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); }); ``` -### isAudioRendererLowLatencySupported9+ +### selectOutputDeviceByFilter9+ -isAudioRendererLowLatencySupported(streaminfo: AudioStreamInfo): Promise<boolean> +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> -Checks whether the system supports the low latency configuration in the audio renderer. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------ | ---- | ------------| -| streaminfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information. | +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ---------------------------------------------------- | -| Promise<void> | Promise used to return the result. If the system supports the low latency configuration, **true** is returned. Otherwise, **false** is returned.| +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** -``` -var audioManager = audio.getAudioManager(); - -var AudioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioStreamManager = await audioManager.getStreamManager(); -var result = audioStreamManager.isAudioRendererLowLatencySupported(AudioStreamInfo); -console.info(`isAudioRendererLowLatencySupported success var =` + result); +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; +await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +}); ``` ## AudioRendererChangeInfo9+ @@ -2289,53 +3371,52 @@ Describes the **AudioRenderChangeInfo** array, which is read-only. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; var audioStreamManager; var audioStreamManagerCB; -var Tag = "AFCapLog : "; var resultFlag = false; await audioManager.getStreamManager().then(async function (data) { audioStreamManager = data; - console.info(Tag + `Get AudioStream Manager : Success `); + console.info('Get AudioStream Manager : Success'); }).catch((err) => { - console.info(Tag + `Get AudioStream Manager : ERROR : ` + err.message); + console.error(`Get AudioStream Manager : ERROR : ${err}`); }); audioManager.getStreamManager((err, data) => { if (err) { - console.error(Tag + `Get AudioStream Manager : ERROR : ` + err.message); + console.error(`Get AudioStream Manager : ERROR : ${err}`); } else { audioStreamManagerCB = data; - console.info(Tag + `Get AudioStream Manager : Success `); + console.info('Get AudioStream Manager : Success'); } }); audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(Tag + `## RendererChange on is called for ` + i + ` ##`); - console.info(Tag + `StreamId for ` + i + `is:` + AudioRendererChangeInfoArray[i].streamId); - console.info(Tag + `ClientUid for ` + i + `is:` + AudioRendererChangeInfoArray[i].clientUid); - console.info(Tag + `Content for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.content); - console.info(Tag + `Stream for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.usage); - console.info(Tag + `Flag ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags); - console.info(Tag + `State for ` + i + `is:` + AudioRendererChangeInfoArray[i].rendererState); + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); + console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); + console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); var devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(Tag + `Id:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].id); - console.info(Tag + `Type:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(Tag + `Role:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(Tag + `Name:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].name); - console.info(Tag + `Addr:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].address); - console.info(Tag + `SR:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(Tag + `C` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(Tag + `CM:` + i + `:` + AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { resultFlag = true; - console.info(Tag + `ResultFlag for ` + i + ` is:` + resultFlag); + console.info(`ResultFlag for ${i} is: ${resultFlag}`); } } }); @@ -2362,35 +3443,34 @@ Describes the **AudioCapturerChangeInfo** array, which is read-only. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; const audioManager = audio.getAudioManager(); -var Tag = "AFCapLog : "; var resultFlag = false; audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(Tag + ` ## CapChange on is called for element ' + i + ' ##'); - console.info(Tag + `StrId for ` + i + `is:` + AudioCapturerChangeInfoArray[i].streamId); - console.info(Tag + `CUid for ` + i + `is:` + AudioCapturerChangeInfoArray[i].clientUid); - console.info(Tag + `Src for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.source); - console.info(Tag + `Flag ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags); - console.info(Tag + `State for ` + i + `is:` + AudioCapturerChangeInfoArray[i].capturerState); + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); var devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(Tag + `Id:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id); - console.info(Tag + `Type:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType); - console.info(Tag + `Role:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole); - console.info(Tag + `Name:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name); - console.info(Tag + `Addr:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address); - console.info(Tag + `SR:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]); - console.info(Tag + `C` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]); - console.info(Tag + `CM:` + i + `:` + AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks); + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { resultFlag = true; - console.info(Tag + `ResultFlag for element ` + i + ` is: ` + resultFlag); - } + console.info(`ResultFlag for element ${i} is: ${resultFlag}`); + } } }); ``` @@ -2401,16 +3481,19 @@ Describes an audio device. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Readable| Writable| Description | -| -------------------------- | -------------------------- | ---- | ---- | ---------- | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name.| -| address9+ | string | Yes | No | Device address.| -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates.| -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported.| -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks.| +| Name | Type | Readable| Writable| Description | +| ----------------------------- | -------------------------- | ---- | ---- | ---------- | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name.| +| address9+ | string | Yes | No | Device address.| +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates.| +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported.| +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks.| +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications.| +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications.| +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications.| ## AudioDeviceDescriptors @@ -2418,7 +3501,7 @@ Array of [AudioDeviceDescriptor](#audiodevicedescriptor), which is read-only. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; function displayDeviceProp(value) { @@ -2430,16 +3513,42 @@ var deviceRoleValue = null; var deviceTypeValue = null; const promise = audio.getAudioManager().getDevices(1); promise.then(function (value) { - console.info(`AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG`); + console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); value.forEach(displayDeviceProp); if (deviceTypeValue != null && deviceRoleValue != null){ - console.info(`AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS`); + console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); } else { - console.info(`AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL`); + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); } }); ``` +## AudioRendererFilter9+ + +Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Type | Mandatory | Description | +| -------------| ---------------------------------------- | ---- | -------------- | +| uid | number | Yes | Application ID.
System capability: SystemCapability.Multimedia.Audio.Core| +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
System capability: SystemCapability.Multimedia.Audio.Renderer| +| rendererId | number | No | Unique ID of an audio stream.
System capability: SystemCapability.Multimedia.Audio.Renderer| + +**Example** + +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` + ## AudioRenderer8+ Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. @@ -2454,7 +3563,7 @@ Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, **Example** -``` +```js var state = audioRenderer.state; ``` @@ -2474,12 +3583,12 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Example** -``` +```js audioRenderer.getRendererInfo((err, rendererInfo) => { - console.log(`Renderer GetRendererInfo:`); - console.log(`Renderer content:` + rendererInfo.content); - console.log(`Renderer usage:` + rendererInfo.usage); - console.log(`Renderer flags:` + rendererInfo.rendererFlags); + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); }); ``` @@ -2499,16 +3608,14 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Example** -``` -var resultFlag = true; +```js audioRenderer.getRendererInfo().then((rendererInfo) => { - console.log(`Renderer GetRendererInfo:`); - console.log(`Renderer content:` + rendererInfo.content); - console.log(`Renderer usage:` + rendererInfo.usage); - console.log(`Renderer flags:` + rendererInfo.rendererFlags); + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) }).catch((err) => { - console.log(`AudioFrameworkRenderLog: RendererInfo :ERROR: ` + err.message); - resultFlag = false; + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); }); ``` @@ -2528,13 +3635,13 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Example** -``` +```js audioRenderer.getStreamInfo((err, streamInfo) => { - console.log(`Renderer GetStreamInfo:`); - console.log(`Renderer sampling rate:` + streamInfo.samplingRate); - console.log(`Renderer channel:` + streamInfo.channels); - console.log(`Renderer format:` + streamInfo.sampleFormat); - console.log(`Renderer encoding type:` + streamInfo.encodingType); + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); }); ``` @@ -2554,15 +3661,15 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Example** -``` +```js audioRenderer.getStreamInfo().then((streamInfo) => { - console.log(`Renderer GetStreamInfo:`); - console.log(`Renderer sampling rate:` + streamInfo.samplingRate); - console.log(`Renderer channel:` + streamInfo.channels); - console.log(`Renderer format:` + streamInfo.sampleFormat); - console.log(`Renderer encoding type:` + streamInfo.encodingType); + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2582,12 +3689,12 @@ Starts the renderer. This API uses an asynchronous callback to return the result **Example** -``` +```js audioRenderer.start((err) => { if (err) { - console.error(`Renderer start failed.`); + console.error('Renderer start failed.'); } else { - console.info(`Renderer start success.`); + console.info('Renderer start success.'); } }); ``` @@ -2608,11 +3715,11 @@ Starts the renderer. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.start().then(() => { - console.log(`Renderer started`); + console.info('Renderer started'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2632,12 +3739,12 @@ Pauses rendering. This API uses an asynchronous callback to return the result. **Example** -``` +```js audioRenderer.pause((err) => { if (err) { - console.error(`Renderer pause failed`); + console.error('Renderer pause failed'); } else { - console.log(`Renderer paused.`); + console.info('Renderer paused.'); } }); ``` @@ -2658,11 +3765,11 @@ Pauses rendering. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.pause().then(() => { - console.log(`Renderer paused`); + console.info('Renderer paused'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2682,12 +3789,12 @@ Drains the playback buffer. This API uses an asynchronous callback to return the **Example** -``` +```js audioRenderer.drain((err) => { if (err) { - console.error(`Renderer drain failed`); + console.error('Renderer drain failed'); } else { - console.log(`Renderer drained.`); + console.info('Renderer drained.'); } }); ``` @@ -2708,11 +3815,11 @@ Drains the playback buffer. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.drain().then(() => { - console.log(`Renderer drained successfully`); + console.info('Renderer drained successfully'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2732,12 +3839,12 @@ Stops rendering. This API uses an asynchronous callback to return the result. **Example** -``` +```js audioRenderer.stop((err) => { if (err) { - console.error(`Renderer stop failed`); + console.error('Renderer stop failed'); } else { - console.log(`Renderer stopped.`); + console.info('Renderer stopped.'); } }); ``` @@ -2758,11 +3865,11 @@ Stops rendering. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.stop().then(() => { - console.log(`Renderer stopped successfully`); + console.info('Renderer stopped successfully'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2782,12 +3889,12 @@ Releases the renderer. This API uses an asynchronous callback to return the resu **Example** -``` +```js audioRenderer.release((err) => { if (err) { - console.error(`Renderer release failed`); + console.error('Renderer release failed'); } else { - console.log(`Renderer released.`); + console.info('Renderer released.'); } }); ``` @@ -2808,11 +3915,11 @@ Releases the renderer. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.release().then(() => { - console.log(`Renderer released successfully`); + console.info('Renderer released successfully'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2833,7 +3940,7 @@ Writes the buffer. This API uses an asynchronous callback to return the result. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; import featureAbility from '@ohos.ability.featureAbility' @@ -2858,29 +3965,29 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data)=> { audioRenderer = data; - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS`); + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); }).catch((err) => { - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ` + err.message); + console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); }); var bufferSize; audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info.(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); + console.error.(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -console.info(`Buffer size:` + bufferSize); +console.info(`Buffer size: ${bufferSize}`); var context = featureAbility.getContext(); var path = await context.getCacheDir(); -var filePath = path + "/StarWars10s-2C-48000-4SW.wav"; +var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); audioRenderer.write(buf, (err, writtenbytes) => { if (writtenbytes < 0) { - console.error(`write failed.`); + console.error('write failed.'); } else { - console.log(`Actual written bytes: ` + writtenbytes); + console.info(`Actual written bytes: ${writtenbytes}`); } }); ``` @@ -2901,7 +4008,7 @@ Writes the buffer. This API uses a promise to return the result. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; import featureAbility from '@ohos.ability.featureAbility' @@ -2926,18 +4033,18 @@ var audioRendererOptions = { var audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS`); + console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); }).catch((err) => { - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ` + err.message); + console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); }); var bufferSize; audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -console.info(`BufferSize: ` + bufferSize); +console.info(`BufferSize: ${bufferSize}`); var context = featureAbility.getContext(); var path = await context.getCacheDir(); var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; @@ -2946,12 +4053,12 @@ let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); audioRenderer.write(buf).then((writtenbytes) => { if (writtenbytes < 0) { - console.error(`write failed.`); + console.error('write failed.'); } else { - console.log(`Actual written bytes: ` + writtenbytes); + console.info(`Actual written bytes: ${writtenbytes}`); } }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -2971,9 +4078,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Example** -``` +```js audioRenderer.getAudioTime((err, timestamp) => { - console.log(`Current timestamp: ` + timestamp); + console.info(`Current timestamp: ${timestamp}`); }); ``` @@ -2993,11 +4100,11 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Example** -``` +```js audioRenderer.getAudioTime().then((timestamp) => { - console.log(`Current timestamp: ` + timestamp); + console.info(`Current timestamp: ${timestamp}`); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -3017,10 +4124,10 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Example** -``` +```js var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { if (err) { - console.error(`getBufferSize error`); + console.error('getBufferSize error'); } }); ``` @@ -3041,7 +4148,7 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Example** -``` +```js import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; @@ -3067,14 +4174,14 @@ audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); }).catch((err) => { - console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ' + err.message); + console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); }); var bufferSize; audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ` + data); + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ` + err.message); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); ``` @@ -3095,12 +4202,12 @@ Sets the render rate. This API uses an asynchronous callback to return the resul **Example** -``` +```js audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { if (err) { - console.error(`Failed to set params`); + console.error('Failed to set params'); } else { - console.log(`Callback invoked to indicate a successful render rate setting.`); + console.info('Callback invoked to indicate a successful render rate setting.'); } }); ``` @@ -3127,11 +4234,11 @@ Sets the render rate. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.log(`setRenderRate SUCCESS`); + console.info('setRenderRate SUCCESS'); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` @@ -3151,9 +4258,9 @@ Obtains the current render rate. This API uses an asynchronous callback to retur **Example** -``` +```js audioRenderer.getRenderRate((err, renderrate) => { - console.log(`getRenderRate: ` + renderrate); + console.info(`getRenderRate: ${renderrate}`); }); ``` @@ -3173,11 +4280,11 @@ Obtains the current render rate. This API uses a promise to return the result. **Example** -``` +```js audioRenderer.getRenderRate().then((renderRate) => { - console.log(`getRenderRate: ` + renderRate); + console.info(`getRenderRate: ${renderRate}`); }).catch((err) => { - console.log(`ERROR: ` + err.message); + console.error(`ERROR: ${err}`); }); ``` ### setInterruptMode9+ @@ -3202,7 +4309,7 @@ Sets the audio interruption mode for the application. This API uses a promise to **Example** -``` +```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, channels: audio.AudioChannel.CHANNEL_1, @@ -3221,14 +4328,14 @@ var audioRendererOptions = { let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 0; audioRenderer.setInterruptMode(mode).then(data=>{ - console.log(`setInterruptMode Success!`); -}).catch(err=>{ - console.log(`setInterruptMode Fail:` + err.message); + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); }); ``` ### setInterruptMode9+ -setInterruptMode(mode: InterruptMode, callback: Callback\): void +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void Sets the audio interruption mode for the application. This API uses a callback to return the result. @@ -3239,11 +4346,11 @@ Sets the audio interruption mode for the application. This API uses a callback t | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ------ | -------------- | |mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode.| -|callback | Callback\ | Yes |Callback used to return the result.| +|callback | AsyncCallback\ | Yes |Callback used to return the result.| **Example** -``` +```js var audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, channels: audio.AudioChannel.CHANNEL_1, @@ -3263,9 +4370,9 @@ let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 1; audioRenderer.setInterruptMode(mode, (err, data)=>{ if(err){ - console.log(`setInterruptMode Fail:` + err.message); + console.error(`setInterruptMode Fail: ${err}`); } - console.log(`setInterruptMode Success!`); + console.info('setInterruptMode Success!'); }); ``` ### on('interrupt')9+ @@ -3285,47 +4392,47 @@ Subscribes to audio interruption events. This API uses a callback to get interru **Example** -``` +```js var isPlay; var started; audioRenderer.on('interrupt', async(interruptEvent) => { if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { switch (interruptEvent.hintType) { case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.log(`Force paused. Stop writing`); + console.info('Force paused. Stop writing'); isPlay = false; break; case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.log(`Force stopped. Stop writing`); + console.info('Force stopped. Stop writing'); isPlay = false; break; } } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { switch (interruptEvent.hintType) { case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.log(`Resume force paused renderer or ignore`); + console.info('Resume force paused renderer or ignore'); await audioRenderer.start().then(async function () { - console.info(`AudioInterruptMusic: renderInstant started :SUCCESS `); + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); started = true; }).catch((err) => { - console.info(`AudioInterruptMusic: renderInstant start :ERROR : ` + err.message); + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); started = false; }); if (started) { isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ` + isPlay); + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); } else { - console.error(`AudioInterruptMusic Renderer start failed`); + console.error('AudioInterruptMusic Renderer start failed'); } break; case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.log('Choose to pause or ignore'); + console.info('Choose to pause or ignore'); if (isPlay == true) { isPlay == false; - console.info(`AudioInterruptMusic: Media PAUSE : TRUE`); + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); } else { isPlay = true; - console.info(`AudioInterruptMusic: Media PLAY : TRUE`); + console.info('AudioInterruptMusic: Media PLAY : TRUE'); } break; } @@ -3335,7 +4442,7 @@ audioRenderer.on('interrupt', async(interruptEvent) => { ### on('markReach')8+ -on(type: 'markReach', frame: number, callback: (position: number) => {}): void +on(type: "markReach", frame: number, callback: Callback): void Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked. @@ -3347,14 +4454,14 @@ Subscribes to mark reached events. When the number of frames rendered reaches th | :------- | :----------------------- | :--- | :---------------------------------------- | | type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** -``` +```js audioRenderer.on('markReach', 1000, (position) => { if (position == 1000) { - console.log(`ON Triggered successfully`); + console.info('ON Triggered successfully'); } }); ``` @@ -3376,13 +4483,13 @@ Unsubscribes from mark reached events. **Example** -``` +```js audioRenderer.off('markReach'); ``` ### on('periodReach') 8+ -on(type: "periodReach", frame: number, callback: (position: number) => {}): void +on(type: "periodReach", frame: number, callback: Callback): void Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked. @@ -3393,15 +4500,15 @@ Subscribes to period reached events. When the period of frame rendering reaches | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | | type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** -``` +```js audioRenderer.on('periodReach', 1000, (position) => { if (position == 1000) { - console.log(`ON Triggered successfully`); + console.info('ON Triggered successfully'); } }); ``` @@ -3422,7 +4529,7 @@ Unsubscribes from period reached events. **Example** -``` +```js audioRenderer.off('periodReach') ``` @@ -3443,46 +4550,17 @@ Subscribes to state change events. **Example** -``` +```js audioRenderer.on('stateChange', (state) => { if (state == 1) { - console.log(`audio renderer state is: STATE_PREPARED`); + console.info('audio renderer state is: STATE_PREPARED'); } if (state == 2) { - console.log(`audio renderer state is: STATE_RUNNING`); + console.info('audio renderer state is: STATE_RUNNING'); } }); ``` -### on('dataRequest') 9+ - -on(type: "dataRequest", callback: Callback\): void; - -Subscribes to request events of audio data. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------- | --------- | ------------------------------------------------------------------- | -| type | string | Yes | Event type. The value **dataRequest** indicates a data request event.| -| callback | [AudioRendererDataInfo](#audiorendererdatainfo9) | Yes | Callback used to return the audio renderer information.| - -**Example** -``` -const path = '/data/storage/el2/ba se/haps/entry/cache/PinkPanther60-44100-1c.wav'; - let ss = fileio.createStreamSync(path, 'r'); - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - let rlen = 0; - audioRenderer.on('dataRequest', (audioRendererDataInfo) => { - var viewObject = new DataView(audioRendererDataInfo.buffer); - rlen += ss.readSync(viewObject.buffer); - console.info(`AudioRenderLog: bytes read from file: ` + rlen); - }) -``` - ## AudioCapturer8+ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. @@ -3497,7 +4575,7 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo **Example** -``` +```js var state = audioCapturer.state; ``` @@ -3517,14 +4595,14 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Example** -``` +```js audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error(`Failed to get capture info`); + console.error('Failed to get capture info'); } else { - console.log(`Capturer getCapturerInfo:`); - console.log(`Capturer source:` + capturerInfo.source); - console.log(`Capturer flags:` + capturerInfo.capturerFlags); + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); ``` @@ -3546,18 +4624,18 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Example** -``` +```js audioCapturer.getCapturerInfo().then((audioParamsGet) => { if (audioParamsGet != undefined) { - console.info(`AudioFrameworkRecLog: Capturer CapturerInfo:`); - console.info(`AudioFrameworkRecLog: Capturer SourceType:` + audioParamsGet.source); - console.info(`AudioFrameworkRecLog: Capturer capturerFlags:` + audioParamsGet.capturerFlags); + console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); + console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ` + audioParamsGet); - console.info(`AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect: `); + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); } }).catch((err) => { - console.log(`AudioFrameworkRecLog: CapturerInfo :ERROR: ` + err.message); + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); ``` @@ -3577,16 +4655,16 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Example** -``` +```js audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error(`Failed to get stream info'); + console.error('Failed to get stream info'); } else { - console.log(`Capturer GetStreamInfo:`); - console.log(`Capturer sampling rate:` + streamInfo.samplingRate); - console.log(`Capturer channel:` + streamInfo.channels); - console.log(`Capturer format:` + streamInfo.sampleFormat); - console.log(`Capturer encoding type:` + streamInfo.encodingType); + console.info('Capturer GetStreamInfo:'); + console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Capturer channel: ${streamInfo.channels}`); + console.info(`Capturer format: ${streamInfo.sampleFormat}`); + console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); ``` @@ -3607,15 +4685,15 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Example** -``` +```js audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info(`getStreamInfo:`); - console.info(`sampleFormat:` + audioParamsGet.sampleFormat); - console.info(`samplingRate:` + audioParamsGet.samplingRate); - console.info(`channels:` + audioParamsGet.channels); - console.info(`encodingType:` + audioParamsGet.encodingType); + console.info('getStreamInfo:'); + console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); + console.info(`samplingRate: ${audioParamsGet.samplingRate}`); + console.info(`channels: ${audioParamsGet.channels}`); + console.info(`encodingType: ${audioParamsGet.encodingType}`); }).catch((err) => { - console.log(`getStreamInfo :ERROR: ` + err.message); + console.error(`getStreamInfo :ERROR: ${err}`); }); ``` @@ -3635,12 +4713,12 @@ Starts capturing. This API uses an asynchronous callback to return the result. **Example** -``` +```js audioCapturer.start((err) => { if (err) { - console.error(`Capturer start failed.`); + console.error('Capturer start failed.'); } else { - console.info(`Capturer start success.`); + console.info('Capturer start success.'); } }); ``` @@ -3662,7 +4740,7 @@ Starts capturing. This API uses a promise to return the result. **Example** -``` +```js import audio from '@ohos.multimedia.audio'; import fileio from '@ohos.fileio'; @@ -3679,24 +4757,22 @@ var audioCapturerInfo = { } var audioCapturer; -var stateFlag; audio.createAudioCapturer(audioCapturerOptions).then((data) => { audioCapturer = data; - console.info(`AudioFrameworkRecLog: AudioCapturer Created: SUCCESS`); + console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created: ERROR: ` + err.message); + console.info(`AudioFrameworkRecLog: AudioCapturer Created: ERROR: ${err}`); }); audioCapturer.start().then(() => { - console.info(`AudioFrameworkRecLog: ---------START---------`); - console.info(`AudioFrameworkRecLog: Capturer started: SUCCESS`); - console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ` + audioCapturer.state); - console.info(`AudioFrameworkRecLog: Capturer started: SUCCESS `); + console.info('AudioFrameworkRecLog: ---------START---------'); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info(`AudioFrameworkRecLog: AudioCapturer is in Running State`); + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); } }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ` + err.message); - stateFlag = false; + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); ``` @@ -3716,12 +4792,12 @@ Stops capturing. This API uses an asynchronous callback to return the result. **Example** -``` +```js audioCapturer.stop((err) => { if (err) { - console.error(`Capturer stop failed`); + console.error('Capturer stop failed'); } else { - console.log(`Capturer stopped.`); + console.info('Capturer stopped.'); } }); ``` @@ -3743,15 +4819,15 @@ Stops capturing. This API uses a promise to return the result. **Example** -``` +```js audioCapturer.stop().then(() => { - console.info(`AudioFrameworkRecLog: ---------STOP RECORD---------`); - console.info(`AudioFrameworkRecLog: Capturer stopped: SUCCESS`); + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info(`AudioFrameworkRecLog: State is Stopped: `); + console.info('AudioFrameworkRecLog: State is Stopped:'); } }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ` + err.message); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` @@ -3771,12 +4847,12 @@ Releases this **AudioCapturer** instance. This API uses an asynchronous callback **Example** -``` +```js audioCapturer.release((err) => { if (err) { - console.error(`capturer release failed`); + console.error('capturer release failed'); } else { - console.log(`capturer released.`); + console.info('capturer released.'); } }); ``` @@ -3798,15 +4874,15 @@ Releases this **AudioCapturer** instance. This API uses a promise to return the **Example** -``` +```js var stateFlag; audioCapturer.release().then(() => { - console.info(`AudioFrameworkRecLog: ---------RELEASE RECORD---------`); - console.info(`AudioFrameworkRecLog: Capturer release : SUCCESS`); - console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ` + audioCapturer.state); - console.info(`AudioFrameworkRecLog: stateFlag : ` + stateFlag); + console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); + console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ` + err.message); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` @@ -3829,17 +4905,17 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Example** -``` +```js var bufferSize; audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ` + data); + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: EROOR: ` + err.message); + console.error(`AudioFrameworkRecLog: getBufferSize: EROOR: ${err}`); }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { - console.log(`Success in reading the buffer data`); + console.info('Success in reading the buffer data'); } }); ``` @@ -3868,19 +4944,19 @@ Reads the buffer. This API uses a promise to return the result. **Example** -``` +```js var bufferSize; audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ` + data); + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ` + err.message); + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); }); -console.info(`Buffer size: ` + bufferSize); +console.info(`Buffer size: ${bufferSize}`); audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`buffer read successfully`); + console.info('buffer read successfully'); }).catch((err) => { - console.info(`ERROR : ` + err.message); + console.info(`ERROR : ${err}`); }); ``` @@ -3897,13 +4973,13 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). | Name | Type | Mandatory| Description | | :------- | :--------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the timestamp. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** -``` +```js audioCapturer.getAudioTime((err, timestamp) => { - console.log(`Current timestamp: ` + timestamp); + console.info(`Current timestamp: ${timestamp}`); }); ``` @@ -3924,11 +5000,11 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Example** -``` +```js audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success` + audioTime ); + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ` + err.message); + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` @@ -3949,14 +5025,14 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Example** -``` +```js audioCapturer.getBufferSize((err, bufferSize) => { if (!err) { - console.log(`BufferSize : ` + bufferSize); + console.info(`BufferSize : ${bufferSize}`); audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ` + buffer ); + console.info(`Buffer read is ${buffer}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ` + err.message); + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); } }); @@ -3979,20 +5055,20 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Example** -``` +```js var bufferSize; audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ` + data); + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ` + err.message); + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` ### on('markReach')8+ -on(type: 'markReach', frame: number, callback: (position: number) => {}): void +on(type: "markReach", frame: number, callback: Callback): void Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked. @@ -4000,18 +5076,18 @@ Subscribes to mark reached events. When the number of frames captured reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | position: number) => {} | Yes | Callback invoked when the event is triggered.| +| Name | Type | Mandatory| Description | +| :------- | :---------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered.| **Example** -``` +```js audioCapturer.on('markReach', 1000, (position) => { if (position == 1000) { - console.log(`ON Triggered successfully`); + console.info('ON Triggered successfully'); } }); ``` @@ -4032,13 +5108,13 @@ Unsubscribes from mark reached events. **Example** -``` +```js audioCapturer.off('markReach'); ``` ### on('periodReach')8+ -on(type: "periodReach", frame: number, callback: (position: number) => {}): void +on(type: "periodReach", frame: number, callback: Callback): void Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked. @@ -4048,16 +5124,16 @@ Subscribes to mark reached events. When the period of frame capturing reaches th | Name | Type | Mandatory| Description | | :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter. | -| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | -| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** -``` +```js audioCapturer.on('periodReach', 1000, (position) => { if (position == 1000) { - console.log(`ON Triggered successfully`); + console.info('ON Triggered successfully'); } }); ``` @@ -4078,7 +5154,7 @@ Unsubscribes from period reached events. **Example** -``` +```js audioCapturer.off('periodReach') ``` @@ -4099,13 +5175,13 @@ Subscribes to state change events. **Example** -``` +```js audioCapturer.on('stateChange', (state) => { if (state == 1) { - console.log(`audio capturer state is: STATE_PREPARED`); + console.info('audio capturer state is: STATE_PREPARED'); } if (state == 2) { - console.log(`audio capturer state is: STATE_RUNNING`); + console.info('audio capturer state is: STATE_RUNNING'); } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..1cebb6079a073e36346e1756d9685d4c550b9c2d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -0,0 +1,2444 @@ +# Buffer + +> **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. + +A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. + +You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, receive and upload files, and use network protocols. + +## Modules to Import + +```ts +import buffer from '@ohos.buffer'; +``` + +## Buffer + +### alloc + +alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer + +Allocates and initializes a **Buffer** instance of the specified size. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| +| encoding | BufferEncoding | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Initialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.alloc(5); +let buf2 = buffer.alloc(5, 'a'); +let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +``` + +### allocUninitializedFromPool + +allocUninitializedFromPool(size: number): Buffer + +Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +To initialize the **Buffer** instance, call the **fill()** function. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Uninitialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(10); +buf.fill(0); +``` + +### allocUninitialized + +allocUninitialized(size: number): Buffer + +Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Uninitialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitialized(10); +buf.fill(0); +``` + +### byteLength + +byteLength(string: string | Buffer | TypeArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number + +Obtains the number of bytes of a string based on the encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| string | string \| Buffer \| TypeArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| +| encoding | BufferEncoding | No| Encoding format. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes of the string.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let str = '\u00bd + \u00bc = \u00be'; +console.log('${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes'); +// Print: ½ + ¼ = ¾: 9 characters, 12 bytes +``` + +### compare + +compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): number + +Compares two **Buffer** instances. + + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| buf1 | Buffer \| Uint8Array | Yes| **Buffer** instance to compare.| +| buf2 | Buffer \| Uint8Array | Yes| **Buffer** instance to compare.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if **buf1** is the same as **buf2**.
Returns **1** if **buf1** comes after **buf2** when sorted.
Returns **-1** if **buf1** comes before **buf2** when sorted.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('1234'); +let buf2 = buffer.from('0123'); + +console.log(buf1.compare(buf2)); +// Print 1 +``` + +### concat + +concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer + +Concatenates an array of **Buffer** instances into a new instance of the specified length. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| +| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from("1234"); +let buf2 = buffer.from("abcd"); +let buf = buffer.concat([buf1, buf2]); +console.log(buf); // +``` + +### from + +from(array: number[]): Buffer + +Creates a **Buffer** instance with the specified array. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| array | number[] | Yes| Array to create a **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let arrayList = new ArrayList(); + +let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); +console.log(buf); +// Print: +``` + +### from + +from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer + +Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| arrayBuffer | ArrayBuffer \| SharedArrayBuffer | Yes| Array of **Buffer** instances, whose memory is to be shared.| +| byteOffset | number | No| Byte offset. The default value is **0**.| +| length | number | No| Length of the **Buffer** instance to create, in bytes. The default value is the length of **arrayBuffer** minus **byteOffset**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance with shared memory.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let ab = new ArrayBuffer(10); +let buf = buffer.from(ab, 0, 2); +``` + +### from + +from(data: Buffer | Uint8Array): Buffer + +Creates a **Buffer** instance with the copy of another instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | Buffer \| Uint8Array | Yes| Instance to copy.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +let buf2 = buffer.from(buf1); +``` + +### from + +from(object: Object, offsetOrEncoding: number | string, length: number): Buffer + +Creates a **Buffer** instance based on the specified object. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| object | Object | Yes| Object that supports **Symbol.toPrimitive** or **valueOf()**.| +| offsetOrEncoding | number \| string | No| Byte offset or encoding format.| +| length | number | No| Length of the **Buffer** instance to create.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from(new String('this is a test')); +``` + +### from + +from(string: string, encoding?: BufferEncoding): Buffer + +Creates a **Buffer** instance based on a string in the given encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| string | string | Yes| String.| +| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('this is a test'); +let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); + +console.log (buf1.toString()); // Print: this is a test +console.log(buf2.toString()); +``` + + +### isBuffer + +isBuffer(obj: Object): boolean + +Checks whether the specified object is a **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| obj | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the object is a **Buffer** instance; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +buffer.isBuffer(buffer.alloc(10)); // true +buffer.isBuffer(buffer.from('foo')); // true +buffer.isBuffer('a string'); // false +buffer.isBuffer([]); // false +buffer.isBuffer(new Uint8Array(1024)); // false +``` + +### isEncoding + +isEncoding(encoding: string): boolean + +Checks whether the encoding format is supported. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | Yes| Encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the encoding format is supported; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +console.log (Buffer.isEncoding ('utf-8')); // Print: true +console.log (Buffer.isEncoding ('hex')); // Print: true +console.log (Buffer.isEncoding ('utf/8')); // Print: false +console.log (Buffer.isEncoding ('')); // Print: false +``` + +### compare + +compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 + +Compares this **Buffer** instance with another instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | Yes| Target **Buffer** instance to compare.| +| targetStart | number | No| Offset to the start of the data to compare in the target **Buffer** instance. The default value is **0**.| +| targetEnd | number | No| Offset to the end of the data to compare in the target **Buffer** instance (not inclusive). The default value is length of the target **Buffer** instance.| +| sourceStart | number | No| Offset to the start of the data to compare in this **Buffer** instance. The default value is **0**.| +| sourceEnd | number | No| Offset to the end of the data to compare in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if the target instance comes before this instance when sorted.
Returns **-1** if the target instance comes after this instance when sorted.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); +let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + +console.log (buf1.compare (buf2, 5, 9, 0, 4); // Print: 0 +console.log (buf1.compare (buf2, 0, 6, 4); // Print: -1 +console.log (buf1.compare (buf2, 5, 6, 5)); // Print: 1 +``` + +### copy + +copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number + +Copies data at the specified position in this **Buffer** instance to the specified position in another **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | Yes| Instance to which data is copied.| +| targetStart | number | No| Offset to the start position in the target instance where data is copied. The default value is **0**.| +| sourceStart | number | No| Offset to the start position in this **Buffer** instance where data is copied. The default value is **0**.| +| sourceEnd | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Total length of the data copied, in bytes.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +let buf2 = buffer.allocUninitializedFromPool(26).fill('!'); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} + +buf1.copy(buf2, 8, 16, 20); +console.log(buf2.toString('ascii', 0, 25)); +// Print: !!!!!!! qrst!!!!!!!!!!!!! +``` + +### entries + +entries(): IterableIterator<[number, number]> + +Creates and returns an iterator that contains key-value pairs of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (let pair of buf.entries()) { + console.log(pair); +} +``` + +### equals + +equals(otherBuffer: Buffer | Uint8Array): boolean + +Checks whether this **Buffer** instance is the same as another **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| otherBuffer | Buffer \| Uint8Array | Yes| **Buffer** instance to compare.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the two instances are the same; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('ABC'); +let buf2 = buffer.from('414243', 'hex'); +let buf3 = buffer.from('ABCD'); + +console.log (buf1.equals (buf2)); // Print: true +console.log (buf1.equals (buf3)); // Print: false + +``` + +### fill + +fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): Buffer + +Fills this **Buffer** instance at the specified position. By default, data is filled cyclically. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| Buffer \| Uint8Array \| number | Yes| Value to fill.| +| offset | number | No| Offset to the start position in this **Buffer** instance where data is filled. The default value is **0**.| +| end | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| +| encoding | BufferEncoding | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance filled with the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let b = buffer.allocUninitializedFromPool(50).fill('h'); +console.log(b.toString()); +``` + + +### includes + +includes(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): boolean + +Checks whether this **Buffer** instance contains the specified value. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the instance contains the specified value; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log (buf.includes ('this')); // Print: true +console.log (buf.includes ('be')); // Print: false +``` + +### indexOf + +indexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +Obtains the index of the first occurrence of the specified value in this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Index obtained.
If **-1** is returned, the **Buffer** instance does not contain the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log (buf.indexOf('this')); // Print: 0 +console.log(buf.indexOf('is')); // Print: 2 +``` + +### keys + +keys(): IterableIterator<number> + +Creates and returns an iterator that contains the keys of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| IterableIterator<number> | Iterator.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (const key of buf.keys()) { + console.log(key); +} +``` + +### lastIndexOf + +lastIndexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +Obtains the index of the last occurrence of the specified value in this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Index obtained.
If **-1** is returned, the **Buffer** instance does not contain the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this buffer is a buffer'); +console.log(buf.lastIndexOf('this')); // Print: 0 +console.log(buf.lastIndexOf('buffer')); // Print:17 +``` + + +### readBigInt64BE + +readBigInt64BE(offset: number): number + +Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, big-endian 64-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64BE(0)); +``` + +### readBigInt64LE + +readBigInt64LE(offset: number): number + +Reads a signed, little-endian 64-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, little-endian 64-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64LE(0)); +``` + +### readBigUInt64BE + +readBigUInt64BE(offset: number): number + +Reads an unsigned, big-endian 64-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, big-endian 64-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64BE(0)); +``` + +### readBigUInt64LE + +readBigUInt64LE(offset: number): number + +Reads an unsigned, little-endian 64-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, little-endian 64-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64LE(0)); +``` + +### readDoubleBE + +readDoubleBE(offset: number): number + +Reads a 64-bit, big-endian double-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A 64-bit, big-endian double-precision floating-point number.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleBE(0)); +``` + +### readDoubleLE + +readDoubleLE(offset: number): number + +Reads a 64-bit, little-endian double-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A 64-bit, little-endian double-precision floating-point number.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleLE(0)); +``` + +### readFloatBE + +readFloatBE(offset: number): number + +Reads a 32-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A 32-bit, big-endian floating-point number.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatBE(0)); +``` + +### readFloatLE + +readFloatLE(offset: number): number + +Reads a 32-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A 32-bit, little-endian floating-point number.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatLE(0)); +``` + +### readInt8 + +readInt8(offset: number): number + +Reads a signed 8-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed 8-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([-1, 5]); +console.log (buf.readInt8(0)); // Print: -1 +console.log (buf.readInt8(1); // Print: 5 +``` + +### readInt16BE + +readInt16BE(offset: number): number + +Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, big-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from([0, 5]); +console.log (buf.readInt16BE(0)); // Print: 5 +``` + +### readInt16LE + +readInt16LE(offset: number): number + +Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, little-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from([0, 5]); +console.log (buf.readInt16BE(0)); // Print: 1280 +``` + +### readInt32BE + +readInt32BE(offset: number): number + +Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, big-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log(buf.readInt32BE(0)); // Print: 5 +``` + +### readInt32LE + +readInt32LE(offset: number): number + +Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, little-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log (buf.readInt32LE(0)); // Print: 83886080 +``` + +### readIntBE + +readIntBE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as a big-endian, two's complement signed value that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| +| byteLength | number | No| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = Buffer.from("ab"); +let num = buf.readIntBE(0, 1); +console.log(num); // 97 +``` + + +### readIntLE + +readIntLE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset and interprets the result as a little-endian, two's complement signed value that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| +| byteLength | number | No| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readIntLE(0, 6).toString(16)); +``` + +### readUInt8 + +readUInt8(offset: number): number + +Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned 8-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, -2]); +console.log(buf.readUInt8(0)); +console.log(buf.readUInt8(1)); +``` + +### readUInt16BE + +readUInt16BE(offset: number): number + +Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, big-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16BE(0).toString(16)); +console.log(buf.readUInt16BE(1).toString(16)); +``` + +### readUInt16LE + +readUInt16LE(offset: number): number + +Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, little-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16LE(0).toString(16)); +console.log(buf.readUInt16LE(1).toString(16)); +``` + +### readUInt32BE + +readUInt32BE(offset: number): number + +Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, big-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32BE(0).toString(16)); +``` + +### readUInt32LE + +readUInt32LE(offset: number): number + +Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, little-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32LE(0).toString(16)); +``` + +### readUIntBE + +readUIntBE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as an unsigned, big-endian integer that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| +| byteLength | number | No| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntBE(0, 6).toString(16)); +``` + +### readUIntLE + +readUIntLE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as an unsigned, little-endian integer that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| +| byteLength | number | No| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntLE(0, 6).toString(16)); +``` + +### subarray + +subarray(start?: number, end?: number): Buffer + +Truncates this **Buffer** instance from the specified position to create a new **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | number | No| Offset to the start position in this **Buffer** instance where data is truncated. The default value is **0**.| +| end | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +const buf2 = buf1.subarray(0, 3); +console.log(buf2.toString('ascii', 0, buf2.length)); +// Print: abc +``` + +### swap16 + +swap16(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 16-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // Print: + +buf1.swap16(); +console.log(buf1); // Print: +``` + +### swap32 + +swap32(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 32-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // Print: + +buf1.swap32(); +console.log(buf1); // Print: +``` + +### swap64 + +swap64(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 64-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1); // Print: +buf1.swap64(); +console.log(buf1); // Print: +``` + +### toJSON + +toJSON(): Object + +Converts this **Buffer** instance into a JSON object. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Object | JSON object.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); +let buf2 = buffer.from(buf1.toJSON()) +let json = JSON.stringify(buf2); +console.log(json); +// Print: {"type":"Buffer","data":[1,2,3,4,5]} +``` + +### toString + +toString(encoding?: string, start?: number, end?: number): string + +Converts the data at the specified position in this **Buffer** instance into a string in the specified encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | No| Encoding format of the string. The default value is **utf-8**.| +| start | number | No| Offset to the start position of the data to convert. The default value is **0**.| +| end | number | No| Offset to the end position of the data to convert. The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | String obtained.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +console.log(buf1.toString('utf-8')); +// Print: abcdefghijklmnopqrstuvwxyz +``` + +### values + +values(): IterableIterator<number> + +Creates and returns an iterator that contains the values of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| IterableIterator<number> | Iterator created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +for (const value of buf.values()) { + console.log(value); +} +``` + +### write + +write(str: string, offset?: number, length?: number, encoding?: string): number + +Writes a string of the specified length to this **Buffer** instance at the specified position in the given encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| str | string | Yes| String to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| +| length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.| +| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(256); +let len = buf.write('\u00bd + \u00bc = \u00be', 0); +console.log(`${len} bytes: ${buf.toString('utf-8', 0, len)}`); +// Print: 12 bytes: ½ + ¼ = ¾ + +let buffer = Buffer.alloc(10); +let length = buffer.write('abcd', 8); +``` + +### writeBigInt64BE + +writeBigInt64BE(value: number, offset?: number): number + +Writes a signed, big-endian 64-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64BE(0x0102030405060708n, 0); +``` + +### writeBigInt64LE + +writeBigInt64LE(value : number, offset? : number): number + +Writes a signed, little-endian 64-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64LE(0x0102030405060708n, 0); +``` + +### writeBigUInt64BE + +writeBigUInt64BE(value : number, offset? : number): number + +Writes an unsigned, big-endian 64-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64BE(0xdecafafecacefaden, 0); +``` + +### writeBigUInt64LE + +writeBigUInt64LE(value : number, offset? : number): number + +Writes an unsigned, little-endian 64-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64LE(0xdecafafecacefaden, 0); +``` + +### writeDoubleBE + +writeDoubleBE(value : number, offset? : number): number + +Writes a 64-bit, big-endian double-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleBE(123.456, 0); +``` + +### writeDoubleLE + +writeDoubleLE(value : number, offset? : number): number + +Writes a 64-bit, little-endian double-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleLE(123.456, 0); +``` + +### writeFloatBE + +writeFloatBE(value : number, offset? : number): number + +Writes a 32-bit, big-endian floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatBE(0xcafebabe, 0); +``` + + +### writeFloatLE + +writeFloatLE(value : number, offset? : number): number + +Writes a 32-bit, little-endian floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatLE(0xcafebabe, 0); +``` + +### writeInt8 + +writeInt8(value : number, offset? : number): number + +Writes a signed 8-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt8(2, 0); +buf.writeInt8(-2, 1); +``` + + +### writeInt16BE + +writeInt16BE(value : number, offset? : number): number + +Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16BE(0x0102, 0); +``` + + +### writeInt16LE + +writeInt16LE(value : number, offset : number): number + +Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16LE(0x0304, 0); +``` + +### writeInt32BE + +writeInt32BE(value : number, offset : number): number + +Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32BE(0x01020304, 0); +``` + + +### writeInt32LE + +writeInt32LE(value : number, offset : number): number + +Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32LE(0x05060708, 0); +``` + +### writeIntBE + +writeIntBE(value : number, offset : number, byteLength : number): number + +Writes a big-endian signed value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| +| byteLength | number | No| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntBE(0x1234567890ab, 0, 6); +``` + + +### writeIntLE + +writeIntLE(value : number, offset : number, byteLength : number): number + +Writes a little-endian signed value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| +| byteLength | number | No| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntLE(0x1234567890ab, 0, 6); +``` + +### writeUInt8 + +writeUInt8(value : number, offset : number): number + +Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt8(0x3, 0); +buf.writeUInt8(0x4, 1); +buf.writeUInt8(0x23, 2); +buf.writeUInt8(0x42, 3); +``` + +### writeUInt16BE + +writeUInt16BE(value : number, offset : number): number + +Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16BE(0xdead, 0); +buf.writeUInt16BE(0xbeef, 2); +``` + +### writeUInt16LE + +writeUInt16LE(value : number, offset : number): number + +Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16LE(0xdead, 0); +buf.writeUInt16LE(0xbeef, 2); +``` + +### writeUInt32BE + +writeUInt32BE(value : number, offset : number): number + +Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32BE(0xfeedface, 0); +``` + +### writeUInt32LE + +writeUInt32LE(value : number, offset : number): number + +Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Number to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32LE(0xfeedface, 0); +``` + +### writeUIntBE + +writeUIntBE(value : number, offset : number, byteLength : number): number + +Writes a big-endian unsigned value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| +| byteLength | number | No| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntBE(0x1234567890ab, 0, 6); +``` + +### writeUIntLE + +writeUIntLE(value : number, offset : number, byteLength : number): number + +Writes a little-endian unsigned value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| +| byteLength | number | No| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntLE(0x1234567890ab, 0, 6); +``` + +### transcode + +transcode(source : Buffer | Uint8Array, fromEnc : string, toEnc : string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to encode.| +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buf.transcode(buffer.from('€'), 'utf8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Blob + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| size | number | Yes| No| Total size of the **Blob** instance, in bytes.| +| type | string | Yes| No| Type of the data in the **Blob** instance.| + +### constructor + +constructor(sources: string[] | ArrayBuffer[] | TypedArray[] | DataView[] | Blob[] , options: Object) + +A constructor used to create a **Blob** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sources | string[] \| ArrayBuffer[] \| TypedArray[] \| DataView[] \| Blob[] | Yes| Data sources of the **Blob** instance.| +| options | Object | No| options:
- **endings**: 'transparent' or 'native'.
- **type**: type of the data in **Blob**.| + + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let blob1 = new buffer.Blob(['a', 'b', 'c']); +let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); +``` + +### encode + +arrayBuffer(): Promise<ArrayBuffer> + +Puts the **Blob** data into an **ArrayBuffer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<ArrayBuffer> | Promise used to return the **ArrayBuffer** containing the **Blob** data.| + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.arrayBuffer(); + pro.then(val => { + console.log(val) + }); + ``` +### slice + +slice(start?: number, end?: number, type?: string): Blob + +Creates a **Blob** instance by copying specified data from this **Blob** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | number | No| Offset to the start position of the data to copy.| +| end | number | No| Offset to the end position of the data to copy.| +| type | string | No| Type of the data in the new **Blob** instance.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Blob | New **Blob** instance created.| + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let blob2 = blob.slice(0, 2); + let blob3 = blob.slice(0, 2, "MIME"); + ``` + + ### text + +text(): Promise<string> + +Returns text in UTF-8 format. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the text encoded in UTF-8.| + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.text(); + pro.then(val => { + console.log(val) + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 79ad744268f719cf6c9c24310e27e91c00ae9630..1631e3318f49bd07012e836449dfa4431a67db65 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -2746,7 +2746,7 @@ Defines the dialup options. | Name | Type | Mandatory| Description | | ------------------------ | ---------------------------------- | ---- | ------------------------------------------------------------ | | extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| -| accountId 8+ | number | No | Account ID. This is a system API. | +| accountId 8+ | number | No | Account ID.
- **0**: card slot 1
- **1**: card slot 2
This is a system API. | | videoState 8+ | [VideoStateType](#videostatetype7) | No | Video state type. This is a system API. | | dialScene 8+ | [DialScene](#dialscene8) | No | Dialup scenario. This is a system API. | | dialType 8+ | [DialType](#dialtype8) | No | Dialup type. This is a system API. | diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 410bfd51d89defc480e3d4dde2da2a351b1fbd24..f9c55898029eee1a6782df976cfd40ec43574735 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -20,9 +20,9 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ---------------------------------- | -| context | Context | Yes | Application context. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ---------------------------- | +| context | Context | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -53,8 +53,8 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------------- | +| Type | Description | +| ----------------------------------------- | ----------------------------------- | | Promise<[CameraManager](#cameramanager)\> | Promise used to return the **CameraManager** instance.| **Example** @@ -71,23 +71,23 @@ Enumerates the camera statuses. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | -------------- | -| CAMERA_STATUS_APPEAR | 0 | A camera appears.| -| CAMERA_STATUS_DISAPPEAR | 1 | The camera disappears. | -| CAMERA_STATUS_AVAILABLE | 2 | The camera is available. | -| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable. | +| Name | Value | Description | +| ------------------------- | ---- | ------------ | +| CAMERA_STATUS_APPEAR | 0 | A camera appears. | +| CAMERA_STATUS_DISAPPEAR | 1 | The camera disappears.| +| CAMERA_STATUS_AVAILABLE | 2 | The camera is available. | +| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable.| ## Profile -Defines the camera configuration. +Defines the camera profile. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| ------ | ----------------------------- | ---- | ---------- | -| format | [CameraFormat](#cameraformat) | Yes | Output format.| -| size | [Size](#size) | Yes | Resolution. | +| Name | Type | Read only| Description | +| -------- | ----------------------------- |---- | ------------- | +| format | [CameraFormat](#cameraformat) | Yes | Output format. | +| size | [Size](#size) | Yes | Resolution. | ## FrameRateRange @@ -95,20 +95,20 @@ Defines the camera configuration. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Read only| Description | -| ---- | ------ | ---- | ----------------- | -| min | number | Yes | Minimum rate, in fps.| -| max | number | Yes | Maximum rate, in fps.| +| Name | Type | Read only| Description | +| ------------------------- | ------ | ---- | ------------------- | +| min | number | Yes | Minimum rate, in fps. | +| max | number | Yes | Maximum rate, in fps. | ## VideoProfile -Defines the video configuration. +Defines the video profile. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| --------------- | --------------------------------- | ---- | ------ | -| frameRateRanges | [FrameRateRange](#frameraterange) | Yes | Frame rate range.| +| Name | Type | Read only| Description | +| ------------------------- | ----------------------------------------- | --- |------------ | +| frameRateRanges | [FrameRateRange](#frameraterange) | Yes | Frame rate range. | ## CameraOutputCapability @@ -116,12 +116,12 @@ Defines the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| ---------------------------- | ------------------------------------------------- | ---- | -------------------------- | -| previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview configurations. | -| photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting configurations. | -| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording configurations. | -| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| +| Name | Type | Read only| Description | +| ----------------------------- | -------------------------------------------------- | --- |------------------- | +| previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview profiles. | +| photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting profiles. | +| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording profiles. | +| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| ## CameraManager @@ -137,8 +137,8 @@ Obtains supported cameras. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------- | | callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| **Example** @@ -163,8 +163,8 @@ Obtains supported cameras. This API uses a promise to return the result. **Return value** -| Type | Description | -| ----------------------------------------------- | ----------------------------- | +| Type | Description | +| ----------------------------------------------- | ------------------------- | | Promise\> | Promise used to return the array of supported cameras.| @@ -186,10 +186,10 @@ Obtains the output capability supported by a camera. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ---------------------------------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | -| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes | Callback used to return the output capability.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------------- | -- | -------------------------- | +| camera | [CameraDevice](#cameradevice) | Yes| **CameraDevice** object. | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes| Callback used to return the output capability.| **Example** @@ -213,15 +213,15 @@ Obtains the output capability supported by a camera. This API uses a promise to **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------ | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| **Return value** -| Type | Description | -| ----------------------------------------------------------- | --------------------------------------------- | -| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.| +| Type | Description | +| -------------------------------------------------------------- | ----------------------------- | +| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.| **Example** @@ -236,15 +236,15 @@ cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapab getSupportedMetadataObjectType(callback: AsyncCallback\>): void -Obtains the metadata information supported by this camera. This API uses an asynchronous callback to return the result. +Obtains the metadata object types supported by this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the metadata information.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------------- | -- | -------------------------- | +| callback | AsyncCallback\> | Yes| Callback used to return the metadata object types.| **Example** @@ -262,15 +262,15 @@ cameraManager.getSupportedMetadataObjectType((err, metadataobject) => { getSupportedMetadataObjectType(camera:CameraDevice): Promise -Obtains the metadata information supported by this camera. This API uses a promise to return the result. +Obtains the metadata object types supported by this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ------------------------------------------------------- | ----------------------------------------------------- | -| Promise\> | Promise used to return the metadata information.| +| Type | Description | +| -------------------------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the metadata object types.| **Example** @@ -291,9 +291,9 @@ Checks whether this camera is muted. This API uses an asynchronous callback to r **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| **Example** @@ -317,9 +317,9 @@ Checks whether this camera is muted. This API uses a promise to return the resul **Return value** -| Type | Description | -| ----------------- | --------------------------------------------------- | -| Promise | Promise used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| +| Type | Description | +| ------------------------------------ | --------------------------------------------- | +| Promise | Promise used to return the result. The value **true** means that the camera is muted, and **false** means the opposite. | **Example** @@ -344,9 +344,9 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite. | **Example** @@ -374,9 +374,9 @@ This is a system API. **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------- | -| Promise | Promise used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| +| Type | Description | +| --------------------- | ----------------------------- | +| Promise | Promise used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| **Example** @@ -401,10 +401,10 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------ | -| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------ | +| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -432,15 +432,15 @@ This is a system API. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | ------- | ---- | -------------- | -| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------ | +| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | **Return value** -| Type | Description | -| -------------- | --------------------------------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -465,10 +465,10 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | **Example** @@ -496,14 +496,14 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------ | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | +| Type | Description | +| ------------------------------------- | ------------------------------------ | | Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** @@ -529,10 +529,10 @@ This is a system API. **Parameters** | Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| -------- | ------------------------------------------- | ---- | --------------------------------- | | position | [CameraPosition](#cameraposition) | Yes | Camera position. | | type | [CameraType](#cameratype) | Yes | Camera type. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | **Example** @@ -560,15 +560,15 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ---------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position.| -| type | [CameraType](#cameratype) | Yes | Camera type.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| position | [CameraPosition](#cameraposition) | Yes | Camera position. | +| type | [CameraType](#cameratype) | Yes | Camera type. | **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | +| Type | Description | +| ------------------------------------- | ------------------------------------ | | Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** @@ -589,11 +589,11 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| profile | [Profile](#profile) | Yes | Supported preview configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------- | +| profile | [Profile](#profile) | Yes | Supported preview profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| **Example** @@ -617,16 +617,16 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------- | ---- | ------------------------------------------------------------ | -| profile | [Profile](#profile) | Yes | Supported preview configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------| ---- | ----------------- | +| profile | [Profile](#profile) | Yes | Supported preview profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| **Return value** -| Type | Description | -| ----------------------------------------- | ------------------------------------------ | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance. | **Example** @@ -646,10 +646,10 @@ Creates a **PreviewOutput** instance without a surface ID. This API uses an asyn **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------------- | -| profile | [Profile](#profile) | Yes | Supported preview configurations. | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | --------------------------------- | +| profile | [Profile](#profile) | Yes | Supported preview profile. | +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance. | **Example** @@ -673,15 +673,15 @@ Creates a **PreviewOutput** instance without a surface ID. This API uses a promi **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------- | ---- | -------------------- | -| profile | [Profile](#profile) | Yes | Supported preview configurations.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------| ---- | ---------- | +| profile | [Profile](#profile) | Yes | Supported preview profile. | **Return value** -| Type | Description | -| ----------------------------------------- | ------------------------------------------ | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| +| Type | Description | +| ----------------------------------------- | --------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| **Example** @@ -701,11 +701,11 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| profile | [Profile](#profile) | Yes | Supported shooting configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| profile | [Profile](#profile) | Yes | Supported shooting profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. | **Example** @@ -729,16 +729,16 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the result **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------- | ---- | ------------------------------------------------------------ | -| profile | [Profile](#profile) | Yes | Supported shooting configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------| ---- | ----------- | +| profile | [Profile](#profile) | Yes | Supported shooting profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| **Return value** | Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance.| +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance. | **Example** @@ -758,11 +758,11 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------ | +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| **Example** @@ -786,16 +786,16 @@ Creates a **VideoOutput** instance. This API uses a promise to return the result **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------- | ---- | ------------------------------------------------------------ | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording configurations. | -| surfaceId | string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------| ---- | ---------- | +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | +| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| **Return value** | Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance.| +| ------------------------------------- | -------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance. | **Example** @@ -815,10 +815,10 @@ Creates a **MetadataOutput** instance. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| ------------------- | ------------------------------------------------- | ---- | -------------------------------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types. | -| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance.| +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | --- | ---------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types. | +| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance. | **Example** @@ -842,15 +842,15 @@ Creates a **MetadataOutput** instance. This API uses a promise to return the res **Parameters** -| Name | Type | Mandatory| Description | -| ------------------- | ------------------------------------------------- | ---- | ---------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | --- | -------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| **Return value** -| Type | Description | -| ------------------------------------------- | ------------------------------------------- | -| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.| +| Type | Description | +| ------------------------------------------ | ----------------------------------------- | +| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.| **Example** @@ -870,9 +870,9 @@ Creates a **CaptureSession** instance. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| +| Name | Type | Mandatory | Description | +| -------------------- | ----------------------------------------- | ----------- | ---------------------------- | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| **Example** @@ -896,9 +896,9 @@ Creates a **CaptureSession** instance. This API uses a promise to return the res **Return value** -| Type | Description | -| ------------------------------------------- | ------------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| +| Type | Description | +| ------------------------------------------- | ---------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| **Example** @@ -918,9 +918,9 @@ Listens for camera status changes. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **cameraStatus**, indicating the camera status change event.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | --------- | +| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**, indicating the camera status change event.| | callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | **Example** @@ -950,10 +950,10 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **cameraMute**, indicating the camera mute status change event.| -| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| +| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | **Example** @@ -973,7 +973,7 @@ Describes the camera status information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Description | +| Name | Type | Description | | ------ | ----------------------------- | ---------- | | camera | [CameraDevice](#cameradevice) | Camera object.| | status | [CameraStatus](#camerastatus) | Camera status.| @@ -984,9 +984,9 @@ Enumerates the camera positions. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------------- | ---- | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| +| Name | Value | Description | +| --------------------------- | ---- | -------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position. | | CAMERA_POSITION_BACK | 1 | Rear camera. | | CAMERA_POSITION_FRONT | 2 | Front camera. | @@ -996,12 +996,12 @@ Enumerates the camera types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ----------------------- | ---- | ------------------ | -| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type. | -| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | -| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | -| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | +| Name | Value | Description | +| ----------------------- | ---- | -------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type. | +| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | +| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | +| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | | CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information.| ## ConnectionType @@ -1010,10 +1010,10 @@ Enumerates the camera connection types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------------- | ---- | ---------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB. | +| Name | Value | Description | +| ---------------------------- | ---- | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| | CAMERA_CONNECTION_REMOTE | 2 | Remote camera.| ## CameraDevice @@ -1022,12 +1022,12 @@ Defines the camera device information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| -------------- | --------------------------------- | ---- | ---------------- | +| Name | Type | Read only| Description | +| -------------- | --------------------------------- | ---- | ---------- | | cameraId | string | Yes | **CameraDevice** object.| -| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | -| cameraType | [CameraType](#cameratype) | Yes | Camera type. | -| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type. | +| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | +| cameraType | [CameraType](#cameratype) | Yes | Camera type. | +| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| **Example** @@ -1049,10 +1049,10 @@ Enumerates the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | ------------------ | +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------ | | height | number | Yes | Yes | Image height, in pixels.| -| width | number | Yes | Yes | Image width, in pixel.| +| width | number | Yes | Yes | Image width, in pixels.| ## Point @@ -1060,21 +1060,21 @@ Enumerates the point coordinates, which are used for focus and exposure configur **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | ----------- | -| x | number | Yes | X coordinate of a point.| -| y | number | Yes | Y coordinate of a point.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------ | +| x | number | Yes | X coordinate of a point. | +| y | number | Yes | Y coordinate of a point. | ## CameraFormat -Enumerates the camera output format. +Enumerates the camera output formats. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value| Description | -| ------------------------ | ------ | ---------------------- | -| CAMERA_FORMAT_YUV_420_SP | 1003 | YUV 420 SP image.| -| CAMERA_FORMAT_JPEG | 2000 | JPEG image. | +| Name | Default Value | Description | +| ----------------------- | --------- | ------------ | +| CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP image. | +| CAMERA_FORMAT_JPEG | 2000 | JPEG image. | ## CameraInput @@ -1090,8 +1090,8 @@ Opens this camera. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1116,8 +1116,8 @@ Opens this camera. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -1138,8 +1138,8 @@ Closes this camera. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1164,8 +1164,8 @@ Closes this camera. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -1186,8 +1186,8 @@ Releases this camera. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1212,8 +1212,8 @@ Releases this camera. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -1234,10 +1234,10 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **error**, indicating the camera input error event.| -| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the camera input error event.| +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | **Example** @@ -1253,14 +1253,14 @@ Enumerates the error codes used for camera input. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | -------------- | -| ERROR_UNKNOWN | -1 | Unknown error. | -| ERROR_NO_PERMISSION | 0 | You do not have the required permission. | -| ERROR_DEVICE_PREEMPTED | 1 | The camera is preempted. | +| Name | Value | Description | +| ------------------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_NO_PERMISSION | 0 | You do not have the required permission.| +| ERROR_DEVICE_PREEMPTED | 1 | The camera is preempted.| | ERROR_DEVICE_DISCONNECTED | 2 | The camera is disconnected.| | ERROR_DEVICE_IN_USE | 3 | The camera is in use.| -| ERROR_DRIVER_ERROR | 4 | Driver error. | +| ERROR_DRIVER_ERROR | 4 | Driver error. | ## CameraInputError @@ -1268,8 +1268,8 @@ Defines an error object used for **[CameraInput](#camerainput)**. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | --------------------------------------------- | ----------------------- | +| Name| Type | Description | +| ---- | --------------------------------------------- | --------------------- | | code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| @@ -1279,8 +1279,8 @@ Enumerates the flash modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------- | ---- | ------------ | +| Name | Value | Description | +| ---------------------- | ---- | ---------- | | FLASH_MODE_CLOSE | 0 | The flash is off.| | FLASH_MODE_OPEN | 1 | The flash is on.| | FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| @@ -1292,8 +1292,8 @@ Enumerates the exposure modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ----------------------------- | ---- | -------------- | +| Name | Value | Description | +| ----------------------------- | ---- | ----------- | | EXPOSURE_MODE_LOCKED | 0 | Exposure locked.| | EXPOSURE_MODE_AUTO | 1 | Auto exposure.| | EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.| @@ -1304,8 +1304,8 @@ Enumerates the focus modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------------- | ---- | -------------- | +| Name | Value | Description | +| -------------------------- | ---- | ------------ | | FOCUS_MODE_MANUAL | 0 | Manual focus. | | FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| | FOCUS_MODE_AUTO | 2 | Auto focus. | @@ -1317,10 +1317,10 @@ Enumerates the focus states. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------- | ---- | ------------ | -| FOCUS_STATE_SCAN | 0 | Focusing. | -| FOCUS_STATE_FOCUSED | 1 | Focused. | +| Name | Value | Description | +| --------------------- | ---- | --------- | +| FOCUS_STATE_SCAN | 0 | Focusing. | +| FOCUS_STATE_FOCUSED | 1 | Focused. | | FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| ## ExposureState @@ -1329,10 +1329,10 @@ Enumerates the exposure states. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------ | ---- | ---------- | -| EXPOSURE_STATE_SCAN | 0 | Exposing. | -| EXPOSURE_STATE_CONVERGED | 1 | Exposure converged.| +| Name | Value | Description | +| ------------------------- | ---- | -------- | +| EXPOSURE_STATE_SCAN | 0 | Exposing. | +| EXPOSURE_STATE_CONVERGED | 1 | Exposure converged.| ## VideoStabilizationMode @@ -1340,13 +1340,13 @@ Enumerates the video stabilization modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------ | ---- | ---------------------------------------------------- | -| OFF | 0 | Video stabilization is disabled. | -| LOW | 1 | The basic video stabilization algorithm is used. | -| MIDDLE | 2 | A video stabilization algorithm with a stabilization effect better than that of the **LOW** type is used. | -| HIGH | 3 | A video stabilization algorithm with a stabilization effect better than that of the **MIDDLE** type is used.| -| AUTO | 4 | Automatic video stabilization is used. | +| Name | Value | Description | +| --------- | ---- | ------------ | +| OFF | 0 | Video stabilization is disabled. | +| LOW | 1 | The basic video stabilization algorithm is used. | +| MIDDLE | 2 | A video stabilization algorithm with a stabilization effect better than that of the **LOW** type is used. | +| HIGH | 3 | A video stabilization algorithm with a stabilization effect better than that of the **MIDDLE** type is used. | +| AUTO | 4 | Automatic video stabilization is used. | ## CaptureSession @@ -1362,8 +1362,8 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1388,8 +1388,8 @@ Starts configuration for this **CaptureSession** instance. This API uses a promi **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| @@ -1411,8 +1411,8 @@ Commits the configuration for this **CaptureSession** instance. This API uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1437,8 +1437,8 @@ Commits the configuration for this **CaptureSession** instance. This API uses a **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -1459,8 +1459,8 @@ Checks whether a **[CameraInput](#camerainput)** instance can be added to this * **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -1486,14 +1486,14 @@ Checks whether a **[CameraInput](#camerainput)** instance can be added to this * **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| **Return value** -| Type | Description | -| ----------------- | --------------------------- | +| Type | Description | +| -------------- | -------------------------- | | Promise | Promise used to return the result.| **Example** @@ -1514,8 +1514,8 @@ Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -1541,14 +1541,14 @@ Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -1569,8 +1569,8 @@ Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -1596,14 +1596,14 @@ Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| **Return value** -| Type | Description | -| --------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -1624,10 +1624,10 @@ Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -1651,15 +1651,15 @@ Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| **Return value** -| Type | Description | -| ----------------- | --------------------------- | +| Type | Description | +| -------------- | --------------------------- | | Promise | Promise used to return the result.| @@ -1681,10 +1681,10 @@ Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. Th **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -1708,14 +1708,14 @@ Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. Th **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -1736,10 +1736,10 @@ Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession* **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------ | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -1763,15 +1763,15 @@ Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession* **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ----------------------------- | ---- | ---------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| @@ -1793,8 +1793,8 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1819,8 +1819,8 @@ Starts this **CaptureSession**. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -1841,8 +1841,8 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1867,8 +1867,8 @@ Stops this **CaptureSession**. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -1883,14 +1883,14 @@ captureSession.stop().then(() => { lockForControl(callback: AsyncCallback): void -Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses an asynchronous callback to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the lock. +Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses an asynchronous callback to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the exclusive control. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1909,14 +1909,14 @@ captureSession.lockForControl((err) => { lockForControl(): Promise -Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses a promise to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the lock. +Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses a promise to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the exclusive control. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -1937,8 +1937,8 @@ Releases the exclusive control on the device configuration. This API uses an asy **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1963,8 +1963,8 @@ Releases the exclusive control on the device configuration. This API uses a prom **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -1985,8 +1985,8 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2011,8 +2011,8 @@ Releases this **CaptureSession**. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -2027,15 +2027,15 @@ captureSession.release().then(() => { hasFlash(callback: AsyncCallback): void -Checks whether the device has flash light. This API uses an asynchronous callback to return the result. +Checks whether the device has flash. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the flash light support status. The value **true** means that the device has flash light.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the flash support status. The value **true** means that the device has flash.| **Example** @@ -2053,15 +2053,15 @@ cameraInput.hasFlash((err, status) => { hasFlash(): Promise -Checks whether the device has flash light. This API uses a promise to return the result. +Checks whether the device has flash. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------- | -| Promise | Promise used to return the flash light support status. The value **true** means that the device has flash light.| +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.| **Example** @@ -2081,9 +2081,9 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------------------------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | --------------------------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | | callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| **Example** @@ -2108,14 +2108,14 @@ Checks whether a specified flash mode is supported. This API uses a promise to r **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------- | | flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------------ | +| Type | Description | +| ----------------- | ---------------------------------------------------- | | Promise | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| **Example** @@ -2134,15 +2134,15 @@ Sets the flash mode. This API uses an asynchronous callback to return the result Before the setting, do the following checks: -1. Use **[hasFlash](#hasflash)** to check whether the device has flash light. +1. Use **[hasFlash](#hasflash)** to check whether the device has flash. 2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | --------------------- | | flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | | callback | AsyncCallback | Yes | Callback used to return the result.| @@ -2166,21 +2166,21 @@ Sets a flash mode. This API uses a promise to return the result. Before the setting, do the following checks: -1. Use **[hasFlash](#hasflash)** to check whether the device has flash light. +1. Use **[hasFlash](#hasflash)** to check whether the device has flash. 2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------- | | flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -2201,8 +2201,8 @@ Obtains the flash mode in use. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ---------------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | --------------------------------- | | callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| **Example** @@ -2227,8 +2227,8 @@ Obtains the flash mode in use. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------------------------- | --------------------------------------- | +| Type | Description | +| --------------------------------- | --------------------------------- | | Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| **Example** @@ -2249,10 +2249,10 @@ Checks whether a specified exposure mode is supported. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ------------------------------------ | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | -| callback | AsyncCallback | Yes | Callback used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| callback | AsyncCallback | Yes | Callback used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| **Example** @@ -2276,14 +2276,14 @@ Checks whether a specified exposure mode is supported. This API uses a promise t **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | **Return value** -| Name | Description | -| ----------------- | ------------------------------------- | +| Name | Description | +| ----------------- |--------------------------------- | | Promise | Promise used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| **Example** @@ -2304,9 +2304,9 @@ Obtains the exposure mode in use. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ---------------------------------------- | +| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.| **Example** @@ -2330,8 +2330,8 @@ Obtains the exposure mode in use. This API uses a promise to return the result. **Return value** -| Name | Description | -| --------------------------------------- | ----------------------------------- | +| Name | Description | +| --------------------------------------- |------------------------------- | | Promise<[ExposureMode](#exposuremode)\> | Promise used to return the exposure mode.| **Example** @@ -2352,10 +2352,10 @@ Sets an exposure mode. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ---------------------------- | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ----------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2379,9 +2379,9 @@ Sets an exposure mode. This API uses a promise to return the result. **Return value** -| Name | Description | -| -------------- | ------------------------------- | -| Promise| Promise used to return the result.| +| Name | Description | +| ----------------- |---------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -2401,9 +2401,9 @@ Obtains the center of the metering area. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the center of the metering area.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ------------------------ | +| callback | AsyncCallback<[Point](#point)\>| Yes | Callback used to return the center of the metering area.| **Example** @@ -2427,8 +2427,8 @@ Obtains the center of the metering area. This API uses a promise to return the r **Return value** -| Name | Description | -| ------------------------- | --------------------------------- | +| Name | Description | +| ------------------------- |----------------------------- | | Promise<[Point](#point)\> | Promise used to return the center of the metering area.| **Example** @@ -2449,10 +2449,10 @@ Sets the center of the metering area. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | -------------------- | ---- | ------------------------ | -| exposurePoint | [Point](#point) | Yes | Exposure point. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | Yes | Exposure point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2478,15 +2478,15 @@ Sets the center of the metering area. This API uses a promise to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | --------------- | ---- | -------- | -| exposurePoint | [Point](#point) | Yes | Exposure point.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | Yes | Exposure point. | **Return value** -| Name | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the center of the metering area.| +| Name | Description | +| ----------------- |------------------------ | +| Promise | Promise used to return the center of the metering area.| **Example** @@ -2508,9 +2508,9 @@ Obtains the exposure compensation values. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ---------------------------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the array of compensation values.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ----------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the array of compensation values.| **Example** @@ -2534,8 +2534,8 @@ Obtains the exposure compensation values. This API uses a promise to return the **Return value** -| Name | Description | -| ------------------------ | ----------------------------------- | +| Name | Description | +| ----------------- |-------------------------------------- | | Promise\> | Promise used to return the array of compensation values.| **Example** @@ -2558,10 +2558,10 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | -------------------- | ---- | ------------------------ | -| exposureBias | number | Yes | Compensation value. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ------------------- | +| exposureBias | number | Yes | Compensation value. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2587,15 +2587,15 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------ | ---- | ---------- | -| exposureBias | number | Yes | Compensation value.| +| Name | Type | Mandatory| Description | +| -------------- | --------- | ---- | --------- | +| exposureBias | number | Yes | Compensation value. | **Return value** -| Name | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the result.| +| Name | Description | +| ----------------- |------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -2615,9 +2615,9 @@ Obtains the exposure value in use. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback | Yes | Callback used to the exposure value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------| ---- | --------------------- | +| callback | AsyncCallback | Yes | Callback used to the exposure value.| **Example** @@ -2641,9 +2641,9 @@ Obtains the exposure value in use. This API uses a promise to return the result. **Return value** -| Name | Description | -| ---------------- | ----------------------------- | -| Promise | Promise used to the exposure value.| +| Name | Description | +| ----------------- |-------------------------- | +| Promise | Promise used to the exposure value.| **Example** @@ -2663,9 +2663,9 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | | callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| **Example** @@ -2690,14 +2690,14 @@ Checks whether a specified focus mode is supported. This API uses a promise to r **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------- | | afMode | [FocusMode](#focusmode) | Yes | Focus mode.| **Return value** -| Type | Description | -| ----------------- | ----------------------------------------------------------- | +| Type | Description | +| ----------------- | --------------------------------------------------- | | Promise | Promise used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| **Example** @@ -2720,9 +2720,9 @@ Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to che **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------ | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2749,14 +2749,14 @@ Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to che **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------- | | afMode | [FocusMode](#focusmode) | Yes | Focus mode.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -2777,8 +2777,8 @@ Obtains the focus mode in use. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | -------------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------- | | callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| **Example** @@ -2803,8 +2803,8 @@ Obtains the focus mode in use. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ------------------------------------- | +| Type | Description | +| ------------------- | -------------------------------- | | Promise | Promise used to return the focus mode.| **Example** @@ -2825,10 +2825,10 @@ Sets a focus point. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| point | [Point](#point) | Yes | Focus point. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#point) | Yes | Focus point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -2848,20 +2848,20 @@ cameraInput.setFocusPoint(Point1, (err) => { setFocusPoint(point: Point): Promise -Sets a focus point. This API uses a promise to return the result. +Sets a focal point. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----- | --------------- | ---- | ------ | -| point | [Point](#point) | Yes | Focus point.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#point) | Yes | Focal point. | **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -2878,15 +2878,15 @@ cameraInput.setFocusPoint(Point2).then(() => { getFocusPoint(callback: AsyncCallback): void -Obtains the focus point. This API uses an asynchronous callback to return the result. +Obtains the focal point. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the focus point.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ----------------------- | +| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the focal point.| **Example** @@ -2904,15 +2904,15 @@ cameraInput.getFocusPoint((err, point) => { getFocusPoint(): Promise -Obtains the focus point. This API uses a promise to return the result. +Obtains the focal point. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| --------------- | ------------------------------- | -| Promise | Promise used to return the focus point.| +| Type | Description | +| --------------- | --------------------------- | +| Promise | Promise used to return the focal point.| **Example** @@ -2932,9 +2932,9 @@ Obtains the focal length. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the focal length.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------- | +| callback | AsyncCallback | Yes | Callback used to return the focal length.| **Example** @@ -2958,8 +2958,8 @@ Obtains the focal length. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------- | --------------------------- | +| Type | Description | +| ---------------- | ----------------------- | | Promise | Promise used to return the focal length.| **Example** @@ -2974,15 +2974,15 @@ cameraInput.getFocalLength().then((focalLength) => { getZoomRatioRange\(callback: AsyncCallback\>\): void -Obtains the zoom range. This API uses an asynchronous callback to return the result. +Obtains the zoom ratio range. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return the zoom range.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Example** @@ -3000,15 +3000,15 @@ cameraInput.getZoomRatioRange((err, zoomRatioRange) => { getZoomRatioRange\(\): Promise\> -Obtains the zoom range. This API uses a promise to return the result. +Obtains the zoom ratio range. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ------------------------ | ------------------------------- | -| Promise\> | Promise used to return the zoom range.| +| Type | Description | +| ------------------------ | --------------------------- | +| Promise\> | Promise used to return the zoom ratio range.| **Example** @@ -3028,9 +3028,9 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------ | -| zoomRatio | number | Yes | Zoom ratio. | +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------- | +| zoomRatio | number | Yes | Zoom ratio. | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3055,14 +3055,14 @@ Sets a zoom ratio. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------ | +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------- | | zoomRatio | number | Yes | Zoom ratio.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -3083,8 +3083,8 @@ Obtains the zoom ratio in use. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3109,8 +3109,8 @@ Obtains the zoom ratio in use. This API uses a promise to return the result. **Return value** -| Type | Description | -| ---------------- | --------------------------- | +| Type | Description | +| ---------------- | ----------------------- | | Promise | Promise used to return the zoom ratio.| **Example** @@ -3125,16 +3125,16 @@ cameraInput.getZoomRatio().then((zoomRatio) => { isVideoStablizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void -Checks whether a specified video stabilization mode is supported. This API uses an asynchronous callback to return the result. +Checks whether the specified video stabilization mode is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------ | -| vsMode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | -| callback | AsyncCallback | Yes | Callback used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------ | +| vsMode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | +| callback | AsyncCallback | Yes | Callback used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite. | **Example** @@ -3152,14 +3152,14 @@ captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OF isVideoStablizationModeSupported(vsMode: VideoStabilizationMode): Promise -Checks whether a specified video stabilization mode is supported. This API uses a promise to return the result. +Checks whether the specified video stabilization mode is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ----------------- | ----------------------------------------------------- | +| Type | Description | +| ----------------- | --------------------------------------------- | | Promise | Promise used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.| **Example** @@ -3180,9 +3180,9 @@ Obtains the video stabilization mode in use. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the video stabilization mode.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the video stabilization mode. | **Example** @@ -3206,9 +3206,9 @@ Obtains the video stabilization mode in use. This API uses a promise to return t **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------------------------- | -| Promise | Promise used to return the video stabilization mode.| +| Type | Description | +| -------------------------------- | ------------------------------------------------- | +| Promise | Promise used to return the video stabilization mode. | **Example** @@ -3228,10 +3228,10 @@ Sets a video stabilization mode. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------ | -| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -3255,15 +3255,15 @@ Sets a video stabilization mode. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | ------------------------------------------------- | ---- | ------------------------ | -| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | **Return value** -| Type | Description | -| -------------- | --------------------------------------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------------------------------- | +| Promise| Promise used to return the result. | **Example** @@ -3283,10 +3283,10 @@ Listens for focus state changes. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **focusStateChange**, indicating the focus state change event.| -| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------ | +| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**, indicating the focus state change event.| +| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | **Example** @@ -3306,10 +3306,10 @@ Listens for exposure state changes. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'exposureStateChange'**, indicating the exposure state change event.| -| callback | AsyncCallback<[ExposureState](#exposurestate)\> | Yes | Callback used to return the exposure state change. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ---------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'exposureStateChange'**, indicating the exposure state change event.| +| callback | AsyncCallback<[ExposureState](#exposurestate)\> | Yes | Callback used to return the exposure state change. | **Example** @@ -3329,10 +3329,10 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | --------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **error**, indicating the capture session error event.| -| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the capture session error event.| +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | **Example** @@ -3348,15 +3348,15 @@ Enumerates the error codes used in a **CaptureSession**. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| -| ERROR_TIMEOUT | 1 | Timeout. | +| Name | Value | Description | +| ----------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| +| ERROR_TIMEOUT | 1 | Timeout.| ## CaptureSessionError -Defines a capture session error. +Defines a **CaptureSession** error. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -3378,8 +3378,8 @@ Releases output resources. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3404,8 +3404,8 @@ Releases output resources. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -3430,10 +3430,10 @@ Adds a surface after a **PreviewOutput** instance is created. This API uses an a **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------------------------------------------ | -| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------------------------------------------- | +| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -3457,14 +3457,14 @@ Adds a surface after a **PreviewOutput** instance is created. This API uses a pr **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------------------------------------------------ | -| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| +| Name | Type | Mandatory| Description | +| -------- | -----------| ---- | ------------------------------------------------------------------------------ | +| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -3485,8 +3485,8 @@ Starts to output preview streams. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3511,8 +3511,8 @@ Starts to output preview streams. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -3533,8 +3533,8 @@ Stops outputting preview streams. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3559,8 +3559,8 @@ Stops outputting preview streams. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** @@ -3581,9 +3581,9 @@ Listens for preview frame start events. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **frameStart**, indicating the preview frame start event.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | --------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'frameStart'**, indicating the preview frame start event.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -3604,10 +3604,10 @@ Listens for preview frame end events. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **frameEnd**, indicating the preview frame end event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the preview frame end event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -3627,10 +3627,10 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **error**, indicating the preview output error event.| -| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the preview output error event.| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | **Example** @@ -3647,7 +3647,7 @@ Enumerates the error codes used for preview output. **System capability**: SystemCapability.Multimedia.Camera.Core | Name | Value | Description | -| ------------- | ---- | ---------- | +| ------------- | ---- | -------- | | ERROR_UNKNOWN | -1 | Unknown error.| ## PreviewOutputError @@ -3656,8 +3656,8 @@ Defines the preview output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------------- | ------------------------- | +| Name| Type | Description | +| ---- | ------------------------------------------------- | ---------------------- | | code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| ## ImageRotation @@ -3666,8 +3666,8 @@ Enumerates the image rotation angles. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------ | ---- | --------------- | +| Name | Value | Description | +| ------------ | ---- | ------------- | | ROTATION_0 | 0 | The image rotates 0 degrees. | | ROTATION_90 | 90 | The image rotates 90 degrees. | | ROTATION_180 | 180 | The image rotates 180 degrees.| @@ -3679,11 +3679,11 @@ Defines geolocation information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------- | -| latitude | number | Yes | Latitude, in degree.| -| longitude | number | Yes | Longitude, in degree.| -| altitude | number | Yes | Altitude, in meter.| +| Name | Type | Mandatory|Description | +| ------------ | ------ | --- |------------ | +| latitude | number | Yes |Latitude, in degrees. | +| longitude | number | Yes |Longitude, in degrees. | +| altitude | number | Yes |Altitude, in meters. | ## QualityLevel @@ -3691,8 +3691,8 @@ Enumerates the image quality levels. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------- | ---- | -------------- | +| Name | Value | Description | +| -------------------- | ---- | ------------ | | QUALITY_LEVEL_HIGH | 0 | High image quality. | | QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| | QUALITY_LEVEL_LOW | 2 | Low image quality. | @@ -3704,12 +3704,12 @@ Defines the settings for photo capture. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Default Value | Description | -| -------- | ------------------------------- | ---- | ------------------ | ---------------------- | -| quality | [QualityLevel](#qualitylevel) | No | QUALITY_LEVEL_HIGH | Photo quality. | -| rotation | [ImageRotation](#imagerotation) | No | ROTATION_0 | Rotation angle of the photo. | -| location | [Location](#location) | No | (0,0,0) | Geolocation information of the photo. | -| mirror | boolean | No | false | Whether mirroring is enabled. By default, mirroring is disabled.| +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------------------------------- | ---- | ----------------- | -----------------| +| quality | [QualityLevel](#qualitylevel) | No | QUALITY_LEVEL_HIGH| Photo quality. | +| rotation | [ImageRotation](#imagerotation) | No | ROTATION_0 | Rotation angle of the photo. | +| location | [Location](#location) | No | (0,0,0) | Geolocation information of the photo. | +| mirror | boolean | No | false |Whether mirroring is enabled. By default, mirroring is disabled.| ## PhotoOutput @@ -3725,8 +3725,8 @@ Obtains the default shooting parameters. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | -------------------- | | callback | AsyncCallback<[PhotoCaptureSetting](#photocapturesetting)\> | Yes | Callback used to return the result.| **Example** @@ -3751,8 +3751,8 @@ Obtains the default shooting parameters. This API uses a promise to return the r **Return value** -| Type | Description | -| ----------------------------------------------------- | --------------------------- | +| Type | Description | +| ----------------------------------------------------- | ----------------------- | | Promise<[PhotoCaptureSetting](#photocapturesetting)\> | Promise used to return the result.| **Example** @@ -3773,8 +3773,8 @@ Captures a photo with the default shooting parameters. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -3799,10 +3799,10 @@ Captures a photo with the specified shooting parameters. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------ | -| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -3830,14 +3830,14 @@ Captures a photo with the specified shooting parameters. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------- | ---- | ---------- | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | -------- | | setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| @@ -3859,9 +3859,9 @@ Checks whether mirroring is supported. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. | **Example** @@ -3885,9 +3885,9 @@ Checks whether mirroring is supported. This API uses a promise to return the res **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------- | -| Promise | Promise used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite.| +| Type | Description | +| ----------------- | ------------------------------------------- | +| Promise | Promise used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. | **Example** @@ -3907,10 +3907,10 @@ Listens for shooting start events. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **captureStart**, indicating the shooting start event.| -| callback | AsyncCallback | Yes | Callback used to return the capture ID. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'captureStart'**, indicating the shooting start event.| +| callback | AsyncCallback | Yes | Callback used to return the capture ID. | **Example** @@ -3930,10 +3930,10 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **frameShutter**, indicating the frame shutter event.| -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | --- | ------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'frameShutter'**, indicating the frame shutter event.| +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | **Example** @@ -3954,10 +3954,10 @@ Listens for shooting end events. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ---------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **captureEnd**, indicating the shooting end event.| -| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'captureEnd'**, indicating the shooting end event.| +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | **Example** @@ -3978,10 +3978,10 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ----------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **error**, indicating the photo output error event.| -| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the photo output error event.| +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | **Example** @@ -3998,8 +3998,8 @@ Defines the frame shutter information. **System capability**: SystemCapability.Multimedia.Camera.Core | Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------ | -| captureId | number | Yes | ID of this capture action. | +| --------- | ------ | ---- | ---------- | +| captureId | number | Yes | ID of this capture action. | | timestamp | number | Yes | Timestamp when the frame shutter event is triggered.| ## CaptureEndInfo @@ -4009,9 +4009,9 @@ Defines the capture end information. **System capability**: SystemCapability.Multimedia.Camera.Core | Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ---------- | +| ---------- | ------ | ---- | ---------| | captureId | number | Yes | ID of this capture action.| -| frameCount | number | Yes | Number of frames captured. | +| frameCount | number | Yes | Number of frames captured. | ## PhotoOutputErrorCode @@ -4019,12 +4019,12 @@ Enumerates the error codes used for photo output. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------------- | ---- | ------------------ | -| ERROR_UNKNOWN | -1 | Unknown error. | -| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| -| ERROR_INSUFFICIENT_RESOURCES | 1 | Insufficient resources. | -| ERROR_TIMEOUT | 2 | Timeout. | +| Name | Value | Description | +| ----------------------------- | ---- | --------------- | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| +| ERROR_INSUFFICIENT_RESOURCES | 1 | Insufficient resources. | +| ERROR_TIMEOUT | 2 | Timeout. | ## PhotoOutputError @@ -4050,8 +4050,8 @@ Starts video recording. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -4076,8 +4076,8 @@ Starts video recording. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| @@ -4125,8 +4125,8 @@ Stops video recording. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** @@ -4135,7 +4135,7 @@ Stops video recording. This API uses a promise to return the result. videoOutput.stop().then(() => { console.log('Promise returned to indicate that stop method execution success.'); }) -``` +``` ### on('frameStart') @@ -4147,10 +4147,10 @@ Listens for video recording start events. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ----------------------------------------- | | type | string | Yes | Event type. The value is fixed at **frameStart**, indicating the video recording start event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4170,10 +4170,10 @@ Listens for video recording stop events. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------ | | type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the video recording stop event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4193,10 +4193,10 @@ Listens for errors that occur during video recording. This API uses a callback t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | --------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **error**, indicating the video output error event.| -| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | -------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the video output error event.| +| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | **Example** @@ -4212,10 +4212,10 @@ Enumerates the error codes used for video recording. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------ | ---- | ------------------ | -| ERROR_UNKNOWN | -1 | Unknown error. | -| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| ## VideoOutputError @@ -4233,9 +4233,9 @@ Enumerates metadata streams. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------- | ---- | ------------------ | -| FACE_DETECTION | 0 | Metadata object type.| +| Name | Value | Description | +| ------------------------- | ---- | ----------------- | +| FACE_DETECTION | 0 | Metadata object type.| ## Rect @@ -4243,10 +4243,10 @@ Defines a rectangle. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Description | -| -------- | ------ | --------------------- | -| topLeftX | number | X-axis coordinate of the upper left corner of the rectangle.| -| topLeftY | number | Y-axis coordinate of the upper left corner of the rectangle.| +| Name | Type | Description | +| -------- | ------ | -------------------- | +| topLeftX | number | X-axis coordinate of the upper left corner of the rectangle. | +| topLeftY | number | Y-axis coordinate of the upper left corner of the rectangle. | | width | number | Width of the rectangle. | | height | number | Height of the rectangle. | @@ -4264,8 +4264,8 @@ Obtains the metadata object type. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | --- | -------------------- | | callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.| **Example** @@ -4290,7 +4290,7 @@ Obtains the metadata object type. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type | Description | | --------------------------------------------------- | --------------------------- | | Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.| @@ -4312,9 +4312,9 @@ Obtains the metadata timestamp. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -4338,8 +4338,8 @@ Obtains the metadata timestamp. This API uses a promise to return the result. **Return value** -| Type | Description | -| ----------------- | --------------------------- | +| Type | Description | +| ---------------- | --------------------------- | | Promise | Promise used to return the result.| **Example** @@ -4360,9 +4360,9 @@ Obtains the bounding box of metadata. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ------------------------ | -| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| **Example** @@ -4387,7 +4387,7 @@ Obtains the bounding box of metadata. This API uses a promise to return the resu **Return value** | Type | Description | -| ----------------------- | --------------------------- | +| ---------------------- | --------------------------- | | Promise<[Rect](#rect)\> | Promise used to return the result.| **Example** @@ -4400,11 +4400,11 @@ metadataObject.getBoundingBox().then((rect) => { ## MetadataFaceObject -Implements the face object of metadata. It inherits **[MetadataObject](#metadataobject)**. +Implements the face object of metadata. It inherits [MetadataObject](#metadataobject). ## MetadataOutput -Implements metadata stream. It inherits **[CameraOutput](#cameraoutput)**. +Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. ### start @@ -4416,9 +4416,9 @@ Starts to output metadata. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -4442,9 +4442,9 @@ Starts to output metadata. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| ---------------------- | ------------------------ | +| Promise | Promise used to return the result.| **Example** @@ -4464,9 +4464,9 @@ Stops outputting metadata. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -4490,9 +4490,9 @@ Stops outputting metadata. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| ---------------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** @@ -4512,10 +4512,10 @@ Listens for metadata objects. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| -| callback | Callback\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- - | ---- | ------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| +| callback | Callback\> | Yes | Callback used to return the error information. | **Example** @@ -4535,10 +4535,10 @@ Listens for metadata errors. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------ | ---- | --------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| -| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | --------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| +| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | **Example** @@ -4550,14 +4550,14 @@ metadataOutput.on('error', (metadataOutputError) => { ## MetadataOutputErrorCode -Enumerates the error codes used for metadata output. +Enumerates the codes used for metadata output errors. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| +| Name | Value | Description | +| ------------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| ## MetadataOutputError @@ -4565,6 +4565,6 @@ Defines a metadata output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | --------------------------------------------------- | -------------------------- | +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | | code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | **MetadataOutput** error code.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 007d35d1408e2381aca841dd64cb9ce6a078b16a..4c04dd7a835c647889d70dff754d6baf14730efb 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -112,33 +112,109 @@ Registers the continuation management service and obtains a token. This API uses ``` ## continuationManager.on("deviceConnect")(deprecated) -> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect) instead. on(type: "deviceConnect", callback: Callback\): void; Subscribes to device connection events. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| + +**Example** + + ```js + continuationManager.on("deviceConnect", (data) => { + console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); + console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); + console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name)); + }); + ``` + ## continuationManager.on("deviceDisconnect")(deprecated) -> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect) instead. on(type: "deviceDisconnect", callback: Callback\): void; Subscribes to device disconnection events. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | callback | Callback\ | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + +**Example** + + ```js + continuationManager.on("deviceDisconnect", (data) => { + console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); + }); + ``` + ## continuationManager.off("deviceConnect")(deprecated) -> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect) instead. off(type: "deviceConnect", callback?: Callback\): void; Unsubscribes from device connection events. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | No| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| + +**Example** + + ```js + continuationManager.off("deviceConnect", (data) => { + console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); + console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); + console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name)); + }); + ``` + ## continuationManager.off("deviceDisconnect")(deprecated) -> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect) instead. off(type: "deviceDisconnect", callback?: Callback\): void; Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | callback | Callback\ | No| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + +**Example** + + ```js + continuationManager.off("deviceDisconnect", (data) => { + console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); + }); + ``` + ## continuationManager.on("deviceConnect")9+ on(type: "deviceConnect", token: number, callback: Callback\>): void; diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 43e096b951e7ea4d97ed9e0d40dc0481f34a0290..3a2f046c36b3c17bca7c87c71e18c69971b5683c 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -55,7 +55,9 @@ let options = {trim : false, declarationKey:"_declaration", commentKey : "_comment", parentKey : "_parent", typeKey : "_type", nameKey : "_name", elementsKey : "_elements"} let result = JSON.stringify(conv.convert(xml, options)); -console.log(result) +console.log(result); +// Output (non-compact) +// {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} ``` ## ConvertOptions diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 296b8a58c2e89677eed23ee377c7568603429646..00f23561e5e00936a425c2fbb6070e361597a4aa 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1529,9 +1529,9 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new rdb.RdbPredicates('EPLOYEE') +let predicates = new rdb.RdbPredicates('EMPLOYEE') predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EPLOYEE", predicates, function(err, resultSet){ +rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, function(err, resultSet){ if (err) { console.info("Failed to remoteQuery, err: " + err) return @@ -1567,7 +1567,7 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new rdb.RdbPredicates('EPLOYEE') +let predicates = new rdb.RdbPredicates('EMPLOYEE') predicates.greaterThan("id", 0) let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates) promise.then((resultSet) => { 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 cd1535b43bfe4e5d13a6460b066a082e31db8020..ff9f8d69e48847bd60741f174af4dbe92a19e2ee 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -55,7 +55,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let storage = data_storage.getStorageSync(path + '/mystore'); @@ -88,7 +88,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.getStorage(path + '/mystore', function (err, storage) { @@ -131,7 +131,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let getPromise = data_storage.getStorage(path + '/mystore'); @@ -167,7 +167,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.deleteStorageSync(path + '/mystore'); @@ -198,7 +198,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.deleteStorage(path + '/mystore', function (err) { @@ -239,7 +239,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let promisedelSt = data_storage.deleteStorage(path + '/mystore'); @@ -274,7 +274,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.removeStorageFromCacheSync(path + '/mystore'); @@ -305,7 +305,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.removeStorageFromCache(path + '/mystore', function (err) { @@ -347,7 +347,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 372e6feb7c832d873bd98ed238d5cf474df10a5d..02c4680e1e082798d81c692cb178ca72fe21cf9a 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -28,29 +28,42 @@ Enumerates the display states. | STATE_VR | 5 | The display is in VR mode.| | STATE_ON_SUSPEND | 6 | The display is powered on, and the CPU is suspended.| +## Rect9+ -## Display +Describes a rectangle on the display. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core -Describes the attributes of a display. +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------ | +| left | number | Yes | Yes | Left boundary of the rectangle.| +| top | number | Yes | Yes | Top boundary of the rectangle.| +| width | number | Yes | Yes | Width of the rectangle. | +| height | number | Yes | Yes | Height of the rectangle. | + +## WaterfallDisplayAreaRects9+ + +Describes the curved area (an area that is not intended for displaying content) on the waterfall display. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| ID of the display.| -| name | string | Yes| No| Name of the display.| -| alive | boolean | Yes| No| Whether the display is alive.| -| state | [DisplayState](#displaystate) | Yes| No| State of the display.| -| refreshRate | number | Yes| No| Refresh rate of the display.| -| rotation | number | Yes| No| Screen rotation angle of the display.| -| width | number | Yes| No| Width of the display, in pixels.| -| height | number | Yes| No| Height of the display, in pixels.| -| densityDPI | number | Yes| No| Screen density of the display, in DPI.| -| densityPixels | number | Yes| No| Screen density of the display, in pixels.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| -| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| -| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| +| Name | Type | Readable| Writable| Description | +| ------ | ------------- | ---- | ---- | ------------------ | +| left | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located on the left of the display surface.| +| top | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located at the top of the display surface.| +| right | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located on the right of the display surface.| +| bottom | [Rect](#rect9) | Yes | No | Bounding rectangle for the curved area, which is located at the bottom of the display surface.| + +## CutoutInfo9+ + +Describes the cutout, which is an area that is not intended for displaying content on the display. +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Readable| Writable| Description | +| --------------------------- | ------------- | ---- | ---- | ------------------ | +| boundingRects | Array\<[Rect](#rect9)> | Yes | No | Bounding rectangle for punch holes and notches.| +| waterfallDisplayAreaRects | [WaterfallDisplayAreaRects](#waterfalldisplayarearects9) | Yes| No| Curved area on the waterfall display.| ## display.getDefaultDisplay @@ -61,22 +74,24 @@ Obtains the default display object. This API uses an asynchronous callback to re **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| **Example** - ```js - var displayClass = null; - display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; - }); - ``` + +```js +var displayClass = null; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; +}); +``` ## display.getDefaultDisplay @@ -94,14 +109,16 @@ Obtains the default display object. This API uses a promise to return the result **Example** - ```js - let promise = display.getDefaultDisplay(); - promise.then(() => { - console.log('getDefaultDisplay success'); - }).catch((err) => { - console.log('getDefaultDisplay fail: ' + JSON.stringify(err)); - }); - ``` +```js +var displayClass = null; +let promise = display.getDefaultDisplay(); +promise.then((data) => { + displayClass = data; + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +}); +``` ## display.getDefaultDisplaySync9+ @@ -139,15 +156,15 @@ Obtains all display objects. This API uses an asynchronous callback to return th **Example** - ```js - display.getAllDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)) - }); - ``` +```js +display.getAllDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}); +``` ## display.getAllDisplay @@ -165,22 +182,22 @@ Obtains all display objects. This API uses a promise to return the result. **Example** - ```js - let promise = display.getAllDisplay(); - promise.then(() => { - console.log('getAllDisplay success'); - }).catch((err) => { - console.log('getAllDisplay fail: ' + JSON.stringify(err)); - }); - ``` +```js +let promise = display.getAllDisplay(); +promise.then((data) => { + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); +}); +``` ## display.hasPrivateWindow9+ hasPrivateWindow(displayId: number): boolean -Checks whether there is a visible privacy window on a display. The privacy window can be set by calling **[setPrivacyMode](js-apis-window.md#setprivacymode7)**. The content in the privacy window cannot be captured or recorded. +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling `[setPrivacyMode](js-apis-window.md#setprivacymode7)`. The content in the privacy window cannot be captured or recorded. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -194,21 +211,31 @@ This is a system API. | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| +|boolean | Whether there is a visible privacy window on the display.
The value `true` means that there is a visible privacy window on the display, and `false` means the opposite.
| **Example** - ```js - var ret = display.hasPrivateWindow(displayClass.id); - if (ret == undefined) { - console.log("HasPrivateWindow undefined."); - } - if (ret) { - console.log("HasPrivateWindow."); - } else if (!ret) { - console.log("Don't HasPrivateWindow."); +```js +var displayClass = null; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; } - ``` + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; +}); + +var ret = display.hasPrivateWindow(displayClass.id); +if (ret == undefined) { + console.log("Failed to check has privateWindow or not."); +} +if (ret) { + console.log("There has privateWindow."); +} else if (!ret) { + console.log("There has no privateWindow."); +} +``` ## display.on('add'|'remove'|'change') @@ -219,19 +246,20 @@ Subscribes to display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| | callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** - ```js - var callback = (data) => { - console.info('Listening enabled. Data: ' + JSON.stringify(data)) - } - display.on("add", callback); - ``` +```js +var callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)); +} +display.on("add", callback); +``` ## display.off('add'|'remove'|'change') @@ -242,12 +270,81 @@ Unsubscribes from display changes. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| | callback | Callback<number> | No| Callback used to return the ID of the display.| **Example** - ```js - display.off("remove"); - ``` + +```js +display.off("remove"); +``` + +## Display +Implements a `Display` instance, with properties and APIs defined. + +To call an API in the following API examples, you must first use `[getAllDisplay()](#displaygetalldisplay)`, `[getDefaultDisplay()](#displaygetdefaultdisplay)`, or `[getDefaultDisplaySync()](#displaygetdefaultdisplaysync)` to obtain a `Display` instance. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| id | number | Yes| No| ID of the display.| +| name | string | Yes| No| Name of the display.| +| alive | boolean | Yes| No| Whether the display is alive.| +| state | [DisplayState](#displaystate) | Yes| No| State of the display.| +| refreshRate | number | Yes| No| Refresh rate of the display.| +| rotation | number | Yes| No| Screen rotation angle of the display.| +| width | number | Yes| No| Width of the display, in pixels.| +| height | number | Yes| No| Height of the display, in pixels.| +| densityDPI | number | Yes| No| Screen density of the display, in DPI.| +| densityPixels | number | Yes| No| Screen density of the display, in pixels.| +| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| +| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| +| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| + +### getCutoutInfo9+ +getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void + +Obtains the cutout information of the display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to If the operation is successful, `err` is `undefined` and `data` is the `CutoutInfo` object obtained. Otherwise, `err` is an error object.| + +**Example** + +```js +displayClass.getCutoutInfo((err, data) => { + if (err.code) { + console.error('Failed to get cutoutInfo. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); +}) +``` +### getCutoutInfo9+ +getCutoutInfo(): Promise<CutoutInfo> + +Obtains the cutout information of the display. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[CutoutInfo](#cutoutinfo9)> | Promise used to return the `CutoutInfo` object.| + +**Example** + +```js +let promise = displayClass.getCutoutInfo(); +promise.then((data) => { + console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 5682921badad9367817fd3e421b1afb823970425..7ad7cfe126f1186189c62cd525098aad770cdabd 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -61,7 +61,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -89,7 +89,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -139,7 +139,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -167,7 +167,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -304,7 +304,7 @@ try { } ``` -### closeKVStore8+ ### +### closeKVStore8+ closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void @@ -350,7 +350,7 @@ const options = { ``` -### closeKVStore8+ ### +### closeKVStore8+ closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> @@ -404,7 +404,7 @@ const options = { ``` -### deleteKVStore8+ ### +### deleteKVStore8+ deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void @@ -447,7 +447,7 @@ try { } ``` -### deleteKVStore8+ ### +### deleteKVStore8+ deleteKVStore(appId: string, storeId: string): Promise<void> @@ -501,7 +501,7 @@ try { ``` -### getAllKVStoreId8+ ### +### getAllKVStoreId8+ getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void @@ -531,7 +531,7 @@ try { ``` -### getAllKVStoreId8+ ### +### getAllKVStoreId8+ getAllKVStoreId(appId: string): Promise<string[]> @@ -570,7 +570,7 @@ try { ``` -### on('distributedDataServiceDie')8+ ### +### on('distributedDataServiceDie')8+ on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void @@ -582,8 +582,8 @@ Subscribes to service status changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | Yes | Callback invoked to return a service status change event.| **Example** @@ -602,11 +602,11 @@ try { ``` -### off('distributedDataServiceDie')8+ ### +### off('distributedDataServiceDie')8+ off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from the service status changes. +Unsubscribes from service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -614,8 +614,8 @@ Unsubscribes from the service status changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | No | Callback used to return service status changes.| +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | No | Callback used to return a service status change event.| **Example** @@ -706,7 +706,7 @@ Defines the schema of a KV store. You can create a **Schema** object and place i | mode8+ | number | Schema mode. | | skip8+ | number | Size of a skip of the schema. | -### constructor8+ ### +### constructor8+ constructor() @@ -726,7 +726,7 @@ Represents a **Schema** instance, which provides the methods for defining the va | default8+ | string | Default value of a **FieldNode**.| | type8+ | number | Value of the data type corresponding to the specified node.| -### constructor8+ ### +### constructor8+ constructor(name: string) @@ -740,7 +740,7 @@ A constructor used to create a **FieldNode** instance with a string field. | ------ | -------- | ---- | --------------- | | name | string | Yes | Value of **FieldNode**.| -### appendChild8+ ### +### appendChild8+ appendChild(child: FieldNode): boolean @@ -790,7 +790,7 @@ Provides methods to obtain the KV store result sets, and query and move the data Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. -### getCount8+ ### +### getCount8+ getCount(): number @@ -823,7 +823,7 @@ try { } ``` -### getPosition8+ ### +### getPosition8+ getPosition(): number @@ -857,7 +857,7 @@ try { ``` -### moveToFirst8+ ### +### moveToFirst8+ moveToFirst(): boolean @@ -891,7 +891,7 @@ try { ``` -### moveToLast8+ ### +### moveToLast8+ moveToLast(): boolean @@ -925,7 +925,7 @@ try { ``` -### moveToNext8+ ### +### moveToNext8+ moveToNext(): boolean @@ -959,7 +959,7 @@ try { ``` -### moveToPrevious8+ ### +### moveToPrevious8+ moveToPrevious(): boolean @@ -993,7 +993,7 @@ try { ``` -### move8+ ### +### move8+ move(offset: number): boolean @@ -1033,7 +1033,7 @@ try { ``` -### moveToPosition8+ ### +### moveToPosition8+ moveToPosition(position: number): boolean @@ -1073,7 +1073,7 @@ try { ``` -### isFirst8+ ### +### isFirst8+ isFirst(): boolean @@ -1107,7 +1107,7 @@ try { ``` -### isLast8+ ### +### isLast8+ isLast(): boolean @@ -1140,7 +1140,7 @@ try { } ``` -### isBeforeFirst8+ ### +### isBeforeFirst8+ isBeforeFirst(): boolean @@ -1174,7 +1174,7 @@ try { ``` -### isAfterLast8+ ### +### isAfterLast8+ isAfterLast(): boolean @@ -1208,7 +1208,7 @@ try { ``` -### getEntry8+ ### +### getEntry8+ getEntry(): Entry @@ -1248,7 +1248,7 @@ Provides methods to create a **Query** object, which defines different data quer **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -### constructor8+ ### +### constructor8+ constructor() @@ -1257,7 +1257,7 @@ A constructor used to create a **Schema** instance. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -### reset8+ ### +### reset8+ reset(): Query @@ -1288,7 +1288,7 @@ try { ``` -### equalTo8+ ### +### equalTo8+ equalTo(field: string, value: number|string|boolean): Query @@ -1323,7 +1323,7 @@ try { ``` -### notEqualTo8+ ### +### notEqualTo8+ notEqualTo(field: string, value: number|string|boolean): Query @@ -1358,7 +1358,7 @@ try { ``` -### greaterThan8+ ### +### greaterThan8+ greaterThan(field: string, value: number|string|boolean): Query @@ -1393,7 +1393,7 @@ try { ``` -### lessThan8+ ### +### lessThan8+ lessThan(field: string, value: number|string): Query @@ -1428,7 +1428,7 @@ try { ``` -### greaterThanOrEqualTo8+ ### +### greaterThanOrEqualTo8+ greaterThanOrEqualTo(field: string, value: number|string): Query @@ -1463,7 +1463,7 @@ try { ``` -### lessThanOrEqualTo8+ ### +### lessThanOrEqualTo8+ lessThanOrEqualTo(field: string, value: number|string): Query @@ -1498,7 +1498,7 @@ try { ``` -### isNull8+ ### +### isNull8+ isNull(field: string): Query @@ -1532,7 +1532,7 @@ try { ``` -### inNumber8+ ### +### inNumber8+ inNumber(field: string, valueList: number[]): Query @@ -1568,7 +1568,7 @@ try { ``` -### inString8+ ### +### inString8+ inString(field: string, valueList: string[]): Query @@ -1603,7 +1603,7 @@ try { ``` -### notInNumber8+ ### +### notInNumber8+ notInNumber(field: string, valueList: number[]): Query @@ -1638,7 +1638,7 @@ try { ``` -### notInString8+ ### +### notInString8+ notInString(field: string, valueList: string[]): Query @@ -1673,7 +1673,7 @@ try { ``` -### like8+ ### +### like8+ like(field: string, value: string): Query @@ -1708,7 +1708,7 @@ try { ``` -### unlike8+ ### +### unlike8+ unlike(field: string, value: string): Query @@ -1743,7 +1743,7 @@ try { ``` -### and8+ ### +### and8+ and(): Query @@ -1773,7 +1773,7 @@ try { ``` -### or8+ ### +### or8+ or(): Query @@ -1803,7 +1803,7 @@ try { ``` -### orderByAsc8+ ### +### orderByAsc8+ orderByAsc(field: string): Query @@ -1838,7 +1838,7 @@ try { ``` -### orderByDesc8+ ### +### orderByDesc8+ orderByDesc(field: string): Query @@ -1873,7 +1873,7 @@ try { ``` -### limit8+ ### +### limit8+ limit(total: number, offset: number): Query @@ -1911,7 +1911,7 @@ try { ``` -### isNotNull8+ ### +### isNotNull8+ isNotNull(field: string): Query @@ -1945,7 +1945,7 @@ try { ``` -### beginGroup8+ ### +### beginGroup8+ beginGroup(): Query @@ -1975,7 +1975,7 @@ try { ``` -### endGroup8+ ### +### endGroup8+ endGroup(): Query @@ -2005,7 +2005,7 @@ try { ``` -### prefixKey8+ ### +### prefixKey8+ prefixKey(prefix: string): Query @@ -2040,7 +2040,7 @@ try { ``` -### setSuggestIndex8+ ### +### setSuggestIndex8+ setSuggestIndex(index: string): Query @@ -2075,7 +2075,7 @@ try { ``` -### deviceId8+ ### +### deviceId8+ deviceId(deviceId:string):Query @@ -2109,7 +2109,7 @@ try { ``` -### getSqlLike8+ ### +### getSqlLike8+ getSqlLike():string @@ -2303,7 +2303,9 @@ try { delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) -Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. +Deletes KV pairs that meet the specified conditions. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2337,7 +2339,9 @@ try { delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> -Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. +Deletes KV pairs that meet the specified conditions. This API uses a promise to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2352,7 +2356,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2379,11 +2383,224 @@ try { ``` +### backup9+ + +backup(file:string, callback: AsyncCallback<void>):void + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file, (err, data) => { + if (err) { + console.info("backup err : " + err); + } else { + console.info("backup data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### backup9+ + +backup(file:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database. This parameter cannot be empty and its length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file).then((data) => { + console.info("backup data : " + data); + }).catch((err) => { + console.info("backup err : " + err); + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### restore9+ + +restore(file:string, callback: AsyncCallback<void>):void + +Restores an RDB store from a database file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file, (err, data) => { + if (err) { + console.info("restore err : " + err); + } else { + console.info("restore data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### restore9+ + +restore(file:string): Promise<void> + +Restores an RDB store from a database file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file).then((data) => { + console.info("restore data : " + data); + }).catch((err) => { + console.info("restore err : " + err); + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### deleteBackup9+ + +deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void + +Deletes a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files, (err, data) => { + if (err) { + console.info("deleteBackup err : " + err); + } else { + console.info("deleteBackup data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### deleteBackup9+ + +deleteBackup(files:Array<string>): Promise<Array<[string, number]>> + +Deletes a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------- | ----------------------------------------------- | +| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files).then((data) => { + console.info("deleteBackup data : " + data); + }).catch((err) => { + console.info("deleteBackup err : " + err); + }) +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + ### on('dataChange') on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data change notifications of the specified type. +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2391,9 +2608,9 @@ Subscribes to data change notifications of the specified type. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return a data change event.| **Example** @@ -2409,7 +2626,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2417,8 +2634,8 @@ Subscribes to data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return a synchronization complete event. | **Example** @@ -2433,7 +2650,7 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data change notifications. +Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2441,26 +2658,35 @@ Unsubscribes from data change notifications. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ### off('syncComplete')9+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from data change events. This API uses a synchronous callback to return the result. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2468,21 +2694,27 @@ Unsubscribes from data change events. This API uses a synchronous callback to re | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | **Example** ```js let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); +class KvstoreModel { + call(data) { + console.log("syncComplete: " + data); + } + subscribeSyncComplete() { + if (kvStore != null) { + kvStore.on('syncComplete', this.call); + } + } + unsubscribeSyncComplete() { + if (kvStore != null) { + kvStore.off('syncComplete', this.call); + } + } } ``` @@ -2592,7 +2824,9 @@ try { putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void -Writes data to this KV store. This API uses an asynchronous callback to return the result. +Writes data to this KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2631,7 +2865,9 @@ try { putBatch(value: Array<ValuesBucket>): Promise<void> -Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. +Write data to this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2645,7 +2881,7 @@ Writes data of the **valuesbucket** type to this KV store. This API uses a promi | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2719,7 +2955,7 @@ try { ``` -### deleteBatch8+ ### +### deleteBatch8+ deleteBatch(keys: string[]): Promise<void> @@ -2775,7 +3011,7 @@ try { ``` -### startTransaction8+ ### +### startTransaction8+ startTransaction(callback: AsyncCallback<void>): void @@ -2827,7 +3063,7 @@ try { ``` -### startTransaction8+ ### +### startTransaction8+ startTransaction(): Promise<void> @@ -2862,7 +3098,7 @@ try { ``` -### commit8+ ### +### commit8+ commit(callback: AsyncCallback<void>): void @@ -2894,7 +3130,7 @@ try { ``` -### commit8+ ### +### commit8+ commit(): Promise<void> @@ -2924,7 +3160,7 @@ try { ``` -### rollback8+ ### +### rollback8+ rollback(callback: AsyncCallback<void>): void @@ -2956,7 +3192,7 @@ try { ``` -### rollback8+ ### +### rollback8+ rollback(): Promise<void> @@ -2986,7 +3222,7 @@ try { ``` -### enableSync8+ ### +### enableSync8+ enableSync(enabled: boolean, callback: AsyncCallback<void>): void @@ -3019,7 +3255,7 @@ try { ``` -### enableSync8+ ### +### enableSync8+ enableSync(enabled: boolean): Promise<void> @@ -3055,7 +3291,7 @@ try { ``` -### setSyncRange8+ ### +### setSyncRange8+ setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void @@ -3087,7 +3323,7 @@ try { ``` -### setSyncRange8+ ### +### setSyncRange8+ setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> @@ -3279,7 +3515,7 @@ try { } ``` -### getEntries8+ ### +### getEntries8+ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void @@ -3325,7 +3561,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(keyPrefix: string): Promise<Entry[]> @@ -3383,7 +3619,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void @@ -3434,7 +3670,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query): Promise<Entry[]> @@ -3492,7 +3728,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -3541,7 +3777,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(keyPrefix: string): Promise<KvStoreResultSet> @@ -3601,7 +3837,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -3649,7 +3885,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query): Promise<KvStoreResultSet> @@ -3705,12 +3941,14 @@ try { } ``` -### getResultSet9+ ### +### getResultSet9+ getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -3740,12 +3978,14 @@ try { console.log('An unexpected error occurred. Error:' + e); } ``` -### getResultSet9+ ### +### getResultSet9+ getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -3758,7 +3998,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **DataSharePred | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise that returns no value.| **Example** @@ -3780,7 +4020,7 @@ try { console.log('An unexpected error occurred. Error:' + e); } ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -3814,7 +4054,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet): Promise<void> @@ -3851,7 +4091,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query, callback: AsyncCallback<number>): void @@ -3897,7 +4137,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query): Promise<number> @@ -3952,7 +4192,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void @@ -3994,7 +4234,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string): Promise<void> @@ -4043,11 +4283,11 @@ try { ``` -### on('syncComplete')8+ ### +### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4055,8 +4295,8 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event. | **Example** @@ -4079,11 +4319,11 @@ try { ``` -### off('syncComplete')8+ ### +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the data synchronization complete events. +Unsubscribes from synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4091,25 +4331,31 @@ Unsubscribes from the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | **Example** ```js let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); +class KvstoreModel { + call(data) { + console.log("syncComplete: " + data); + } + subscribeSyncComplete() { + if (kvStore != null) { + kvStore.on('syncComplete', this.call); + } + } + unsubscribeSyncComplete() { + if (kvStore != null) { + kvStore.off('syncComplete', this.call); + } + } } ``` -### on('dataChange')9+ ### +### on('dataChange')9+ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void @@ -4121,9 +4367,9 @@ Subscribes to data changes of the specified type. This API returns the result sy | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -4135,11 +4381,11 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun ``` -### off('dataChange')9+ ### +### off('dataChange')9+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API returns the result synchronously. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4147,19 +4393,28 @@ Unsubscribes from the data change events. This API returns the result synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ### sync7+ @@ -4229,7 +4484,7 @@ try { } ``` -### setSyncParam8+ ### +### setSyncParam8+ setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void @@ -4259,7 +4514,7 @@ try { ``` -### setSyncParam8+ ### +### setSyncParam8+ setSyncParam(defaultAllowedDelayMs: number): Promise<void> @@ -4297,7 +4552,7 @@ try { ``` -### getSecurityLevel8+ ### +### getSecurityLevel8+ getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void @@ -4325,7 +4580,7 @@ try { ``` -### getSecurityLevel8+ ### +### getSecurityLevel8+ getSecurityLevel(): Promise<SecurityLevel> @@ -4365,7 +4620,7 @@ For example, a device KV store can be used to implement image sharing between de Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. -### get8+ ### +### get8+ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void @@ -4400,7 +4655,7 @@ try{ ``` -### get8+ ### +### get8+ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> @@ -4444,7 +4699,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void @@ -4492,7 +4747,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> @@ -4551,7 +4806,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void @@ -4603,7 +4858,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query): Promise<Entry[]> @@ -4661,7 +4916,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void @@ -4714,7 +4969,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, query: Query): Promise<Entry[]> @@ -4774,7 +5029,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -4809,7 +5064,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> @@ -4853,7 +5108,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -4905,7 +5160,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query): Promise<KvStoreResultSet> @@ -4969,7 +5224,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -5021,7 +5276,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> @@ -5087,7 +5342,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -5122,7 +5377,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet): Promise<void> @@ -5160,7 +5415,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query, callback: AsyncCallback<number>): void @@ -5207,7 +5462,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query): Promise<number> @@ -5263,7 +5518,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; @@ -5310,7 +5565,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(deviceId: string, query: Query): Promise<number> @@ -5366,7 +5621,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void @@ -5408,7 +5663,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string): Promise<void> @@ -5457,7 +5712,7 @@ try { ``` -### sync8+ ### +### sync8+ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void @@ -5496,7 +5751,7 @@ try { } ``` -### sync9+ ### +### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void @@ -5538,11 +5793,11 @@ try { } ``` -### on('syncComplete')8+ ### +### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5550,8 +5805,8 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback | Yes |Callback used to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback |Callback | Yes |Callback invoked to return a synchronization complete event. | **Example** @@ -5574,11 +5829,11 @@ try { ``` -### off('syncComplete')8+ ### +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API returns the result synchronously. +Unsubscribes from synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5586,25 +5841,31 @@ Unsubscribes from the synchronization complete events. This API returns the resu | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback9+ ### +### on('dataChange')9+ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void @@ -5616,9 +5877,9 @@ Subscribes to data changes of the specified type. This API returns the result sy | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -5630,11 +5891,11 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun ``` -### off('dataChange')9+ ### +### off('dataChange')9+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API returns the result synchronously. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5642,19 +5903,28 @@ Unsubscribes from the data change events. This API returns the result synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ## SyncMode @@ -5668,4 +5938,3 @@ Enumerates the synchronization modes. | PULL_ONLY |0 |Pull data from the peer end to the local end only.| | PUSH_ONLY |1 |Push data from the local end to the peer end only.| | PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| - diff --git a/en/application-dev/reference/apis/js-apis-document.md b/en/application-dev/reference/apis/js-apis-document.md index 3fbdc4f46c5e28f74743575a12f23fc138350f58..1ff80d1b41633b2fc1dc351a3c0180baec1d71b6 100644 --- a/en/application-dev/reference/apis/js-apis-document.md +++ b/en/application-dev/reference/apis/js-apis-document.md @@ -2,7 +2,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. -> - The APIs of this module will be deprecated and are not recommended for use. An exception will be thrown if any of the APIs is called. +> - The APIs of this module have been deprecated since API version 9 and are not recommended for use. An exception will be thrown if any of the APIs is called. ## Modules to Import @@ -10,7 +10,7 @@ import document from '@ohos.document'; ``` -## document.choose +## document.choose(deprecated) choose(types? : string[]): Promise<string> @@ -20,15 +20,15 @@ Chooses files of the specified types using the file manager. This API uses a pro **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------- | -| types | string[] | No | Types of the files to choose. | + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | types | string[] | No | Types of the files to choose.| **Return value** -| Type | Description | -| --------------------- | -------------- | -| Promise<string> | Promise used to return the result. An error code is returned.| + | Type | Description | + | --------------------- | -------------- | + | Promise<string> | Promise used to return the result. An error code is returned.| **Example** @@ -36,7 +36,7 @@ Chooses files of the specified types using the file manager. This API uses a pro let types = []; document.choose(types); ``` -## document.choose +## document.choose(deprecated) choose(callback:AsyncCallback<string>): void @@ -46,9 +46,9 @@ Chooses a file using the file manager. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| **Example** @@ -58,7 +58,7 @@ Chooses a file using the file manager. This API uses an asynchronous callback to // Do something with the URI. }); ``` -## document.choose +## document.choose(deprecated) choose(types:string[], callback:AsyncCallback<string>): void @@ -68,10 +68,10 @@ Chooses files using the file manager. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| types | string[] | No | Types of the files to choose.| -| callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | types | string[] | No | Types of the files to choose.| + | callback | AsyncCallback<string> | Yes | Callback used to return the result. An error code is returned.| **Example** @@ -83,7 +83,7 @@ Chooses files using the file manager. This API uses an asynchronous callback to }); ``` -## document.show +## document.show(deprecated) show(uri:string, type:string):Promise<void> @@ -93,16 +93,16 @@ Opens a file. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | ---------------------------- | -| uri | string | Yes | URI of the file to open.| -| type | string | Yes | Type of the file to open.| + | Name| Type | Mandatory| Description | + | ---- | ------ | ---- | ---------------------------- | + | uri | string | Yes | URI of the file to open.| + | type | string | Yes | Type of the file to open.| **Return value** -| Type | Description | -| --------------------- | ------------ | -| Promise<void> | Promise used to return the result. An error code is returned.| + | Type | Description | + | --------------------- | ------------ | + | Promise<void> | Promise used to return the result. An error code is returned.| **Example** @@ -112,7 +112,7 @@ Opens a file. This API uses a promise to return the result. document.show(uri, type); ``` -## document.show +## document.show(deprecated) show(uri:string, type:string, callback:AsyncCallback<void>): void @@ -122,11 +122,11 @@ Opens a file. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| uri | string | Yes | URI of the file to open.| -| type | string | Yes | Type of the file to open.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | + | Name | Type | Mandatory| Description | + | -------- | --------------------------- | ---- | ---------------------------- | + | uri | string | Yes | URI of the file to open.| + | type | string | Yes | Type of the file to open.| + | callback | AsyncCallback<void> | Yes | Callback used to return the result. An error code is returned. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md index 089bf96cb239204c4b52c3ce71848f15141d76a4..c5edd6538136499bfe2deb04450cefbda2d8f146 100644 --- a/en/application-dev/reference/apis/js-apis-effectKit.md +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -67,7 +67,7 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses a promi | Type | Description | | ---------------------- | -------------- | -| Promisse\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.| +| Promise\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 1849150107a5922136403a0c01cb24eb1152d675..d8b5065a9e6e99693e97cf02fd64874b26e19961 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -18,7 +18,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callba Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -27,8 +27,8 @@ Enables a device administrator application based on the specified bundle name an | Name | Type | Mandatory | Description | | -------------- | ----------------------------------- | ---- | ------------------ | | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -57,7 +57,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -66,8 +66,8 @@ Enables a device administrator application based on the specified bundle name an | Name | Type | Mandatory | Description | | -------------- | ----------------------------------- | ---- | ---------------------------- | | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | | userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -97,7 +97,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -106,8 +106,8 @@ Enables a device administrator application based on the specified bundle name an | Name | Type | Mandatory | Description | | -------------- | ----------------------------------- | ---- | ---------------------------- | | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | | userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** @@ -141,7 +141,7 @@ disableAdmin(admin: Want, callback: AsyncCallback\): void Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -174,7 +174,7 @@ disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): vo Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -208,7 +208,7 @@ disableAdmin(admin: Want, userId?: number): Promise\ Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN **System capability**: SystemCapability.Customization.EnterpriseDeviceManager @@ -467,7 +467,7 @@ Obtains a **DeviceSettingsManager** object. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | -------- | --------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Usage + +Before calling any API in **EnterpriseDeviceManager**, use **getDeviceSettingsManager** to create an **EnterpriseDeviceManager** instance. + +```js +import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager' + +enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + let deviceMgr = mgr; +}); +``` + +## DeviceSettingsManager.setDateTime + +setDateTime(admin: Want, time: number, callback: AsyncCallback): void + +Sets the system time. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.EDM_MANAGE_DATETIME + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| +| time | number | Yes| Timestamp (ms).| +| callback | AsyncCallback | Yes| Callback used to the result. If the system time is set successfully, **err** is **null**; otherwise, **err** is an error object.| + +**Example** + +```js +import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager' + +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + return; + } + mgr.setDateTime(wantTemp, 1526003846000, (error) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + } + }); +}); +``` + +## DeviceSettingsManager.setDateTime + +setDateTime(admin: Want, time: number): Promise + +Sets the system time. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.EDM_MANAGE_DATETIME + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| +| time | number | Yes| Timestamp (ms).| + +**Return value** + +| Type | Description | +| ----- | ----------------------------------- | +| Promise | Promise that returns no value.| + + +**Example** + +```js +import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager' + +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.getDeviceSettingsManager().then((mgr) => { + mgr.setDateTime(wantTemp, 1526003846000).then(() => { + }).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); + }) +}).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-environment.md b/en/application-dev/reference/apis/js-apis-environment.md index d023cdc8403d028ff250d3ea7afa82858d6ad5b8..3f879c77b9ef5cc9427ff5ac74b5758769ddb70f 100644 --- a/en/application-dev/reference/apis/js-apis-environment.md +++ b/en/application-dev/reference/apis/js-apis-environment.md @@ -1,6 +1,6 @@ # Environment -This module provides JS APIs for obtaining the root directories of the storage and public files. +The **Environment** module provides APIs for obtaining the root directories of the storage and public files. > **NOTE** > @@ -21,13 +21,13 @@ Obtains the root directory of the storage. This API uses a promise to return the **System capability**: SystemCapability.FileManagement.File.Environment -- Return value +**Return value** - | Type | Description | - | --------------------- | ---------------- | - | Promise<string> | Promise returned with the root directory of the storage.| +| Type | Description | +| --------------------- | ---------------- | +| Promise<string> | Promise returned with the root directory of the storage.| -- Example +**Example** ```js environment.getStorageDataDir().then(function(path){ @@ -45,13 +45,13 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac **System capability**: SystemCapability.FileManagement.File.Environment -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | -------------------------------- | - | callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of the storage.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of the storage.| -- Example +**Example** ```js environment.getStorageDataDir(function(error, path){ @@ -67,13 +67,13 @@ Obtains the root directory of public files. This API uses a promise to return th **System capability**: SystemCapability.FileManagement.File.Environment -- Return value +**Return value** - | Type | Description | - | --------------------- | ------------------ | - | Promise<string> | Promise returned with the root directory of public files.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<string> | Promise returned with the root directory of public files.| -- Example +**Example** ```js environment.getUserDataDir().then(function(path){ @@ -91,13 +91,13 @@ Obtains the root directory of public files. This API uses an asynchronous callba **System capability**: SystemCapability.FileManagement.File.Environment -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------- | --------------------------- | ---- | -------------------------------- | - | callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of public files.| - -- Example +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<string> | Yes | Asynchronous callback used to return the root directory of public files.| + +**Example** ```js environment.getUserDataDir(function(error, path){ diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-errorManager.md index a06e1650bd6f3614a33c58dd092b55451d0a0db8..69d3c3bf8240d370a364294d4089aa445f3809cc 100644 --- a/en/application-dev/reference/apis/js-apis-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-errorManager.md @@ -33,14 +33,8 @@ var observer = { console.log('onUnhandledException, errorMsg: ', errorMsg) } } -errorManager.registerErrorObserver(observer) - .then((data) => { - console.log('----------- registerErrorObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- registerErrorObserver fail ----------', err); - }) - +const registerErrorObserverNumber=errorManager.registerErrorObserver(observer) +console.info(registerErrorObserverNumber) ``` ## ErrorManager.unregisterErrorObserver diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md index 15e434ce7b5e6e29d67749b6d12a1069fb258c75..eace629fc87a608f2235f9887c4b0e075ce38b4e 100644 --- a/en/application-dev/reference/apis/js-apis-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-formInfo.md @@ -96,10 +96,27 @@ Enumerates the widget parameters. | Name | Value | Description | | ----------- | ---- | ------------ | -| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget.
**System API**: This is a system API and cannot be called by third-party applications. | +| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | ID of a widget.
**System API**: This is a system API and cannot be called by third-party applications. | | DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | | NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | | MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | | WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | | HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | +| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
This is a system API. | +| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.
This is a system API. | + +## FormDimension + +Enumerates the widget dimensions. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| Dimension_1_29+ | 1 | 1 x 2. | +| Dimension_2_29+ | 2 | 2 x 2. | +| Dimension_2_49+ | 3 | 2 x 4. | +| Dimension_4_49+ | 4 | 4 x 4. | +| Dimension_2_19+ | 5 | 2 x 1. | diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-formerror.md index b5868572cb1d74e528b029609da121a4db0b3ca6..9425026504a875b92fe5d2312b7de6d4c1e61d84 100644 --- a/en/application-dev/reference/apis/js-apis-formerror.md +++ b/en/application-dev/reference/apis/js-apis-formerror.md @@ -28,16 +28,16 @@ SystemCapability.Ability.Form | ----------- | ---- | ------------ | | ERR_COMMON | 1 | Default error code. | | ERR_PERMISSION_DENY | 2 | No permission to perform the operation. | -| ERR_GET_INFO_FAILED | 4 | Failed to query widget information. | -| ERR_GET_BUNDLE_FAILED | 5 | Failed to query the bundle information. | -| ERR_GET_LAYOUT_FAILED | 6 | Failed to query the layout information. | +| ERR_GET_INFO_FAILED | 4 | Failed to obtain the widget information. | +| ERR_GET_BUNDLE_FAILED | 5 | Failed to obtain the bundle information. | +| ERR_GET_LAYOUT_FAILED | 6 | Failed to obtain the layout information. | | ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. | -| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match. | +| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. | | ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. | | ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. | | ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. | | ERR_MAX_INSTANCES_PER_FORM | 12 | The number of instances per widget exceeds the upper limit. | -| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets applied by other applications. | +| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets provided by other applications. | | ERR_PROVIDER_DEL_FAIL | 14 | The widget provider failed to delete the widget. | | ERR_MAX_FORMS_PER_CLIENT | 15 | The number of widgets applied for by the widget host exceeds the upper limit. | | ERR_MAX_SYSTEM_TEMP_FORMS | 16 | The number of temporary widgets exceeds the upper limit. | @@ -48,3 +48,4 @@ SystemCapability.Ability.Form | ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. | | ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | | ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | +| ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
This is a system API. | diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md index 769b226018f184016164e0866c4020fa5e601c5a..7ed0ff46de845198aac96bbcf7ebdeaad4055ad1 100644 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -4,7 +4,8 @@ The **FormHost** module provides APIs related to the widget host, which is an ap > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -28,13 +29,11 @@ Deletes a widget. This API uses an asynchronous callback to return the result. A **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | ID of a widget.| +| formId | string | Yes | Widget ID.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -58,19 +57,17 @@ Deletes a widget. This API uses a promise to return the result. After this API i **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | - | formId | string | Yes | ID of a widget.| + | formId | string | Yes | Widget ID.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Parameters** @@ -93,13 +90,11 @@ Releases a widget. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | ID of a widget.| +| formId | string | Yes | Widget ID.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -123,13 +118,11 @@ Releases a widget. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ----------- | -| formId | string | Yes | ID of a widget. | +| formId | string | Yes | Widget ID. | | isReleaseCache | boolean | Yes | Whether to release the cache.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -154,20 +147,18 @@ Releases a widget. This API uses a promise to return the result. After this API **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ----------- | - | formId | string | Yes | ID of a widget. | + | formId | string | Yes | Widget ID. | | isReleaseCache | boolean | No | Whether to release the cache.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -190,13 +181,11 @@ Requests a widget update. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | ID of a widget.| +| formId | string | Yes | Widget ID.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -220,19 +209,17 @@ Requests a widget update. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | - | formId | string | Yes | ID of a widget.| + | formId | string | Yes | Widget ID.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -255,13 +242,11 @@ Converts a temporary widget to a normal one. This API uses an asynchronous callb **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| formId | string | Yes | ID of a widget.| +| formId | string | Yes | Widget ID.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -285,19 +270,17 @@ Converts a temporary widget to a normal one. This API uses a promise to return t **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | - | formId | string | Yes | ID of a widget.| + | formId | string | Yes | Widget ID.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -320,8 +303,6 @@ Instructs the widget framework to make a widget visible. This API uses an asynch **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -350,8 +331,6 @@ Instructs the widget framework to make a widget visible. This API uses a promise **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -362,7 +341,7 @@ Instructs the widget framework to make a widget visible. This API uses a promise | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -385,8 +364,6 @@ Instructs the widget framework to make a widget invisible. This API uses an asyn **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -415,8 +392,6 @@ Instructs the widget framework to make a widget invisible. This API uses a promi **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -427,7 +402,7 @@ Instructs the widget framework to make a widget invisible. This API uses a promi | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -450,8 +425,6 @@ Instructs the widget framework to make a widget updatable. This API uses an asyn **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -480,8 +453,6 @@ Instructs the widget framework to make a widget updatable. This API uses a promi **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -492,7 +463,7 @@ Instructs the widget framework to make a widget updatable. This API uses a promi | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -515,8 +486,6 @@ Instructs the widget framework to make a widget not updatable. This API uses an **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -545,8 +514,6 @@ Instructs the widget framework to make a widget not updatable. This API uses a p **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -557,7 +524,7 @@ Instructs the widget framework to make a widget not updatable. This API uses a p | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -578,8 +545,6 @@ Checks whether the system is ready. This API uses an asynchronous callback to re **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -605,13 +570,11 @@ Checks whether the system is ready. This API uses a promise to return the result **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -634,8 +597,6 @@ Obtains the widget information provided by all applications on the device. This **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -665,8 +626,6 @@ Obtains the widget information provided by all applications on the device. This **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Return value** | Type | Description | @@ -694,8 +653,6 @@ Obtains the widget information provided by a given application on the device. Th **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -726,8 +683,6 @@ Obtains the widget information provided by a given application on the device. Th **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -759,8 +714,6 @@ Obtains the widget information provided by a given application on the device. Th **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -794,8 +747,6 @@ Deletes invalid widgets from the list. This API uses an asynchronous callback to **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -826,8 +777,6 @@ Deletes invalid widgets from the list. This API uses a promise to return the res **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -861,8 +810,6 @@ Obtains the widget state. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -902,8 +849,6 @@ Obtains the widget state. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -944,8 +889,6 @@ Subscribes to widget uninstall events. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -970,8 +913,6 @@ Unsubscribes from widget uninstall events. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -998,8 +939,6 @@ Instructs the widgets to make themselves visible. This API uses an asynchronous **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -1029,8 +968,6 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -1042,7 +979,7 @@ Instructs the widgets to make themselves visible. This API uses a promise to ret | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -1065,8 +1002,6 @@ Instructs the widgets to enable or disable updates. This API uses an asynchronou **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -1096,8 +1031,6 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type | Mandatory| Description | @@ -1109,7 +1042,7 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -1121,3 +1054,71 @@ Instructs the widgets to enable or disable updates. This API uses a promise to r console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); }); ``` +## shareForm9+ + +shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void; + +Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; + formHost.shareForm(formId, deviceId, (error, data) => { + if (error.code) { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + } + }); + ``` + +## shareForm9+ + +shareForm(formId: string, deviceId: string): Promise<void>; + +Shares a specified widget with a remote device. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | Widget ID.| + | deviceId | string | Yes | Remote device ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Parameters** + + ```js + var formId = "12400633174999288"; + var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; + formHost.shareForm(formId, deviceId).then(() => { + console.log('formHost shareForm success'); + }).catch((error) => { + console.log('formHost shareForm, error:' + JSON.stringify(error)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..eb94104e5e3dfc430db1f395f48ac0302d1e0a1c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @@ -0,0 +1,66 @@ +# InputMethodExtensionAbility + +The **InputMethodExtensionAbility** module provides the **InputMethodExtensionAbility** and **InputMethodExtensionContext** APIs that you can implement to develop input methods and manage their lifecycles. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +``` +import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; +``` + +## Attributes + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) | Yes| No| Context of the **InputMethodExtension**, which is inherited from **ExtensionContext**.| + + +## InputMethodExtensionAbility.onCreate() + +onCreate(want: Want): void; + +Called when the **InputMethodExtension** ability is started to implement initialization. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to the **InputMethodExtension** ability, including the ability name and bundle name. | + +**Example** + + ```js + class InputMethodExt extends InputMethodExtensionAbility { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + } + ``` + + +## InputMethodExtensionAbility.onDestroy() + +onDestroy(): void; + +Called when this **InputMethodExtension** ability is destroyed to clear resources. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Example** + + ```js + class InputMethodExt extends InputMethodExtensionAbility { + onDestroy() { + console.log('onDestroy'); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md new file mode 100644 index 0000000000000000000000000000000000000000..ae8312d452b3a7a0fdea35b0330b5f092ddef05d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -0,0 +1,169 @@ +# InputMethodExtensionContext + +The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities. + +You can use the APIs of this module to start, terminate, connect, and disconnect abilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +``` +import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext'; +``` + +## Usage + +Before using the **InputMethodExtensionContext** module, you must define a child class that inherits from **InputMethodExtensionAbility**. + +```js + import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; + class MainAbility extends InputMethodExtensionAbility { + onCreate() { + let context = this.context; + } + } +``` + +## InputMethodExtensionContext.startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void; + +Starts an ability with the **want** parameter. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility"}; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringify(err)); + }); + ``` + +## InputMethodExtensionContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise\; + +Starts an ability with the mandatory **want** and optional **options** parameters. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| +| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```js + let want = { + "bundleName": "com.example.myapp", + "abilityName": "MyAbility" + }; + this.context.startAbility(want).then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + + ``` + +## InputMethodExtensionContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void + +Starts an ability with the **want** and **options** parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| options | [StartOptions](js-apis-application-StartOptions.md) | 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": "MainAbility" + }; + var options = { + windowMode: 0, + }; + this.context.startAbility(want, options, (error) => { + console.log("error.code = " + error.code) + }) + ``` + +## InputMethodExtensionContext.terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + + ```js +this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringify(err)); +}); + ``` + +## InputMethodExtensionContext.terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + + ```js + this.context.terminateSelf().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 47f0d3429179406f598940f977baab87ef7b3482..f29975c5b4459acfd3d22e1a0f40b0579969ba24 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -45,8 +45,8 @@ Obtains an **[InputMethodController](#inputmethodcontroller)** instance. **Return value** -| Type | Description | -| ----------------------------------------- | ---------------------------- | +| Type | Description | +| ----------------------------------------------- | ------------------------ | | [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.| **Example** @@ -77,9 +77,9 @@ Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. ``` ## inputMethod.switchInputMethod9+ -switchInputMethod(target: InputmethodProperty, callback: AsyncCallback<boolean>): void; +switchInputMethod(target: InputMethodProperty, callback: AsyncCallback<boolean>): void -Switches to another input method. This API uses an asynchronous callback to return the result. This API can be used only in the stage model. +Switches to another input method. This API can be used only in the stage model. It uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -88,20 +88,28 @@ Switches to another input method. This API uses an asynchronous callback to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | |target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result.| **Example** ```js - inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { - prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); - }); +inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"} ,(err,result) => { + if (err) { + console.error("switchInputMethod err: " + JSON.stringify(err)); + return; + } + if (result) { + console.info("Success to switchInputMethod.(callback)"); + } else { + console.error("Failed to switchInputMethod.(callback)"); + } +}); ``` ## inputMethod.switchInputMethod9+ -switchInputMethod(target: InputmethodProperty): Promise<boolean> +switchInputMethod(target: InputMethodProperty): Promise<boolean> -Switches to another input method. This API uses a promise to return the result. This API can be used only in the stage model. +Switches to another input method. This API can be used only in the stage model. It uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -112,27 +120,55 @@ Switches to another input method. This API uses a promise to return the result. |target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| **Return value** + | Type | Description | | ----------------------------------------- | ---------------------------- | -| Promise\ | Promise used to return the execution result. | +| Promise\ | Promise used to return the execution result.| **Example** ```js - inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { - prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); - }); +inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"}).then((result) => { + if (result) { + console.info("Success to switchInputMethod.(promise)"); + } else { + console.error("Failed to switchInputMethod.(promise)"); + } +}).catch((err) => { + console.error("switchInputMethod promise err: " + err); +}) +``` +## inputMethod.getCurrentInputMethod9+ + +getCurrentInputMethod(): InputMethodProperty + +Obtains the current input method. This API synchronously returns the **InputmethodProperty** instance of the current input method. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| -------------------------------------------- | ------------------------ | +| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method. | + +**Example** + + +```js +var currentIme = inputMethod.getCurrentInputMethod(); ``` + ## InputMethodController -In the following API examples, you must first use [getInputMethodController](#inputmethodgetinputmethodcontroller) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. ### stopInput stopInput(callback: AsyncCallback<boolean>): void -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -145,16 +181,24 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. **Example** ```js - InputMethodController.stopInput((error)=>{ - console.info('stopInput'); - }); +InputMethodController.stopInput((error, result) => { + if (error) { + console.error("failed to stopInput because: " + JSON.stringify(error)); + return; + } + if (result) { + console.info("Success to stopInput.(callback)"); + } else { + console.error("Failed to stopInput.(callback)"); + } +}); ``` ### stopInput stopInput(): Promise<boolean> -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -162,29 +206,200 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden. | +| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| **Example** ```js - var isSuccess = InputMethodController.stopInput(); - console.info('stopInput isSuccess = ' + isSuccess); +InputMethodController.stopInput().then((result) => { + if (result) { + console.info("Success to stopInput.(promise)"); + } else { + console.error("Failed to stopInput.(promise)"); + } +}).catch((err) => { + console.error("stopInput promise err: " + err); +}) +``` + +### showSoftKeyboard9+ ### + +showSoftKeyboard(callback: AsyncCallback<void>): void + +Shows this soft keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| + +**Example** + +```js +InputMethodController.showSoftKeyboard((err) => { + if (err == undefined) { + console.info('showSoftKeyboard success'); + } else { + console.error('showSoftKeyboard failed because : ' + JSON.stringify(err)); + } +}) +``` + + +### showSoftKeyboard9+ ### + +showSoftKeyboard(): Promise<void> + +Shows this soft keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +InputMethodController.showSoftKeyboard().then(async (err) => { + console.log('showSoftKeyboard success'); +}).catch((err) => { + console.error('showSoftKeyboard promise err: ' + JSON.stringify(err)); +}); +``` + +### hideSoftKeyboard9+ ### + +hideSoftKeyboard(callback: AsyncCallback<void>): void + +Hides this soft keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| + +**Example** + +```js +InputMethodController.hideSoftKeyboard((err) => { + if (err == undefined) { + console.info('hideSoftKeyboard success'); + } else { + console.error('hideSoftKeyboard failed because : ' + JSON.stringify(err)); + } +}) +``` + + +### hideSoftKeyboard9+ ### + +hideSoftKeyboard(): Promise<void> + +Hides this soft keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +InputMethodController.hideSoftKeyboard().then(async (err) => { + console.log('hideSoftKeyboard success'); +}).catch((err) => { + console.error('hideSoftKeyboard promise err: ' + JSON.stringify(err)); +}); ``` ## InputMethodSetting8+ -In the following API examples, you must first use [getInputMethodSetting](#inputmethodgetinputmethodcontroller) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. + +### listInputMethod9+ + +listInputMethod(enable: boolean, callback: AsyncCallback<Array<InputMethodProperty>>): void + +Obtains a list of activated or deactivated input methods. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------- | +| enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods. | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods. | + +**Example** + +```js +imeList: Array = null +InputMethodSetting.listInputMethod(true, (err,data) => { + if (err) { + console.error("listInputMethod failed because: " + JSON.stringify(err)); + return; + } + console.log("listInputMethod success"); + this.imeList = data; + }); +``` + +### listInputMethod9+ + +listInputMethod(enable: boolean): Promise<Array<InputMethodProperty>> + +Obtains a list of activated or deactivated input methods. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------- | +| enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------- | +| Promise> | Promise used to return a list of activated or deactivated input methods. | + +**Example** + +```js +imeList: Array = null +InputMethodSetting.listInputMethod(true).then((data) => { + console.info("listInputMethod success"); + this.imeList = data; +}).catch((err) => { + console.error("listInputMethod promise err: " + err); +}) +``` ### listInputMethod listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>): void -Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. +Obtains a list of installed input methods. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | | callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.| @@ -192,42 +407,48 @@ 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); +imeList: Array = null +InputMethodSetting.listInputMethod((err,data) => { + if (err) { + console.error("listInputMethod failed because: " + JSON.stringify(err)); + return; } - }); + console.log("listInputMethod success"); + this.imeList = data; + }); ``` ### listInputMethod -listInputMethod(): Array<InputMethodProperty> +listInputMethod(): Promise<Array<InputMethodProperty>> -Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. +Obtains a list of installed input methods. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** + | Type | Description | | ----------------------------------------------------------- | ---------------------- | -| Promise> | Promise used to return the list of installed input methods. | +| Promise> | Promise used to return the list of installed input methods.| **Example** ```js - var properties = InputMethodSetting.listInputMethod(); - for (var i = 0;i < properties.length; i++) { - var property = properties[i]; - console.info(property.packageName + "/" + property.methodId); - } +imeList: Array = null +InputMethodSetting.listInputMethod().then((data) => { + console.info("listInputMethod success"); + this.imeList = data; +}).catch((err) => { + console.error("listInputMethod promise err: " + err); +}) ``` ### displayOptionalInputMethod displayOptionalInputMethod(callback: AsyncCallback<void>): void -Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -240,16 +461,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono **Example** ```js - InputMethodSetting.displayOptionalInputMethod(()=>{ - console.info('displayOptionalInputMethod is called'); - }); +InputMethodSetting.displayOptionalInputMethod((err) => { + if (err) { + console.error("displayOptionalInputMethod failed because: " + JSON.stringify(err)); + return; + } + console.info("displayOptionalInputMethod success"); +}); ``` ### displayOptionalInputMethod displayOptionalInputMethod(): Promise<void> -Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. +Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -257,10 +482,14 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result. | +| Promise<void> | Promise that returns no value.| **Example** ```js - InputMethodSetting.displayOptionalInputMethod(); +InputMethodSetting.displayOptionalInputMethod().then(() => { + console.info("displayOptionalInputMethod success.(promise)"); +}).catch((err) => { + console.error("displayOptionalInputMethod promise err: " + err); +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index bb6de45ab300f0e8fe1d5143849e656869decd3f..4176338c0957632f67df2a74c73cd51a8ab1d48d 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,5 +1,7 @@ # Media Query +The **mediaquery** module provides different styles for different media types. + > **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. @@ -28,7 +30,7 @@ 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. For details, see "Syntax of Media Query Conditions" in [Media Query](../../ui/ui-ts-layout-mediaquery.md). | +| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| **Return value** | Type | Description | @@ -36,9 +38,8 @@ Sets the media query criteria and returns the corresponding listening handle. | MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.| **Example** - ```js -listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. +let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. ``` @@ -92,7 +93,7 @@ Deregisters a callback with the corresponding query condition by using the handl ```js import mediaquery from '@ohos.mediaquery' - listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. function onPortrait(mediaQueryResult) { if (mediaQueryResult.matches) { // do something here @@ -118,10 +119,9 @@ Deregisters a callback with the corresponding query condition by using the handl ### Example -```js +```ts import mediaquery from '@ohos.mediaquery' -let portraitFunc = null @Entry @Component @@ -141,7 +141,7 @@ struct MediaQueryExample { } aboutToAppear() { - portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance. + let portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance. this.listener.on('change', portraitFunc) } diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 237dfe4234e2eb9049e419bfe94d051c2aab893e..4af1fc423938baa39a4ea5771202b0013a65aaec 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -491,7 +491,7 @@ plainArray.forEach((value, index) => { [Symbol.iterator]\(): IterableIterator<[number, T]> -Obtains an iterator, each item of which is a JavaScript object. +Obtains an iterator object that contains key-value pairs, where the key is of the number type. **System capability**: SystemCapability.Utils.Lang @@ -510,7 +510,7 @@ plainArray.add(2, "sffdfhf"); // Method 1: for (let item of plainArray) { - console.log("index:" + item[0]); + console.log("key:" + item[0]); console.log("value:" + item[1]); } @@ -518,7 +518,7 @@ for (let item of plainArray) { let iter = plainArray[Symbol.iterator](); let temp = iter.next().value; while(temp != undefined) { - console.log("index:" + temp[0]); + console.log("key:" + temp[0]); console.log("value:" + temp[1]); temp = iter.next().value; } diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 971b3408c9a9fdd616fe1133ca3cab3844ee7fd1..11ec375e987ab2312a93b5233bd4ecdd049bb79d 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -21,28 +21,31 @@ Shows a toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------------- | ---- | ------- | | options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| **Example** - ```js + +```js prompt.showToast({ message: 'Message Info', duration: 2000, }); - ``` +``` + ## ShowToastOptions Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ------ | ---------------------------------------- | -| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | ## prompt.showDialog @@ -53,6 +56,7 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | --------------------------------------- | ---- | ------ | | options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| @@ -65,7 +69,7 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Example** - ```js +```js prompt.showDialog({ title: 'Title Info', message: 'Message Info', @@ -86,7 +90,7 @@ prompt.showDialog({ .catch(err => { console.info('showDialog error: ' + err); }) - ``` +``` ## prompt.showDialog @@ -96,15 +100,16 @@ Shows a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full - **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------ | | options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| | callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Example** - ```js + +```js prompt.showDialog({ title: 'showDialog Title Info', message: 'Message Info', @@ -125,7 +130,7 @@ prompt.showDialog({ } console.info('showDialog success callback, click button: ' + data.index); }); - ``` +``` ## ShowDialogOptions @@ -159,6 +164,7 @@ Shows an action menu. This API uses a callback to return the result asynchronous **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------- | | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | @@ -166,7 +172,8 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ```js + +```js prompt.showActionMenu({ title: 'Title Info', buttons: [ @@ -186,7 +193,7 @@ prompt.showActionMenu({ } console.info('showActionMenu success callback, click button: ' + data.index); }) - ``` +``` ## prompt.showActionMenu @@ -197,17 +204,20 @@ Shows an action menu. This API uses a promise to return the result synchronously **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | --------------------------------------- | ---- | ------- | | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| **Return value** + | Type | Description | | ---------------------------------------- | ------- | | Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Example** - ```js + +```js prompt.showActionMenu({ title: 'showActionMenu Title Info', buttons: [ @@ -227,7 +237,7 @@ prompt.showActionMenu({ .catch(err => { console.info('showActionMenu error: ' + err); }) - ``` +``` ## ActionMenuOptions Describes the options for showing the action menu. diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 24f01b3f40d20ae22434cba44c2a6c644d4a95fa..7db47e5bec79abe6abd5ff65457e1b6565ce0fc9 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -20,7 +20,7 @@ import reminderAgent from'@ohos.reminderAgent'; publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void -Publishes an agent-powered reminder. This API uses an asynchronous callback to return the result. +Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER @@ -49,7 +49,7 @@ Publishes an agent-powered reminder. This API uses an asynchronous callback to r publishReminder(reminderReq: ReminderRequest): Promise<number> -Publishes an agent-powered reminder. This API uses a promise callback to return the result. +Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](../reference/apis/js-apis-notification.md#notificationrequestenablenotification8). **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER @@ -435,7 +435,7 @@ Sets the package and ability that are redirected to when the reminder notificati ## MaxScreenWantAgent -Sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. +Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved. **System capability**: SystemCapability.Notification.ReminderAgent @@ -454,7 +454,7 @@ Defines the reminder to publish. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderType | ReminderType | Yes| Type of the reminder.| -| actionButton | [ActionButton?, ActionButton?] | No| Action button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| +| actionButton | [ActionButton?, ActionButton?] | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| | wantAgent | WantAgent | No| Information about the ability that is redirected to when the notification is clicked.| | maxScreenWantAgent | MaxScreenWantAgent | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| | ringDuration | number | No| Ringing duration.| diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 5fd946a50a96ae6ba4086934c749d05f89e5362e..2609d848a83392c8b0630015b2f135894fde0a61 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -183,6 +183,7 @@ Obtains state information about the current page. | Type | Description | | --------------------------- | ------- | | [RouterState](#routerstate) | Page routing state.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 94f5f3cb5e532f3e28f221addb164358589b1754..73ea5d3c915d2ba91c129ed8d7c8ed80efe8170d 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -99,7 +99,7 @@ Unsubscribes from events related to the screen state. **Example** ```js var callback = (data) => { - console.info('Unegister the callback for screen changes. Data: ' + JSON.stringify(data)) + console.info('Unregister the callback for screen changes. Data: ' + JSON.stringify(data)) }; screen.off("connect", callback); ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index af5243124408e6ad499dad801811d0a3fd2c957a..52ffdfc66d3fd0880602eccf574ec3b1b310904d 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1894,7 +1894,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000 console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); return; } - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); }); @@ -2012,7 +2012,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba ```js sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { if (err) { - console.error('SensorJsAPI--->Failed to register data, error code is: ' + err.code + ', message: ' + + console.error('SensorJsAPI--->Failed to register data, error code is:' + err.code + ', message: ' + err.message); return; } @@ -2045,7 +2045,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis ```js const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); promise.then((data) => { - console.info(' getGeomagneticDip_promise successed', data); + console.info('getGeomagneticDip_promise successed', data); }).catch((err) => { console.error("Operation failed"); }) @@ -2593,9 +2593,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | --------------------------------- | -| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field does not exist, and a value greater than **0** means the opposite.| ## MagneticFieldResponse diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index cb56fdccb85fd5aa96e161df2f86fbc1a5573b2d..5a521ffca5fcefb393551effd6b02bc69a9d64aa 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -2,7 +2,7 @@ The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities. -You can use the APIs of this module to start, terminate, connection, and disconnect abilities. +You can use the APIs of this module to start, terminate, connect, and disconnect abilities. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index a71897b34211faccfe2254e77f89dc10ff644244..b7b7e08a0a6a5a82a8813aad1f9d2010ff899a50 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,6 +1,7 @@ # Thermal Manager -> ![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. This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. @@ -42,7 +43,7 @@ Subscribes to thermal level changes. | Name | Type | Mandatory | Description | | -------- | --------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to obtain the return value.
Return value: thermal level| +| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to obtain the return value.
The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index f9e174b5147370f465e140d03aeba6b3802380a0..cf8ca596bd72517835c6bd277c0bf29ebf2b7213 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -1,5 +1,10 @@ # Timer +The **Timer** module provides basic timer capabilities. You can use the APIs of this module to execute functions at the specified time. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## setTimeout @@ -7,6 +12,8 @@ setTimeout(handler[,delay[,…args]]): number Sets a timer for the system to call a function after the timer goes off. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -23,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off. **Example** -```js -export default { - setTimeOut() { - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); + ```js + export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); + } } -} -``` + ``` ## clearTimeout @@ -40,6 +47,8 @@ clearTimeout(timeoutID: number): void Cancels the timer created via **setTimeout()**. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -48,16 +57,16 @@ Cancels the timer created via **setTimeout()**. **Example** -```js -export default { - clearTimeOut() { - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - clearTimeout(timeoutID); + ```js + export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); + } } -} -``` + ``` ## setInterval @@ -66,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -82,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i **Example** -```js -export default { - setInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); + ```js + export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + } } -} -``` + ``` ## clearInterval @@ -99,6 +110,8 @@ clearInterval(intervalID: number): void Cancels the repeating timer set via **setInterval()**. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name| Type| Mandatory| Description| @@ -107,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**. **Example** -```js -export default { - clearInterval() { - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - clearInterval(intervalID); + ```js + export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); + } } -} -``` \ No newline at end of file + ``` diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index 1cad2b9d5796f5039d62124ff9543c77d7dc48f1..ab8fc8e866ae68175f6ddabc0be83ac1f2803b5f 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1379,7 +1379,7 @@ Represents a version component. | Parameter | Type | Mandatory | Description | | --------------- | ----------------------------------- | ---- | -------- | -| componentId | number | Yes | Component ID. | +| componentId | string | Yes | Component ID. | | componentType | [ComponentType](#componenttype) | Yes | Component type. | | upgradeAction | [UpgradeAction](#upgradeaction) | Yes | Update mode. | | displayVersion | string | Yes | Display version number. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index afa1c20bcd4eace98512772fb3cd7160d23a5b92..d1ffe6f45c4a792bdfda7ad81743a3fe1b8aac51 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -123,17 +123,6 @@ Processes an asynchronous function and returns a promise version. | -------- | -------- | | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise version.| -**Example** - ```js - function aysnFun() { - return 0; - } - let newPromiseObj = util.promiseWrapper(aysnFun); - newPromiseObj().then(res => { - console.log(res); - }) - ``` - ## util.promisify9+ promisify(original: (err: Object, value: Object) => void): Function diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 76bba2f5b15c6a9da9b2f4bb4f5201f4552a9cbd..c30f11c4a06a5b80ae2f00f88a5baa8e071ffad3 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -94,11 +94,11 @@ Describes the properties of the status bar and navigation bar. | Name | Type| Readable| Writable| Description | | -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | isStatusBarLightIcon7+ | boolean | No | Yes | Whether any icon on the status bar is highlighted. | | statusBarContentColor8+ | string | No | Yes | Color of the text on the status bar. | -| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isNavigationBarLightIcon7+ | boolean | No | No | Whether any icon on the navigation bar is highlighted. | +| navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| isNavigationBarLightIcon7+ | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. | | navigationBarContentColor8+ | string | No | Yes | Color of the text on the navigation bar. | ## Orientation9+ @@ -147,11 +147,11 @@ Describes the callback for a single system bar. | Name | Type | Readable| Writable| Description | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| type | [WindowType](#windowtype) | Yes | Yes | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| -| isEnable | boolean | Yes | Yes | Whether the system bar is displayed. | -| region | [Rect](#rect) | Yes | Yes | Current position and size of the system bar. | -| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| contentColor | string | Yes | Yes | Color of the text on the system bar. | +| type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| +| isEnable | boolean | Yes | No | Whether the system bar is displayed. | +| region | [Rect](#rect) | Yes | No | Current position and size of the system bar. | +| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| contentColor | string | Yes | No | Color of the text on the system bar. | ## SystemBarTintState8+ @@ -164,7 +164,7 @@ Describes the callback for the current system bar. | Name | Type | Readable| Writable| Description | | ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- | | displayId | number | Yes | No | ID of the current physical screen. | -| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information that has been changed.| +| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | No | All system bar information that has been changed.| ## Rect7+ @@ -224,6 +224,7 @@ Describes the window properties. | isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | | isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| | isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | +| id9+ | number | Yes | No | Window ID. The default value is `0.0`. | ## ColorSpace8+ @@ -246,8 +247,8 @@ Describes the scale parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | No | Yes | Scale factor of the x-axis. The default value is `1.0`. | -| y | number | No | Yes | Scale factor of the y-axis. The default value is `1.0`. | +| x | number | No | Yes | Scale factor along the x-axis. The default value is `1.0`. | +| y | number | No | Yes | Scale factor along the y-axis. The default value is `1.0`. | | pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| | pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| @@ -1238,9 +1239,9 @@ Sets the type of this window. This API uses an asynchronous callback to return t **System API**: This is a system API. -> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > -> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1272,9 +1273,9 @@ Sets the type of this window. This API uses a promise to return the result. **System API**: This is a system API. -> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> **NOTE** > -> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1404,7 +1405,8 @@ Obtains the area where this window cannot be displayed, for example, the system **Example** ```js -let promise = windowClass.getAvoidArea(); +var type = window.AvoidAreaType.TYPE_SYSTEM; +let promise = windowClass.getAvoidArea(type); promise.then((data)=> { console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); }).catch((err)=>{ @@ -1882,7 +1884,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| **Example** @@ -1908,7 +1910,7 @@ Checks whether this window is displayed. This API uses a promise to return the r | Type | Description | | ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| +| Promise<boolean> | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| **Example** @@ -1970,9 +1972,9 @@ windowClass.off('windowSizeChange'); on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void Enables listening for changes to the area where the window cannot be displayed. -> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. +> **NOTE** > -> +> This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1996,9 +1998,9 @@ windowClass.on('systemAvoidAreaChange', (data) => { off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void Disables listening for changes to the area where the window cannot be displayed. -> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. +> **NOTE** > -> +> This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2164,7 +2166,7 @@ Subscribes to screenshot events. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| | callback | Callback<void> | Yes | Callback invoked when a screenshot event occurs. | **Example** @@ -2187,7 +2189,7 @@ Unsubscribes from screenshot events. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| | callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| **Example** @@ -2215,7 +2217,7 @@ Subscribes to click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| | callback | Callback<void>| Yes | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** @@ -2238,7 +2240,7 @@ Unsubscribes from click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| | callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** @@ -2527,7 +2529,7 @@ Sets the background color for this window. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -2555,7 +2557,7 @@ Sets the background color for this window. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| **Return value** @@ -3120,7 +3122,7 @@ let promise = windowClass.setForbidSplitMove(isForbidSplitMove); promise.then((data)=> { console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to forbidd window moving in split screen mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); }); ``` @@ -3257,8 +3259,8 @@ Sets the shadow for the window borders. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur for the borders. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| -| color | string | No | Color of the shadow. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| +| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | | offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | @@ -3331,11 +3333,12 @@ Sets the scale parameters for this window. **Example** ```js -var obj : window.ScaleOptions; -obj.x = 2.0; -obj.y = 1.0; -obj.pivotX = 0.5; -obj.pivotY = 0.5; +var obj : window.ScaleOptions = { + x : 2.0, + y : 1.0, + pivotX = 0.5; + pivotY = 0.5; +} windowClass.scale(obj); ``` @@ -3358,12 +3361,13 @@ Sets the rotation parameters for this window. **Example** ```js -var obj : window.RotateOptions; -obj.x = 1.0; -obj.y = 1.0; -obj.z = 45.0; -obj.pivotX = 0.5; -obj.pivotY = 0.5; +var obj : window.RotateOptions = { + x : 1.0, + y : 1.0, + z : 45.0, + pivotX = 0.5; + pivotY = 0.5; +} windowClass.rotate(obj); ``` @@ -3386,10 +3390,11 @@ Sets the translation parameters for this window. **Example** ```js -var obj : window.TranslateOptions; -obj.x = 100.0; -obj.y = 0.0; -obj.z = 0.0; +var obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 +} windowClass.translate(obj); ``` @@ -3421,20 +3426,23 @@ controller.animationForHidden = (context : window.TransitionContext) => { curve: Curve.EaseInOut, // Animation curve. delay: 0, // Animation delay. iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation mode. + playMode: PlayMode.Normal // Animation playback mode. + onFinish: ()=> { + context.completeTransition(true) + } }, () => { - var obj : window.TranslateOptions; - obj.x = 100.0; - obj.y = 0.0; - obj.z = 0.0; + var obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + } toWindow.translate(obj); // Set the transition animation. console.info('toWindow translate end'); } ) - context.completeTransition(true) console.info('complete transition end'); } -windowClass.showWithAnimation((err, data) => { +windowClass.hideWithAnimation((err, data) => { if (err.code) { console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); return; @@ -3915,21 +3923,23 @@ class myAbility extends Ability { Provides the context for the transition animation. -**System API**: This is a system API. +### Attributes -### toWindow9+ +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| -------- | ----------------- | ---- | ---- | ---------------- | -| toWindow | [Window](#window) | Yes | Yes | Target window to display the animation.| +| Name | Type | Readable| Writable| Description | +| --------------------- | ----------------- | ---- | ---- | ---------------- | +| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation.| ### completeTransition9+ completeTransition(isCompleted: boolean): void -Completes the transition. This API must be called after [animateTo()](../arkui-ts/ts-explicit-animation.md) is executed. +Completes the transition. This API can be called only after [animateTo()](../arkui-ts/ts-explicit-animation.md) is executed. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3951,12 +3961,13 @@ controller.animationForShown = (context : window.TransitionContext) => { curve: Curve.EaseInOut, // Animation curve. delay: 0, // Animation delay. iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation mode. + playMode: PlayMode.Normal // Animation playback mode. }, () => { - var obj : window.TranslateOptions; - obj.x = 100.0; - obj.y = 0.0; - obj.z = 0.0; + var obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + } toWindow.translate(obj); console.info('toWindow translate end'); } @@ -3970,13 +3981,13 @@ controller.animationForShown = (context : window.TransitionContext) => { Implements the transition animation controller. -**System API**: This is a system API. - ### animationForShown9+ animationForShown(context: TransitionContext): void -Customizes the animation when the window is shown. +Customizes the animation for the scenario when the window is shown. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3998,17 +4009,20 @@ controller.animationForShown = (context : window.TransitionContext) => { curve: Curve.EaseInOut, // Animation curve. delay: 0, // Animation delay. iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation mode. + playMode: PlayMode.Normal // Animation playback mode. + onFinish: ()=> { + context.completeTransition(true) + } }, () => { - var obj : window.TranslateOptions; - obj.x = 100.0; - obj.y = 0.0; - obj.z = 0.0; + var obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + } toWindow.translate(obj); console.info('toWindow translate end'); } ) - context.completeTransition(true) console.info('complete transition end'); } ``` @@ -4017,7 +4031,9 @@ controller.animationForShown = (context : window.TransitionContext) => { animationForHidden(context: TransitionContext): void -Customizes the animation when the window is hidden. +Customizes the animation for the scenario when the window is hidden. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -4039,17 +4055,20 @@ controller.animationForHidden = (context : window.TransitionContext) => { curve: Curve.EaseInOut, // Animation curve. delay: 0, // Animation delay. iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation mode. + playMode: PlayMode.Normal // Animation playback mode. + onFinish: ()=> { + context.completeTransition(true) + } }, () => { - var obj : window.TranslateOptions; - obj.x = 100.0; - obj.y = 0.0; - obj.z = 0.0; + var obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + } toWindow.translate(obj); console.info('toWindow translate end'); } ) - context.completeTransition(true) console.info('complete transition end'); } ``` diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md index a81bb5c76c64a092ea77afb14db231040adf77ac..ee3fa7397ef213d615ce3e0f71d094cb3d4fc98e 100644 --- a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -3,7 +3,7 @@ The **WindowAnimationManager** module provides APIs to listen for application st > **NOTE** > -> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > > The APIs provided by this module are system APIs. @@ -350,7 +350,7 @@ var controller = { ``` ## WindowAnimationTarget -Implements animation in a window. +Defines a window to display animation. **System capability**: SystemCapability.WindowManager.WindowManager.Core diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index e5d14db39c8473ef7a96dd382ce64fa70a57371b..067897c8c6f4d3292683d63b4288a7fc987c578c 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,9 +1,10 @@ # Worker Startup -> ![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. -A Worker thread is an independent thread running in parallel with the main thread. The thread that creates the Worker thread is referred to as a host thread. The URL file passed in during Worker creation is executed in the Worker thread. The Worker thread can process time-consuming operations, but cannot directly operate the UI. +The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. ## Modules to Import @@ -18,7 +19,7 @@ import worker from '@ohos.worker'; | Name | Type | Readable| Writable| Description | | ---------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------ | -| parentPort | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the Worker thread used to communicate with the host thread.| +| parentPort | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.| ## WorkerOptions @@ -29,13 +30,13 @@ Provides options that can be set for the **Worker** instance to create. | Name| Type | Readable| Writable| Description | | ---- | --------- | ---- | ---- | ---------------------- | -| type | "classic" | Yes | Yes | Mode in which the Worker thread executes the script.| -| name | string | Yes | Yes | Name of the Worker thread. | +| type | "classic" | Yes | Yes | Mode in which the worker thread executes the script.| +| name | string | Yes | Yes | Name of the worker thread. | ## Worker -Before using the following APIs, you must construct a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). +Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). ### constructor @@ -70,7 +71,7 @@ const workerInstance = new worker.Worker("workers/worker.js", {name:"first worke postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the Worker thread. The data is transferred using the structured clone algorithm. +Sends a message to the worker thread. The message data is transferred using the structured clone algorithm. **System capability**: SystemCapability.Utils.Lang @@ -78,7 +79,7 @@ Sends a message to the Worker thread. The data is transferred using the structur | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Data to be sent to the Worker thread. | +| message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| **Example** @@ -99,7 +100,7 @@ workerInstance.postMessage(buffer, [buffer]); on(type: string, listener: EventListener): void -Adds an event listener for the Worker instance. +Adds an event listener for the worker instance. **System capability**: SystemCapability.Utils.Lang @@ -124,7 +125,7 @@ workerInstance.on("alert", (e)=>{ once(type: string, listener: EventListener): void -Adds an event listener for the Worker thread and removes the event listener after it is invoked once. +Adds an event listener for the worker thread and removes the event listener after it is invoked once. **System capability**: SystemCapability.Utils.Lang @@ -149,7 +150,7 @@ workerInstance.once("alert", (e)=>{ off(type: string, listener?: EventListener): void -Removes an event listener for the Worker thread. +Removes an event listener for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -172,7 +173,7 @@ workerInstance.off("alert"); terminate(): void -Terminates the Worker thread to stop it from receiving messages. +Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang @@ -188,7 +189,7 @@ workerInstance.terminate() onexit?: (code: number) => void -Defines the event handler to be called when the Worker thread exits. The handler is executed in the host thread. +Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread. **System capability**: SystemCapability.Utils.Lang @@ -196,7 +197,7 @@ Defines the event handler to be called when the Worker thread exits. The handler | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the Worker thread exit state.| +| code | number | No | Code indicating the worker thread exit state.| **Example** @@ -212,7 +213,7 @@ workerInstance.onexit = function(e) { onerror?: (err: ErrorEvent) => void -Defines the event handler to be called when an exception occurs during Worker execution. The event handler is executed in the host thread. +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. **System capability**: SystemCapability.Utils.Lang @@ -236,7 +237,7 @@ workerInstance.onerror = function(e) { onmessage?: (event: MessageEvent) => void -Defines the event handler to be called when the host thread receives a message created by itself and sent by the Worker thread through the **parentPort.postMessage**. The event handler is executed in the host thread. +Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. **System capability**: SystemCapability.Utils.Lang @@ -260,7 +261,7 @@ workerInstance.onmessage = function(e) { onmessageerror?: (event: MessageEvent) => void -Defines the event handler to be called when the Worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. +Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. **System capability**: SystemCapability.Utils.Lang @@ -287,7 +288,7 @@ workerInstance.onmessageerror= function(e) { addEventListener(type: string, listener: EventListener): void -Adds an event listener for the Worker thread. +Adds an event listener for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -312,7 +313,7 @@ workerInstance.addEventListener("alert", (e)=>{ removeEventListener(type: string, callback?: EventListener): void -Removes an event listener for the Worker thread. +Removes an event listener for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -335,7 +336,7 @@ workerInstance.removeEventListener("alert") dispatchEvent(event: Event): boolean -Dispatches the event defined for the Worker thread. +Dispatches the event defined for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -363,7 +364,7 @@ workerInstance.dispatchEvent({type:"alert"}) removeAllListener(): void -Removes all event listeners for the Worker thread. +Removes all event listeners for the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -377,14 +378,14 @@ workerInstance.removeAllListener({type:"alert"}) ## DedicatedWorkerGlobalScope -Implements communication between the Worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the Worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#workerglobalscope). +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#workerglobalscope). ### postMessage postMessage(message: Object, options?: PostMessageOptions): void -Sends a message to the host thread from the Worker thread. +Sends a message to the host thread from the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -392,7 +393,7 @@ Sends a message to the host thread from the Worker thread. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| message | Object | Yes | Data to be sent to the Worker thread. | +| message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| **Example** @@ -421,7 +422,7 @@ parentPort.onmessage = function(e){ close(): void -Terminates the Worker thread to stop it from receiving messages. +Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang @@ -447,7 +448,7 @@ parentPort.onmessage = function(e) { onmessage?: (event: MessageEvent) => void -Defines the event handler to be called when the Worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the Worker thread. +Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -480,7 +481,7 @@ parentPort.onmessage = function(e) { onmessageerror?: (event: MessageEvent) => void -Defines the event handler to be called when the Worker thread receives a message that cannot be deserialized. The event handler is executed in the Worker thread. +Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. **System capability**: SystemCapability.Utils.Lang @@ -566,7 +567,7 @@ workerInstance.addEventListener("alert", (e)=>{ ## ErrorEvent -Provides detailed information about the exception occurred during Worker execution. The **ErrorEvent** class inherits from [Event](#event). +Provides detailed information about the exception that occurs during worker execution. The **ErrorEvent** class inherits from [Event](#event). **System capability**: SystemCapability.Utils.Lang @@ -574,14 +575,14 @@ Provides detailed information about the exception occurred during Worker executi | -------- | -------- | ---- | ---- | -------------------- | | message | string | Yes | No | Information about the exception.| | filename | string | Yes | No | File where the exception is located.| -| lineno | number | Yes | No | Number of the line where the exception is located. | -| colno | number | Yes | No | Number of the column where the exception is located. | +| lineno | number | Yes | No | Serial number of the line where the exception is located. | +| colno | number | Yes | No | Serial number of the column where the exception is located. | | error | Object | Yes | No | Type of the exception. | ## MessageEvent -Holds the data transferred between Worker threads. +Holds the data transferred between worker threads. **System capability**: SystemCapability.Utils.Lang @@ -592,7 +593,7 @@ Holds the data transferred between Worker threads. ## WorkerGlobalScope -Defines the running environment of the Worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). +Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). ### Attributes @@ -601,14 +602,14 @@ Defines the running environment of the Worker thread. The **WorkerGlobalScope** | Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | --------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| -| self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | WorkerGlobalScope. | +| self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | **WorkerGlobalScope**. | ### onerror onerror?: (ev: ErrorEvent) => void -Defines the event handler to be called when an exception occurs during Worker execution. The event handler is executed in the Worker thread. +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 21e43edc10b5e4fd5acf567ceabb822f26935ade..7544a074dd9261a349698e813ac1b82b77a6ab66 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -344,15 +344,22 @@ for (var i = 0; i < strLen; ++i) { } var that = new xml.XmlPullParser(arrayBuffer); var arrTag = {}; -arrTag[0] = '132'; -var i = 1; +var str = ""; +var i = 0; function func(key, value){ arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + str += arrTag[i]; i++; - return true; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. } var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:1key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:3 value:1key:1 value:0 +// Note: +// key indicates the event type, and value indicates the parsing depth. You can learn the specific parsed event based on EVENTTYPE. In this example, key: value means: +// 0(START_DOCUMENT):0 (START_DOCUMENT is being parsed, and the depth is 0), 2(START_TAG):1 (START_TAG is being parsed, and the depth is 1), 10(WHITESPACE):1 (WHITESPACE is being parsed, and the depth is 1), 2(START_TAG):2 (START_TAG is being parsed, and the depth is 2), ... ``` diff --git a/en/application-dev/reference/arkui-js/js-components-custom-lifecycle.md b/en/application-dev/reference/arkui-js/js-components-custom-lifecycle.md index fcadfdd427267b239e3f8660a7eca2b3bece1119..efaf962b6d2be3e3cc36afda214a5cbcff31ec40 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-lifecycle.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-lifecycle.md @@ -1,97 +1,34 @@ -# Lifecycle Definition +# Lifecycle Definition ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. -We provide a range of lifecycle callbacks for custom components, including **onInit**, **onAttached**, **onDetached**, **onLayoutReady**, **onDestroy**, **onPageShow**, and **onPageHide**. You can use these callbacks to manage the internal logic of your custom components. The following describes the times when the lifecycle callbacks are invoked. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Attribute

-

Type

-

Description

-

Called When

-

onInit

-

Function

-

Custom component initialization

-

Triggered once, when a custom component is created.

-

onAttached

-

Function

-

Custom component loading

-

Triggered when a custom component is added to the <Page> component tree. When this callback is triggered, related data can be displayed during the lifecycle in scenarios such as image loading and animation playback.

-

onLayoutReady

-

Function

-

Component layout completion

-

Triggered when layout calculation, including content size and position adjustment, is complete for a custom component.

-

onDetached

-

Function

-

Custom component removal

-

Triggered when a custom component is removed. It is usually used to stop animation or asynchronous logic execution.

-

onDestroy

-

Function

-

Custom component destruction

-

Triggered when a custom component is destroyed. It is usually used to release resources.

-

onPageShow

-

Function

-

Page display of a custom component

-

Triggered when the page where a custom component is located is displayed.

-

onPageHide

-

Function

-

Page hiding of a custom component

-

Triggered when the page where a custom component is located is hidden.

-
+We provide a range of lifecycle callbacks for custom components, including **onInit**, **onAttached**, **onDetached**, **onLayoutReady**, **onDestroy**, **onShow**, and **onHide**. You can use these callbacks to manage the internal logic of your custom components. The following describes the times when the lifecycle callbacks are invoked. -## Example -``` +| Attribute | Type | Description | Invoked When | +| ------------- | -------- | ------------------ | ------------------------------------------------------------ | +| onInit | Function | Custom component initialization | The custom component is created. This callback is invoked once.| +| onAttached | Function | Custom component loading | The custom component is added to the **\** component tree. When this callback is invoked, related data can be displayed during the lifecycle in scenarios such as image loading and animation playback.| +| onLayoutReady | Function | Component layout completion| Layout calculation, including content size and position adjustment, is complete for the custom component.| +| onDetached | Function | Custom component removal | The custom component is removed. It is usually used to stop animation or asynchronous logic execution.| +| onDestroy | Function | Custom component destruction | The custom component is destroyed. It is usually used to release resources. | +| onShow | Function | Page display of a custom component| The page where the custom component is located is displayed. | +| onHide | Function | Page hiding of a custom component| The page where the custom component is located is hidden. | + + +## Example + +```html
{{value}}
``` -``` +```js //comp.js export default { data: { @@ -106,12 +43,11 @@ export default { onDetached() { this.value = "" }, - onPageShow() { + onShow() { console.log ("Page displayed.") }, - onPageHide() { + onHide() { console.log ("Page hidden.") } } ``` - diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index ee169162cdeeeeb0be3c4c717d74d6bb231b74ff..4ed91abbcccddf2c639302c6f6524e257303e6e8 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -38,6 +38,7 @@ - [Component ID](ts-universal-attributes-component-id.md) - [Touch Target](ts-universal-attributes-touch-target.md) - [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) + - [Background Blur](ts-universal-attributes-backgroundBlurStyle.md) - Gesture Processing - [Gesture Binding Methods](ts-gesture-settings.md) - Basic Gestures diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif new file mode 100644 index 0000000000000000000000000000000000000000..24702d37d233b9f10a83e4e36b8c8ff23393014f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_000000111864201.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104404.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104404.png new file mode 100644 index 0000000000000000000000000000000000000000..e370a44cf043fc34bd8891f57faad2cd2ca05707 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174104404.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264376.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264376.png new file mode 100644 index 0000000000000000000000000000000000000000..dfcb0c5e259b3f8d7375c21712249c1e847edd67 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174264376.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422914.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422914.png new file mode 100644 index 0000000000000000000000000000000000000000..bc28f5056c679e189543c8ad6fba67fb56db7655 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422914.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582864.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582864.png new file mode 100644 index 0000000000000000000000000000000000000000..b54dbc2391d1a8f16312dd02dc3d65a35ea2626f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582864.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582866.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582866.png new file mode 100644 index 0000000000000000000000000000000000000000..56d32d4cd371c5374b133cb81c9c077aaf7b110d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174582866.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662661.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662661.png new file mode 100644 index 0000000000000000000000000000000000000000..9c43caf5fdfd466eafc37b793f509a6bde2b885d Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662661.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662663.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662663.png new file mode 100644 index 0000000000000000000000000000000000000000..5c5e360f249a2002ba68ad9b94bd7f66f5d6aab1 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662663.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662665.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662665.png new file mode 100644 index 0000000000000000000000000000000000000000..309d1c46f8bc396df5eaed381a5ffa2f0389d602 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219662665.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744201.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744201.png new file mode 100644 index 0000000000000000000000000000000000000000..0d22570503febc7a7dcba0d1e870f49f32fe489a Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219744201.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864153.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864153.png new file mode 100644 index 0000000000000000000000000000000000000000..58293d5e874f2aa36ecaf7282ca9e4736318092f Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001219864153.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_background_blur_style.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_background_blur_style.png new file mode 100644 index 0000000000000000000000000000000000000000..e9a7b0e3baa6d48739c2a3cfbc7b5b46600f9c70 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_background_blur_style.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/loadingProgress.png b/en/application-dev/reference/arkui-ts/figures/loadingProgress.png deleted file mode 100644 index afc52b1a469c858e3029282e193b684114803db0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/loadingProgress.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/search.png b/en/application-dev/reference/arkui-ts/figures/search.png new file mode 100644 index 0000000000000000000000000000000000000000..fddf98d7104f3bd8a370b5be86da322834ff0180 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/search.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md index de967be1f6e0ec184ce0d6ba553b0fe15a7ea5dd..e6c2c03cee6bc7d7daa9511fce2ee4a5ef0e0c4a 100644 --- a/en/application-dev/reference/arkui-ts/ts-animatorproperty.md +++ b/en/application-dev/reference/arkui-ts/ts-animatorproperty.md @@ -1,44 +1,31 @@ -# AnimatorProperty +# Property Animator +You can create a property animator to animate the universal attributes of a component. > **NOTE** > -> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +| API | Description | +| ------------------------------ | ------------------------------------------------------------ | +| animation(value: AnimateParam) | Applies a property animator to this component to control the transition of the component from one state to another.| -When the universal attributes of a component change, you can create an **AnimatorProperty** for gradient to improve user experience. +## AnimateParam +- Attributes -| Name | Type | Default Value | Description | -| -------- | -------- | -------- | -------- | -| duration | number | 1000 | Animation duration, in ms. The default duration is 1000 ms. | -| curve | Curve | Curve.Linear | Animation curve. The default curve is linear. | -| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | -| iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | -| playMode | [PlayMode](ts-appendix-enums.md#playmode-enums) | PlayMode.Normal | Playback mode. By default, the animation is played from the beginning after the playback is complete. | - -- Curve enums - | Name | Description | - | -------- | -------- | - | Linear | The animation speed keeps unchanged. | - | Ease | The animation starts at a low speed and then accelerates. It slows down before the animation ends. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used. | - | EaseIn | The animation starts at a low speed. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. | - | EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. | - | EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used. | - | FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). | - | LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). | - | FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0). | - | ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). | - | Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). | - | Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). | - | Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). | - | Friction | Damping curve. The cubic-bezier curve (0.2, 0.0, 0.2, 1.0) is used. | +| Name | Type | Default Value | Description | +| ---------- | ---------------------------------------- | --------------- | ----------------------- | +| duration | number | 1000 | Animation duration, in ms. The default duration is 1000 ms. | +| curve | [Curve](ts-appendix-enums.md#curve) | Curve.Linear | Animation curve. The default curve is linear. | +| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | +| iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | +| playMode | [PlayMode](ts-appendix-enums.md#playmode) | PlayMode.Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.| ## Example - ```ts // xxx.ets @Entry @@ -67,8 +54,8 @@ struct AttrAnimationExample { curve: Curve.EaseOut, // Animation curve delay: 500, // Animation delay iterations: 1, // Number of playback times - playMode: PlayMode.Normal // Animation mode - }) // Animation configuration for the width and height attributes of the Button component + playMode: PlayMode.Normal // Animation playback mode + }) // Animation configuration for the width and height attributes of the