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/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-dataability.md b/en/application-dev/ability/fa-dataability.md index d291124c123f0f8e30ef344179a8891c67972b81..36eda5d9210681106a9476bdc87de28f4d06406c 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -23,12 +23,10 @@ Example URIs: - Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10* - Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10* - > **NOTE** -> +> > In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. - ## Available APIs **Table 1** Data ability lifecycle APIs @@ -140,7 +138,7 @@ Import the basic dependency packages and obtain the URI string for communicating The basic dependency packages include: - @ohos.ability.featureAbility -- @ohos.data.dataability +- @ohos.data.dataAbility - @ohos.data.rdb #### Data Ability API Development @@ -154,7 +152,7 @@ The basic dependency packages include: import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_rdb from '@ohos.data.rdb' - + var urivar = "dataability:///com.ix.DataAbility" var DAHelper = featureAbility.acquireDataAbilityHelper( urivar 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/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-continuation.md b/en/application-dev/ability/stage-ability-continuation.md index 0695a3bd491785d414d75be6520d513229b0bcbc..6945f49db8ef05109452fc1b3dcad3dc1e5ddeca 100644 --- a/en/application-dev/ability/stage-ability-continuation.md +++ b/en/application-dev/ability/stage-ability-continuation.md @@ -12,8 +12,9 @@ The following table lists the APIs used for ability continuation. For details ab |API| Description| |:------ | :------| -| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.| -| onCreate(want: Want, param : LaunchParam): void | Called by the target to restore the data and UI page.| +| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation. The return value indicates whether the continuation request is accepted. The value **AGREE** means that the continuation request is accepted, **REJECT** means that the continuation request is rejected, and **MISMATCH** means a version mismatch.| +| onCreate(want: Want, param: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the multi-instance ability scenario.| +| onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; | Called by the target to restore the data and UI page in the singleton ability scenario.| @@ -21,20 +22,30 @@ The following table lists the APIs used for ability continuation. For details ab ![continuation_dev](figures/continuation-info.png) -In effect, ability continuation is a cross-device ability startup that carries data. When the continuation is triggered, device A calls back **onContinue()** of the application. You must save the current data in this API. Then, device A initiates a cross-device ability startup on device B and transmits the data to device B. Device B calls back **onCreate()**. You must restore the transmitted data in this API. +In effect, ability continuation is a cross-device ability startup that carries data. When a continuation action is initiated, the system on device A calls back **onContinue()** of the application. You must implement storage of the current data in this API. Then, the system initiates a cross-device ability startup on device B and transmits the data to device B. The system on device B calls back **onCreate()** or **onNewWant()**. You must implement restoration of the transmitted data in this API. ## How to Develop +The code snippets provided below are all from [Sample](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/samples/continuationManualTestSuite). + ### Application Continuation -1. Configuration +1. Modify the configuration file. - Configure the application to support ability continuation. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on another device. ```javascript - "continuable": true + { + "module": { + "abilities": [ + { + "continuable": true, + } + ] + } + } ``` @@ -42,30 +53,53 @@ In effect, ability continuation is a cross-device ability startup that carries d - Configure the application startup type. - Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application. + If **launchType** is set to **standard** in the **module.json5** file, the application is of the multi-instance launch type. During ability continuation, regardless of whether the application is already open, the target starts the application and restores the UI page. If **launchType** is set to **singleton**, the application is of the singleton launch type. If the application is already open, the target clears the existing page stack and restores the UI page. For more information, see "Launch Type" in [Ability Development](./stage-ability.md). + + Configure a multi-instance application as follows: ```javascript - "launchType": "standard" + { + "module": { + "abilities": [ + { + "launchType": "standard", + } + ] + } + } ``` - - - + Configure a singleton application as follows or retain the default settings of **launchType**: + + ```javascript + { + "module": { + "abilities": [ + { + "launchType": "singleton", + } + ] + } + } + ``` + + + - Apply for the distributed permissions. Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. - + ```javascript "requestPermissions": [ { "name": "ohos.permission.DISTRIBUTED_DATASYNC" }, ``` - + This permission must be granted by the user in a dialog box when the application is started for the first time. To enable the application to display a dialog box to ask for the permission, add the following code to **onWindowStageCreate** of the **Ability** class: - + ```javascript requestPermissions = async () => { let permissions: Array = [ @@ -102,14 +136,13 @@ In effect, ability continuation is a cross-device ability startup that carries d } } ``` - - + 2. Implement the **onContinue()** API. - The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE(0)** to accept the continuation request. If an error code is returned, the request is rejected. If this API is not implemented, the system rejects the continuation request by default. + The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return either **OnContinueResult.AGREE(0)** to accept the continuation request or an error code to reject the request. If this API is not implemented, the system rejects the continuation request by default. Modules to import: @@ -119,22 +152,25 @@ In effect, ability continuation is a cross-device ability startup that carries d ``` To implement ability continuation, you must implement this API and have the value **AGREE** returned. - + + You can obtain the target device ID (identified by the key **targetDevice**) and the version number (identified by the key **version**) of the application installed on the target device from the **wantParam** parameter of this API. The version number can be used for compatibility check. If the current application version is incompatible with that on the target device, **OnContinueResult.MISMATCH** can be returned to reject the continuation request. + Example - + ```javascript - onContinue(wantParam : {[key: string]: any}) { - Logger.info("onContinue using distributedObject") - // Set the user input data into want params. - wantParam["input"] = AppStorage.Get('ContinueInput'); - Logger.info(`onContinue input = ${wantParam["input"]}`); - return AbilityConstant.OnContinueResult.AGREE - } + onContinue(wantParam : {[key: string]: any}) { + Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + let workInput = AppStorage.Get('ContinueWork'); + // Set the user input data into wantParam. + wantParam["work"] = workInput // set user input data into want params + Logger.info(`onContinue input = ${wantParam["input"]}`); + return AbilityConstant.OnContinueResult.AGREE + } ``` - + -3. Implement the continuation logic in the **onCreate()** API. +3. Implement the continuation logic in the **onCreate()** or **onNewWant()** API. The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. @@ -142,22 +178,34 @@ In effect, ability continuation is a cross-device ability startup that carries d After data restore is complete, call **restoreWindowStage** to trigger page restoration. - Example + + You can also use **want.parameters.version** in the **want** parameter to obtain the application version number of the initiator. + + Example + ```javascript - onCreate(want, launchParam) { - Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) - globalThis.abilityWant = want; - if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { - let input = want.parameters.input // Obtain user data from want params. - AppStorage.SetOrCreate('ContinueInput', input) - Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - - this.contentStorage = new ContentStorage(); - this.context.restoreWindowStage(this.contentStorage); - } - } + import Ability from '@ohos.application.Ability'; + import distributedObject from '@ohos.data.distributedDataObject'; + + export default class MainAbility extends Ability { + storage : LocalStorag; + + onCreate(want, launchParam) { + Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) + if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { + // Obtain the user data from the want parameter. + let workInput = want.parameters.work + Logger.info(`work input ${workInput}`) + AppStorage.SetOrCreate('ContinueWork', workInput) + + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); + } + } + } ``` +For a singleton ability, use **onNewWant()** to achieve the same implementation. @@ -169,28 +217,38 @@ Distributed objects allow cross-device data synchronization like local variables In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. -- In **onContinue()**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**. +- In **onContinue()**, the initiator saves the data to be migrated to the distributed object, calls the **save()** API to save the data and synchronize the data to the target device, sets the session ID, and sends the session ID to the target device through **wantParam**. ```javascript import Ability from '@ohos.application.Ability'; import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:undefined}); + var g_object = distributedObject.createDistributedObject({data:undefined}); export default class MainAbility extends Ability { - contentStorage : ContentStorage sessionId : string; onContinue(wantParam : {[key: string]: any}) { - Logger.info("onContinue using distributedObject") - this.sessionId = distributedObject.genSessionId(); - // Set the session ID for the distributed data object. - g_object.setSessionId(this.sessionId); - g_object.name = "Amy"; - // Set the session ID into the want parameter. - wantParam["session"] = this.sessionId; - return AbilityConstant.OnContinueResult.AGREE - } + Logger.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) + + if (g_object.__sessionId === undefined) { + this.sessionId = distributedObject.genSessionId() + Logger.info(`onContinue generate new sessionId`) + } + else { + this.sessionId = g_object.__sessionId; + } + + wantParam["session"] = this.sessionId + g_object.data = AppStorage.Get('ContinueStudy'); + Logger.info(`onContinue sessionId = ${this.sessionId}, name = ${g_object.data}`) + g_object.setSessionId(this.sessionId); + g_object.save(wantParam.targetDevice, (result, data)=>{ + Logger.info("save callback"); + Logger.info("save sessionId " + data.sessionId); + Logger.info("save version " + data.version); + Logger.info("save deviceId " + data.deviceId); + }); ``` @@ -201,15 +259,11 @@ In the ability continuation scenario, the distributed data object is used to syn import Ability from '@ohos.application.Ability'; import distributedObject from '@ohos.data.distributedDataObject'; - var g_object = distributedObject.createDistributedObject({name:undefined}); + var g_object = distributedObject.createDistributedObject({data:undefined}); export default class MainAbility extends Ability { - contentStorage : ContentStorage - sessionId : string; + storage : LocalStorag; - statusCallback(sessionId, networkid, status) { - Logger.info(`continuation object status change, sessionId: ${sessionId}, status: ${status}, g_object.name: ${g_object.name}`) - } onCreate(want, launchParam) { Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) @@ -218,13 +272,40 @@ In the ability continuation scenario, the distributed data object is used to syn this.sessionId = want.parameters.session Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) - g_object.on("status", this.statusCallback); - // Set the session ID for data synchronization. - g_object.setSessionId(this.sessionId); + // Before fetching data from the remote device, reset g_object.data to undefined. + g_object.data = undefined; + // Set the session ID, so the target will fetch data from the remote device. + g_object.setSessionId(this.sessionId); - this.contentStorage = new ContentStorage(); - this.context.restoreWindowStage(this.contentStorage); + AppStorage.SetOrCreate('ContinueStudy', g_object.data) + this.storage = new LocalStorage(); + this.context.restoreWindowStage(this.storage); } + } } ``` + + + +### More Information + +1. Timeout + + - If the application to be continued is not installed on the target device, the system checks whether the application can be installed on it and waits for a response for 4 seconds. If no response is received within 4 seconds, the caller receives a timeout error code, which means that the application cannot be installed on the target device. If the application can be installed, the system prompts the consumer to install the application on the target device. The consumer can initiate the continuation again after the installation. + - If the application to be continued has been installed on the target device, the system waits for a response to the continuation request for 20 seconds. If no response is received within 20 seconds, the caller receives a timeout error code, which means that the continuation fails. + +2. By default, the system supports page stack information migration, which means that the page stack of the initiator will be automatically migrated to the target device. No adaptation is required. + + + +### Restrictions + +1. The continuation must be performed between the same ability, which means the same bundle name, module name, and ability name. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). +2. Currently, the application can only implement the continuation capability. The continuation action must be initiated by the system. + + + +### Best Practice + + For better user experience, you are advised to use the **wantParam** parameter to transmit data smaller than 100 KB and use distributed objects to transmit data larger than 100 KB. diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index e1d67a295b673453d7340fb20a40c81d8c7a7855..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": { @@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 2** Ability APIs + |API|Description| |:------|:------| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| @@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme ``` import AbilityStage from "@ohos.application.AbilityStage" ``` -2. Implement the `AbilityStage` class. +2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. ```ts export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -70,9 +71,9 @@ To create Page abilities for an application in the stage model, you must impleme ```js import Ability from '@ohos.application.Ability' ``` -4. Implement the lifecycle callbacks of the `Ability` class. +4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**. - In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). + In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/application-window-stage.md). ```ts export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -86,8 +87,8 @@ To create Page abilities for an application in the stage model, you must impleme onWindowStageCreate(windowStage) { console.log("MainAbility onWindowStageCreate") - windowStage.loadContent("pages/index").then((data) => { - console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) + windowStage.loadContent("pages/index").then(() => { + console.log("MainAbility load content succeed") }).catch((error) => { console.error("MainAbility load content failed with error: " + JSON.stringify(error)) }) @@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme } ``` ### Obtaining AbilityStage and Ability Configurations -Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: +Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. + +The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: + ```ts import AbilityStage from "@ohos.application.AbilityStage" export default class MyAbilityStage extends AbilityStage { @@ -140,14 +144,14 @@ export default class MainAbility extends Ability { console.log("MainAbility ability name" + abilityInfo.name) let config = this.context.config - console.log("MyAbilityStage config language" + config.language) + console.log("MainAbility config language" + config.language) } } ``` ### Requesting Permissions -If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the 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": [ { @@ -227,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)) }) @@ -244,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/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 15f38e97a75585520cf60534d03a4c1812001716..da5bea318e2b60da5641b9cf01ee73c926802c16 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th console.log("on close") }); - // Bind the IP address and port number. + // Bind the local IP address and port number. let bindAddress = { address: '192.168.xx.xx', port: 1234, // Bound port, for example, 1234. diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 251c33fbc54aadba8aa07b92f0292ab86f322d70..c8cb5c503329f6dc49c66fe457eb0aa8e6debf78 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -1,5 +1,5 @@ # DataShare Development -The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device. ## Available APIs @@ -29,10 +29,10 @@ For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare ## When to Use -**DataShare** can be divided into the following: +There are two roles in **DataShare**. -- Data provider: Implement functions of adding, deleting, modifying, and querying data, and opening files, and share data. -- Data consumer: Access the data provided by the provider using **DataShareHelper**. +- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. +- Data consumer: accesses the data provided by the provider using **DataShareHelper**. Examples are given below. @@ -47,7 +47,7 @@ Examples are given below. import dataSharePredicates from '@ohos.data.dataSharePredicates' ``` -2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the query() API. +2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API. 3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. @@ -107,9 +107,9 @@ Examples are given below. | Field| Description | | ------------ | ------------------------------------------------------------ | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | - | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **Datashare** template.| - | "uri" | URI used for communication. It is the unique identifier for the client to connect to the server. | - | "visible" | Whether it is visible to other applications. Communication with other applications is allowed only when the value is **true**.| + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.| + | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. | + | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| **module.json5 example** @@ -129,7 +129,7 @@ Examples are given below. ### Data Consumer Application Development -1. Import basic dependencies. +1. Import the dependencies. ```ts import Ability from '@ohos.application.Ability' @@ -175,7 +175,7 @@ Examples are given below. dsHelper.insert(dseUri, valuesBucket, (err,data) => { console.log("dsHelper insert result: " + data); }); - // Delete the specified data. + // Delete data. dsHelper.delete(dseUri, da, (err,data) => { console.log("dsHelper delete result: " + data); }); diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md index 857e9fa4205cd0545803643af1515da485b83d8a..f603c4dd54840118471cba6c344de58121577d57 100644 --- a/en/application-dev/database/database-datashare-overview.md +++ b/en/application-dev/database/database-datashare-overview.md @@ -2,9 +2,9 @@ ## Introduction -The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device. -**DataShare** is used in application scenarios, such as contacts, short message service (SMS), and media gallery. However, not all data, such as accounts and passwords, can be accessed by other applications. Some data, such as SMS messages, can only be queried by other applications. **DataShare** provides a secure data sharing mechanism for applications. +Data needs to be shared in a wealth of scenarios. For example, contacts, short message service (SMS), and media gallery always needs to be shared. However, certain data, such as accounts and passwords, cannot be shared. Some data, such as SMS messages, can be queried but not modified by other applications. **DataShare** provides a secure data sharing mechanism for applications in a variety of scenarios. The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty. @@ -45,7 +45,7 @@ Before you get started, familiarize yourself with the following concepts: - The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data. - The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage. -- The **ResultSet** module is implemented through shared memory. Share memory stores the result sets, and interfaces are provided to traverse result sets. +- The **ResultSet** module is implemented through shared memory. Shared memory stores the result sets, and interfaces are provided to traverse result sets. ## Constraints diff --git a/en/application-dev/database/database-mdds-overview.md b/en/application-dev/database/database-mdds-overview.md index 2262558e38e892854b4de12cf124a88569cabf84..26efa7491805e871017db3593f5fa50d947717f5 100644 --- a/en/application-dev/database/database-mdds-overview.md +++ b/en/application-dev/database/database-mdds-overview.md @@ -1,8 +1,12 @@ -# Distributed Data Service Overview +# Distributed Data Service Overview -The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. +The distributed data service (DDS) implements distributed database collaboration across devices for applications. -## Basic Concepts +Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. + +You do not need to care about the implementation of the database locking mechanism. + +## Basic Concepts - **KV data model** @@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. -## Working Principles +## Working Principles The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: @@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ![](figures/en-us_image_0000001183386164.png) -## Constraints +## Constraints - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The KV data model specifications supported by the DDS are as follows: diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index b65916cdd157419ef44b821c423a33ce272f9da0..fdb69297523057f5530ef2f885fbe3e0b5cbf5cf 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -2,45 +2,48 @@ > **NOTE** > -> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. +> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. ## When to Use -Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. +Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files. -## Available APIs +Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can call the **Preferences** APIs to manage data. -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md). +## Available APIs -### Creating a Preferences Instance +The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. -Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance. +The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. -**Table 1** API for creating a **Preferences** instance +For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md). -| Package | API | Description | -| ----------------- | ------------------------------------------- | ------------------------------------------- | -| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\ | Obtains a **Preferences** instance for data operations.| +### Obtaining a **Preferences** Instance -### Writing Data +Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance. -Call the **put()** method to add or modify data in a **Preferences** instance. +**Table 1** API for obtaining a **Preferences** instance -**Table 2** API for writing data +| Package | API | Description | +| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\ | Obtains a **Preferences** instance.| -| Class | API | Description | -| ------- | -------------------------------------------------- | ----------------------------------------------- | -| Preferences | put(key: string, value: ValueType): Promise\ | Writes data with the value type of number, string, boolean, Array\, Array\, or Array\.| +### Accessing Data -### Reading Data +Call the **put()** method to add or modify data in a **Preferences** instance. Call the **get()** method to read data from a **Preferences** instance. -**Table 3** API for reading data +Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance. + +**Table 2** APIs for accessing **Preferences** data + +| Class | API | Description | +| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ | +| Preferences | put(key: string, value: ValueType): Promise\ | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| Preferences | get(key: string, defValue: ValueType): Promise\ | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| Preferences | getAll(): Promise | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. | -| Class | API | Description | -| ------- | ---------------------------------------------------------- | ----------------------------------------------- | -| Preferences | get(key: string, defValue: ValueType): Promise\ | Obtains data with the value type of number, string, boolean, Array\, Array\, or Array\.| ### Storing Data Persistently @@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p **Table 4** API for data persistence -| Class | API | Description | -| ------- | ----------------------- | --------------------------------------- | -| Preferences | flush(): Promise\ | Writes data from the **Preferences** instance back to its file through an asynchronous thread.| +| Class | API | Description | +| ----------- | ----------------------- | ------------------------------------------- | +| Preferences | flush(): Promise\ | Flushes data from the **Preferences** instance to its file through an asynchronous thread.| ### Observing Data Changes -You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data. +You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data. **Table 5** APIs for observing **Preferences** changes -| Class | API | Description | -| ------- | ------------------------------------------------------------ | -------------- | +| Class | API | Description | +| ----------- | ------------------------------------------------------------ | -------------- | | Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.| | Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. | @@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file. **Table 6** APIs for deleting **Preferences** -| Package | API | Description | -| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | -| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| -| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\; | Removes a **Preferences** instance from the memory to release memory. +| Package | API | Description | +| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\ | Deletes a **Preferences** instance from the memory and its files from the device.| +| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\ | Removes a **Preferences** instance from the memory to release memory. | ## How to Develop 1. Import @ohos.data.preferences and related modules to the development environment. ```js - import data_preferences from '@ohos.data.preferences' + import data_preferences from '@ohos.data.preferences'; ``` -2. Create a **Preferences** instance. +2. Obtain a **Preferences** instance. Read the specified file and load its data to the **Preferences** instance for data operations. ```js - let promise = data_preferences.getPreferences(this.context, 'mystore') + let promise = data_preferences.getPreferences(this.context, 'mystore'); ``` 3. Write data. - Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance. + Use the **preferences.put()** method to write data to the **Preferences** instance. ```js promise.then((preferences) => { - let putPromise = preferences.put('startup', 'auto') + let putPromise = preferences.put('startup', 'auto'); putPromise.then(() => { - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to put the value of startup with err: " + err) + console.info("Failed to put the value of 'startup'. Cause: " + err); }) }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences."); }) ``` 4. Read data. - Use the **get()** method of the **Preferences** class to read data. + Use the **preferences.get()** method to read data. ```js promise.then((preferences) => { - let getPromise = preferences.get('startup', 'default') + let getPromise = preferences.get('startup', 'default'); getPromise.then((value) => { - console.info("The value of startup is " + value) + console.info("The value of 'startup' is " + value); }).catch((err) => { - console.info("Failed to get the value of startup with err: " + err) + console.info("Failed to get the value of 'startup'. Cause: " + err); }) }).catch((err) => { - console.info("Failed to get the preferences")}) + console.info("Failed to get the preferences.") + }); ``` 5. Store data persistently. @@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file. 6. Observe data changes. - Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change. + Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. ```js var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key" + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup with err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file with err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed to file successfully.") // Observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) }) ``` 7. Delete the specified file. - Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. + Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored. ```js - let proDelete = data_preferences.deletePreferences(context, 'mystore') + let proDelete = data_preferences.deletePreferences(context, 'mystore'); proDelete.then(() => { - console.info("Data deleted successfully.") + console.info("Deleted data successfully."); }).catch((err) => { - console.info("Failed to delete data with err: " + err) + console.info("Failed to delete data. Cause: " + err); }) ``` diff --git a/en/application-dev/database/database-preference-overview.md b/en/application-dev/database/database-preference-overview.md index b26943b6109818b1ca9d74038f9df4471f69531e..4987b6e8494c738ef29e2f362b2acda43528bbb6 100644 --- a/en/application-dev/database/database-preference-overview.md +++ b/en/application-dev/database/database-preference-overview.md @@ -1,29 +1,34 @@ # Preferences Overview -Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. +Preferences are used to implement quick access and persistence of the data in the `key-value` structure. + +After an application obtains a **Preferences** instance, the data in the instance will be cached in the memory for faster access. + +The cached data can also be written to a text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing files. + +You do not need to care about the implementation of the database locking mechanism. ## Basic Concepts -- **Key-value data structure** +- **Key-value structure** - A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. + A type of data structure. The `Key` is the unique identifier for a piece of data, and the `Value` is the specific data being identified. - **Non-relational database** - A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent. + A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. The database that organizes data in the `key-value` structure is a non-relational database. ## Working Principles -When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file. - -When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method. +1. An application can load data from a **Preferences** persistent file to a **Preferences** instance. The system stores the **Preferences** instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** persistent file. +2. When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the `Preferences` instance can be flushed to its **Preferences** persistent file by calling the **flush()** method. -**Figure 1** How **Preferences** work +**Figure 1** Working mechanism ![](figures/preferences.png) ## Constraints - **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. -- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. -- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty. +- The `Key` in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. +- The `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty. diff --git a/en/application-dev/database/database-relational-overview.md b/en/application-dev/database/database-relational-overview.md index 2363e12b7c389845ba9586cf332080e8600e58c0..c78034c76f63fe1f6e8bd338f9595206f8c5eea0 100644 --- a/en/application-dev/database/database-relational-overview.md +++ b/en/application-dev/database/database-relational-overview.md @@ -2,6 +2,8 @@ The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. +You do not need to care about the implementation of the database locking mechanism. + ## Basic concepts - **RDB** diff --git a/en/application-dev/database/figures/preferences.png b/en/application-dev/database/figures/preferences.png index ab91e2d4fb3019ca3f48a195041c9b19bdaec830..be3c6feef3c1f8d9da83e5d3c0065655bd07cb57 100644 Binary files a/en/application-dev/database/figures/preferences.png and b/en/application-dev/database/figures/preferences.png differ 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/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 54199719cd93a523d8f2b0af14c12578997a02a2..48f725e080441281cd2e88820eeacc6032a2dbab 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -2,89 +2,164 @@ ## When to Use -The event logging function helps applications to log various information generated during running. +The event logging function helps applications log various information generated during running. ## Available APIs JS application event logging APIs are provided by the **hiAppEvent** module. -**Table 1** APIs for event logging +The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md). -| API | Return Value | Description | -| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | -| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. | -| write(string eventName, EventType type, object keyValues): Promise\ | Promise\ | Logs application events in asynchronous mode. This method uses a promise to return the result. | +**Table 1** APIs for application event logging -When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | +| write(string eventName, EventType type, object keyValues): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | +| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.| +| write(AppEventInfo info): Promise\ | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.| -**Table 2** APIs for event logging configuration +When an asynchronous callback is used, the return value can be processed directly in the callback. -| API | Return Value | Description | -| ------------------------------ | ------------ | ------------------------------------------------------------ | -| configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.
The value **true** indicates that the operation is successful, and value **false** indicates the opposite. | +If a promise is used, the return value can also be processed in the promise in a similar way. -## Event Verification Result Codes +For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). -| Result Code | Cause | Check Rule | Processing Method | -| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| 0 | None | Event verification is successful. | Event logging is normal. No action is required. | -| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.
The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. | -| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The key value must be an object. | Ignore this event and do not perform logging. | -| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. | -| -100 | Unknown error | None | Ignore this event and do not perform logging. | -| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.
The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The key name does not start with a digit or underscore (\_).
The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. | -| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | -| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. | -| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. | -| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | -| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. | -| 7 | Invalid list value | A list value can only be a basic element.
The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. | +**Table 2** APIs for event logging configuration +| API | Description | +| --------------------------------------- | ---------------------------------------------------- | +| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.| -## How to Develop +**Table 3** APIs for watcher management -In this example, an application event is logged after the application startup execution page is loaded. +| API | Description | +| -------------------------------------------------- | -------------------- | +| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.| +| removeWatcher(Watcher watcher): void | Removes an event watcher.| -1. Create a JS application project. In the displayed Project window, choose **entry > src > main** > **js** > **default** > **pages > index**, and double-click index.js. Add the code to log the initial application event after page loading. The sample code is as follows: +**Table 4** APIs for clearing logging data - ```js - import hiAppEvent from '@ohos.hiAppEvent' +| API | Description | +| ----------------- | -------------------- | +| clearData(): void | Clears local logging data.| + +### Event Verification Result Codes + +| Result Code| Cause | Verification Rules | Handling Method | +| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | +| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. | +| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. | +| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The event parameter must be an object.| Ignore this event and do not perform logging. | +| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. | +| -99 | Application event logging disabled | Application event logging is disabled. | Ignore this event and do not perform logging. | +| -100 | Unknown error | None. | Ignore this event and do not perform logging. | +| 1 | Invalid key name | The name is not empty and contains a maximum of 16 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).
The name does not end with an underscore \(_).| Ignore the key-value pair and continue to perform logging. | +| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | +| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element]| Ignore the key-value pair and continue to perform logging. | +| 4 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, and continue to perform logging.| +| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | +| 6 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. | +| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. | + +## Development Procedure + +The following uses a one-time event watcher as an example to illustrate the development procedure. + +1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows: + + ```ts + import hiAppEvent from '@ohos.hiAppEvent'; - export default { - data: { - title: "" - }, - onInit() { - this.title = this.$t('strings.world'); + @Entry + @Component + struct Index { + @State message: string = 'Hello World' - // 1. Callback mode - hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}, (err, value) => { - if (err) { - console.error(`failed to write event because ${err.code}`); - return; + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button("1 writeTest").onClick(()=>{ + hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" } - console.log(`success to write event: ${value}`); - }); + }).then((value) => { + console.log(`HiAppEvent success to write event: ${value}`); + }).catch((err) => { + console.error(`HiAppEvent failed to write event because ${err.code}`); + }); + }) - // 2. Promise mode - hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}) - .then((value) => { - console.log(`success to write event: ${value}`); - }).catch((err) => { - console.error(`failed to write event because ${err.code}`); - }); - - // 3. Set the application event logging switch. - hiAppEvent.configure({ - disable: true - }); + Button("2 addWatcherTest").onClick(()=>{ + hiAppEvent.addWatcher({ + name: "watcher1", + appEventFilters: [{ domain: "test_domain" }], + triggerCondition: { + row: 2, + size: 1000, + timeOut: 2 + }, + onTrigger: function (curRow, curSize, holder) { + if (holder == null) { + console.error("HiAppEvent holder is null"); + return; + } + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { + console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); + console.info("HiAppEvent eventPkg.row=" + eventPkg.row); + console.info("HiAppEvent eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("HiAppEvent eventPkg.data=" + eventInfo); + } + } + } + }); + }) - // 4. Set the maximum size of the event file storage directory. The default value is 10M. - hiAppEvent.configure({ - maxStorage: '100M' - }); + Button("3 removeWatcherTest").onClick(()=>{ + hiAppEvent.removeWatcher({ + name: "watcher1" + }) + }) + } + .width('100%') } + .height('100%') + } } ``` -2. Tap the run button on the application UI to run the project. +2. Touch the run button on the IDE to run the project. + +3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window: + + ``` + success to write event: 0 + ``` + +4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window. + + ``` + HiAppEvent eventPkg.packageId=0 + HiAppEvent eventPkg.row=2 + HiAppEvent eventPkg.size=308 + HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"} + ``` + +5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher. + +## Samples + +The following sample is provided to help you better understand how to develop the application event logging feature: + +- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest) diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md index 2a5e36f879a922f3d6bf845e700068c2a299b337..088f3624b0c9638dd5137e1460b3cc832c290de9 100644 --- a/en/application-dev/dfx/hiappevent-overview.md +++ b/en/application-dev/dfx/hiappevent-overview.md @@ -2,10 +2,10 @@ HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. -The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data. +The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events. ## Basic Concepts -- **Logging** +**Logging** - Logs changes caused by user operations to provide service data for development, product, and O&M analysis. + A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis. \ No newline at end of file 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/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 677e70f6e3b7eee215530cd15e7ab1b42676866c..131114d67cb3e1c8519d6d5f3a85b438e5846f6f 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -5,6 +5,7 @@ - [Audio Playback Development](audio-playback.md) - [Audio Recording Development](audio-recorder.md) - [Audio Rendering Development](audio-renderer.md) + - [Audio Stream Management Development](audio-stream-manager.md) - [Audio Capture Development](audio-capturer.md) - [OpenSL ES Audio Playback Development](opensles-playback.md) - [OpenSL ES Audio Recording Development](opensles-capture.md) diff --git a/en/application-dev/media/audio-stream-manager.md b/en/application-dev/media/audio-stream-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..4f0f88c8fa2c3357e7a8d582642cf4efbb7bf1db --- /dev/null +++ b/en/application-dev/media/audio-stream-manager.md @@ -0,0 +1,158 @@ +# Audio Stream Management Development + +## When to Use + +You can use **AudioStreamManager** to manage audio streams. + +### Development Process + +During application development, use **getStreamManager()** to create an **AudioStreamManager** instance. Then, you can call **on('audioRendererChange')** or **on('audioCapturerChange')** to listen for status, client, and audio attribute changes of the audio playback or recording application. To cancel the listening for these changes, call **off('audioRendererChange')** or **off('audioCapturerChange')**. You can call **getCurrentAudioRendererInfoArray()** to obtain information about the audio playback application, such as the unique audio stream ID, UID of the audio playback client, and audio status. Similarly, you can call **getCurrentAudioCapturerInfoArray()** to obtain information about the audio recording application. The figure below shows the invoking relationship. + +For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). + +**Figure 1** Audio stream management invoking relationship + +![](figures/zh-ch_image_audio_stream_manager.png) + +## How to Develop + +1. Create an **AudioStreamManager** instance. + + Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. + + ```js + var audioStreamManager = audio.getStreamManager(); + ``` + +2. (Optional) Call **on('audioRendererChange')** to listen for audio renderer changes. +If an application needs to receive notifications when the audio playback application status, audio playback client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js + 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); + } + } + }); + ``` + +3. (Optional) Call **off('audioRendererChange')** to cancel listening for audio renderer changes. + + ```js + audioStreamManager.off('audioRendererChange'); + console.info('######### RendererChange Off is called #########'); + ``` + +4. (Optional) Call **on('audioCapturerChange')** to listen for audio capturer changes. +If an application needs to receive notifications when the audio recording application status, audio recording client, or audio attribute changes, it can subscribe to this event. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + + ```js + audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(' ## audioCapturerChange 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); + } + } + }); + ``` + +5. (Optional) Call **off('audioCapturerChange')** to cancel listening for audio capturer changes. + + ```js + audioStreamManager.off('audioCapturerChange'); + console.info('######### CapturerChange Off is called #########'); + ``` + +6. (Optional) Call **getCurrentAudioRendererInfoArray()** to obtain information about the current audio renderer. +This API can be used to obtain the unique ID of the audio stream, UID of the audio playback client, audio status, and other information about the audio player. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly. + + ```js + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info('######### 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); + }); + ``` + +7. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio capturer. +This API can be used to obtain the unique ID of the audio stream, UID of the audio recording client, audio status, and other information about the audio capturer. Before calling this API, a third-party application must have the **ohos.permission.USE_BLUETOOTH** permission configured, for the device name and device address to be displayed correctly. + + ```js + 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; + 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); + } + } + } + }).catch((err) => { + console.log('getCurrentAudioCapturerInfoArray :ERROR: ' + err.message); + }); + ``` diff --git a/en/application-dev/media/figures/zh-ch_image_audio_stream_manager.png b/en/application-dev/media/figures/zh-ch_image_audio_stream_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..1f326d4bd0798dd5ecc0b55130904cbf87d2ea1f Binary files /dev/null and b/en/application-dev/media/figures/zh-ch_image_audio_stream_manager.png differ 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/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md index c6de99e3fee6919ef1ca1e1a0f87a7aa0a890a74..5d83cf443c0f629fcb471a6c12ccd3069ac2e593 100644 --- a/en/application-dev/notification/assistant-guidelines.md +++ b/en/application-dev/notification/assistant-guidelines.md @@ -6,7 +6,7 @@ The common event and notification module provides debugging tools to facilitate ### publish -* Functionality +* Function Publishes a common event. @@ -16,14 +16,14 @@ The common event and notification module provides debugging tools to facilitate The table below describes the available options. - | Option | Description | + | Option | Description | | ------------ | ------------------------------------------ | - | -e/--event | Indicates the name of the common event to publish. Mandatory. | - | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.| - | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | - | -c/--code | Indicates the result code of the common event. Optional. | - | -d/--data | Indicates the data carried in the common event. Optional. | - | -h/--help | Indicates the help Information | + | -e/--event | Indicates the name of the common event to publish. Mandatory. | + | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. | + | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | + | -c/--code | Indicates the result code of the common event. Optional. | + | -d/--data | Indicates the data carried in the common event. Optional. | + | -h/--help | Indicates the help Information | * Example @@ -43,7 +43,7 @@ The common event and notification module provides debugging tools to facilitate ### dump -* Functionality +* Function Displays information about common events. @@ -53,11 +53,11 @@ The common event and notification module provides debugging tools to facilitate The table below describes the available options. - | Option | Description | + | Option | Description | | ---------- | -------------------------------------------- | - | -a/--all | Displays information about all common events that have been sent since system startup.| - | -e/--event | Displays information about a specific event. | - | -h/--help | Displays the help information. | + | -a/--all | Displays information about all common events that have been sent since system startup. | + | -e/--event | Displays information about a specific event. | + | -h/--help | Displays the help information. | * Example @@ -69,7 +69,7 @@ The common event and notification module provides debugging tools to facilitate ### help -* Functionality +* Function Displays the help information. @@ -87,7 +87,7 @@ The common event and notification module provides debugging tools to facilitate ### dump -* Functionality +* Function Displays information about notifications. @@ -97,19 +97,19 @@ The common event and notification module provides debugging tools to facilitate The table below describes the available options. - | Option | Description | + | Option | Description | | ---------------- | ---------------------------------------- | - | -A/--active | Displays information about all active notifications. | - | -R/--recent | Displays information about the recent notifications. | - | -D/--distributed | Displays information about distributed notifications from other devices. | - | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional.| - | -h/--help | Displays the help information. | + | -A/--active | Displays information about all active notifications. | + | -R/--recent | Displays information about the recent notifications. | + | -D/--distributed | Displays information about distributed notifications from other devices. | + | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. | + | -h/--help | Displays the help information. | * Example `anm dump -A` - Displays information about all active notifications. + Display information about all active notifications. ![anm-dump-A](figures/anm-dump-A.png) @@ -117,11 +117,11 @@ The common event and notification module provides debugging tools to facilitate `anm dump --setRecentCount 10` - Set the number of the cached recent notifications to be displayed to 10. + Set the number of the cached recent notifications to be displayed to **10**. ### help -* Functionality +* Function Displays the help information. 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 792837f2620a8c44dcf69ad7a56e8aed6693bf24..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/figures/en-us_image_0000001655128998.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png index d044d5d829ab1ad805f4ffcda19837f867b976fc..a044e797ef1429b5ef5cf8cf99950697e7bb1e98 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png index 2dd664a2b25751cc32bd81927b30036d5cc4f351..408bf7d9864352d03f1603b0e1c68741401e016f 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png index 7d3222667d7bffe89a148dc3b08861a86c43713e..6f5469a6374e6da2ca48c03708fc59c74f556adb 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png index b42f2e3896d334d86e89b867cf3428782f88d600..d4197e195f3b4f8ca0fc05965af7457ece28decc 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png index 2dda1a5cfca8d75d70e40b8bc0d555faade04583..b106ff353bddede943257f62a0a71403b1b5db4d 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png differ diff --git a/en/application-dev/quick-start/full-sdk-switch-guide.md b/en/application-dev/quick-start/full-sdk-switch-guide.md index 4c20e429bdef97ab0503614d01f1807e56eedb13..a687d69b739e12893aff91fb2e6939eb1b32aad0 100644 --- a/en/application-dev/quick-start/full-sdk-switch-guide.md +++ b/en/application-dev/quick-start/full-sdk-switch-guide.md @@ -1,23 +1,22 @@ # Guide to Switching to Full SDK -Both the public SDK and full SDK are toolkits for application development. - -The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications. +Both the public SDK and full SDK are toolkits for application development.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications. The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs. The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. -## Downloading the Full SDK (of 3.1.1 Release in this example) - -Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md). - -![image-20220613161049897](figures/en-us_image_0000001655128646.png) +> **NOTE** +> +> The screenshots in this document are for reference only. +## Downloading the Full SDK +Manually download the system-specific full SDK package from the mirror. For details, see [Release Notes](../../release-notes/OpenHarmony-v3.2-beta2.md). +## Checking the Local SDK Location -## Checking the Local SDK Location
In this example, an eTS project is used. For a JS project, replace **ets** with **js**. +In this example, an eTS project is used. For a JS project, replace **ets** with **js**. In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK. @@ -38,61 +37,58 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo Note: The criteria for identifying system APIs are subject to the released API documentation. - - -2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example. +2. Replace the SDK. The following uses public-SDK-3.x.x.x for Windows as an example. - - - a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip` + a. Decompress the downloaded full SDK file: `ets-windows-3.x.x.x-Release.zip` ![image-20220613165018184](figures/en-us_image_0000001655129264.png) b. Replace the SDK files. - Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.) + Back up the local SDK files. (Copy and rename the version directory in the **ets** directory, or copy the entire **ets** directory to another local path.) Go to the obtained location of the local installed SDK and back up the files therein. ![image-20220613161352157](figures/en-us_image_0000001655129041.png) - Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**. + Note: The name of the backup version directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.x.x.x_backup**. ![image-20220613165018184](figures/en-us_image_0000001655129398.png) - The configuration in the **oh-uni-package.json** file is as follows: + The configuration in the **oh-uni-package.json** file is as follows, where the value of `apiVersion` is subject to the API version of the SDK, and the value of `version` is subject to the version number in the SDK file. ``` { - "apiVersion": "8", + "apiVersion": "X", "displayName": "Ets", "meta": { "metaVersion": "3.0.0" }, "path": "ets", "releaseType": "Release", - "version": "3.1.6.6" + "version": "3.x.x.x" } ``` + - **Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten. + Delete all files in the original SDK (3.x.x.x) directory. Failure to do so may result in some files being unable to be overwritten. Copy the full SDK to the location of the local SDK. - Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK. + Copy all files in the **ets** directory in the full SDK to the **ets\*3.x.x.x*** directory in the location of the local SDK. Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number. - In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package. + In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the `npm install` command to download the **node_modules** dependency package. ![image-20220613171111405](figures/en-us_image_0000001655129333.png) c. Check for system APIs. - + ![image-20220613213038104](figures/en-us_image_0000001655129372.png) diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index 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 7129aef3ab0de633ab3ab96a225578a6a31da2f3..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 @@ -14,7 +14,7 @@ ![01](figures/01.png) -2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, **Language** to **eTS** and retain the default values for other parameters. +2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, and retain the default values for other parameters. ![07](figures/07.png) @@ -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 3f1c11258560d916d54490ff4e2c0c23becdd410..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 @@ -216,6 +219,7 @@ - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) + - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) - [Timer](js-apis-timer.md) diff --git a/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md index 2b4b2d249af1a50e2427773f36e8c1270481ca55..a78f8cc320a4d081f356145d8ed4c51907a025ba 100644 --- a/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @@ -14,6 +14,14 @@ The **AccessibilityExtensionAbility** module is based on the ExtensionAbility fr import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' ``` +## Attributes + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Type | Readable | Writable | Description | +| --------- | -------- | ---- | ---- | ------------------------- | +| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | + ## AccessibilityEvent Defines an accessibility event. @@ -24,7 +32,7 @@ Defines an accessibility event. | Name | Type | Readable | Writable | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [EventType](js-apis-accessibility.md#EventType) \| [WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](touchguidetype) \| [GestureType](gesturetype) \| [PageUpdateType](pageupdatetype) | Yes | No | Event type. | +| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | target | AccessibilityElement | Yes | No | Target component where the event occurs.| | timeStamp | number | Yes | No | Timestamp of the event. | @@ -41,24 +49,6 @@ Defines a gesture path. | points | Array<[GesturePoint](gesturepoint)> | Yes | Yes | An array of gesture touch points. | | durationTime | number | Yes | Yes | Total time consumed by the gesture.| -### constructor - -constructor(durationTime: number) - -A constructor used to create a **GesturePath** object. - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------------ | ------ | ---- | ------ | -| durationTime | number | Yes | Total time consumed by the gesture.| - -**Example** - -```typescript -let gesturePath = new GesturePath(100); -``` - ## GesturePoint Defines a gesture touch point. @@ -72,25 +62,6 @@ Defines a gesture touch point. | positionX | number | Yes | Yes | X-coordinate of the touch point.| | positionY | number | Yes | Yes | Y-coordinate of the touch point.| -### constructor - -constructor(positionX: number, positionY: number) - -A constructor used to create a **GesturePoint** object. - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ------- | -| positionX | number | Yes | X-coordinate of the touch point.| -| positionY | number | Yes | Y-coordinate of the touch point.| - -**Example** - -```typescript -let gesturePoint = new GesturePoint(100, 200); -``` - ## GestureType Enumerates gesture types. @@ -190,7 +161,7 @@ Called when an event that matches the specified bundle and event type occurs. In | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | --------------- | -| event | [AccessibilityEvent](accessibilityevent) | Yes | Accessibility event. No value is returned.| +| event | [AccessibilityEvent](#accessibilityevent) | Yes | Accessibility event. No value is returned.| **Example** @@ -215,7 +186,7 @@ Called when a physical key is pressed. In this API, you can determine whether to | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------- | -| keyEvent | [KeyEvent](js-apis-inputeventclient.md#KeyEvent) | Yes | Key event. If **true** is returned, the key is intercepted.| +| keyEvent | [KeyEvent](js-apis-keyevent.md#KeyEvent) | Yes | Key event. If **true** is returned, the key is intercepted.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md index 3289f1d2efc43a5af0a8fa3266f41b1ff3139aaa..c7a280fecc755160c7e7c602aed0f80e958fc9ee 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -4,11 +4,11 @@ The **DataShareExtensionAbility** module provides Extension abilities for data s >**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 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 provided by this module are system APIs. +> The APIs provided by this module are system APIs. > ->The APIs of this module can be used only in the stage model. +> The APIs of this module can be used only in the stage model. ## Modules to Import @@ -70,62 +70,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { }; ``` -## getFileTypes - -getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void - -Obtains the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API is called by the server and can be overridden as required. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ---------------------------------------- | ---- | ---------------------------------- | -| uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME types to match. | -| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the MIME types obtained.| - -**Example** - -```ts -export default class DataShareExtAbility extends DataShareExtensionAbility { - getFileTypes(uri, mimeTypeFilter, callback) { - let err = {"code":0}; - let ret = new Array("type01", "type02", "type03"); - callback(err, ret); - } -}; -``` - -## openFile - -openFile?(uri: string, mode: string, callback: AsyncCallback<number>): void - -Opens a file. This API is called by the server and can be overridden as required. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------------------ | -| uri | string | Yes | URI of the file to open. | -| mode | string | Yes | File open mode, which can be read-only or read/write.| -| callback | AsyncCallback<number> | Yes | Callback invoked to return the file descriptor. | - -**Example** - -```ts -export default class DataShareExtAbility extends DataShareExtensionAbility { - openFile(uri, mode, callback) { - let err = {"code":0}; - let fd = 0; - callback(err,fd); - } -}; -``` - ## insert insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void @@ -301,33 +245,6 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { }; ``` -## getType - -getType?(uri: string, callback: AsyncCallback<string>): void - -Obtains the MIME type corresponding to the given URI. This API can be overridden as required. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| uri | string | Yes | URI of the target data.| -| callback | AsyncCallback<string> | Yes| Callback invoked to return the MIME type obtained.| - -**Example** - -```ts -export default class DataShareExtAbility extends DataShareExtensionAbility { - getType(uri, callback) { - let err = {"code":0}; - let ret = "image"; - callback(err, ret); - } -}; -``` - ## batchInsert batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>): void 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-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-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index d0702995d7955ccf0b7a9907ab09b79efd6268ec..710d6ccb8820e88ed98e3519c36824efdd5e5b17 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -2,7 +2,7 @@ The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. -> **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. @@ -18,7 +18,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v **System capability**: SystemCapability.Notification.CommonEvent -| Name | Value | Subscriber Permissions | Description | +| Name | Value | Subscriber Permission | Description | | ------------ | ------------------ | ---------------------- | -------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | @@ -30,7 +30,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | | COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | | COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | | COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | | COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | | COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | @@ -39,7 +39,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | | COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | | COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. | COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | | COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | | COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | @@ -66,21 +66,21 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | | COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | | COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | -| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | Indicates the common event that user switching is happening. | -| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be started. | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | Indicates the common event that user switching is happening. | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be started. | | COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | -| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be stopped. | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be stopped. | | COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | | COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | Indicates the common event about a HUAWEI ID login. | | COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | Indicates the common event about a HUAWEI ID logout. | | COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | Indicates the common event that the HUAWEI ID is invalid. | | COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | Indicates the common event about a HUAWEI ID logoff. | | COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | -| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | -| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | | COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | | COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | -| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | | COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | | COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | | COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | @@ -104,7 +104,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | @@ -115,29 +115,29 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | | COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | | COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | | COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | -| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | -| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | | COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the enabled state. | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the enabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | | COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | | COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | | COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | | COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | -| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been added to the system. | -| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been removed from the system. | -| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | -| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | -| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been added to the system. | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been removed from the system. | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | | COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | | COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | | COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | @@ -153,7 +153,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v |COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates the common event that the USB device status has changed. | |COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the common event that the USB port status of the user device has changed. | | COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | | COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | | COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | @@ -162,18 +162,18 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | | COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device becomes unmountable. | | COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | -| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | -| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | -| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | -| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | -| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | -| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | -| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | -| COMMON_EVENT_SPN_INFO_CHANGED9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | +| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | ## CommonEvent.publish @@ -186,10 +186,10 @@ Publishes a common event. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| -------- | -------- | -------------------- | ---- | ---------------------- | -| event | Read only | string | Yes | Name of the common event to publish.| -| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -219,11 +219,11 @@ Publishes a common event with given attributes. This API uses a callback to retu **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read only | string | Yes | Name of the common event to publish. | -| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | syncCallback\ | Yes | Callback used to return the result. | **Example** @@ -263,11 +263,11 @@ Publishes a common event to a specific user. This API uses a callback to return **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| -------- | -------- | -------------------- | ---- | ---------------------------------- | -| event | Read only | string | Yes | Name of the common event to publish. | -| userId | Read only | number | Yes | User ID.| -| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -302,12 +302,12 @@ Publishes a common event with given attributes to a specific user. This API uses **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read only | string | Yes | Name of the common event to publish. | -| userId | Read only| number | Yes| User ID.| -| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes| User ID.| +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -347,10 +347,10 @@ Creates a subscriber. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------- | -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | -| callback | Read only | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| **Example** @@ -389,9 +389,9 @@ Creates a subscriber. This API uses a promise to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------- | -------- | ----------------------------------------------------- | ---- | -------------- | -| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| +| Name | Type | Mandatory| Description | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| **Return value** | Type | Description | @@ -429,10 +429,10 @@ Subscribes to common events. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | --------------------------------------------------- | ---- | -------------------------------- | -| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | Read only | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| **Example** @@ -481,10 +481,10 @@ Unsubscribes from common events. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | ----------------------------------------------- | ---- | ------------------------ | -| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | Read only | AsyncCallback\ | No | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| **Example** @@ -1234,37 +1234,37 @@ subscriber.finishCommonEvent().then(() => { **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------- | -| event | Read only | string | Yes | Name of the common event that is being received. | -| bundleName | Read only | string | No | Bundle name. | -| code | Read only | number | No | Result code of the common event, which is used to transfer data of the int type. | -| data | Read only | string | No | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | +| Name | Readable| Writable| Type | Description | +| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | +| event | Yes | No | string | Name of the common event that is being received. | +| bundleName | Yes | No | string | Bundle name. | +| code | Yes | No | number | Result code of the common event, which is used to transfer data of the int type. | +| data | Yes | No | string | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | ## CommonEventPublishData **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable/Writable| Type | Mandatory| Description | -| --------------------- | -------- | -------------------- | ---- | ---------------------------- | -| bundleName | Read only | string | No | Bundle name. | -| code | Read only | number | No | Result code of the common event. | -| data | Read only | string | No | Custom result data of the common event.| -| subscriberPermissions | Read only | Array\ | No | Permissions required for subscribers to receive the common event. | -| isOrdered | Read only | boolean | No | Whether the common event is an ordered one. | -| isSticky | Read only | boolean | No | Whether the common event is a sticky one. | -| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | +| Name | Readable| Writable| Type | Description | +| --------------------- | ---- | ---- | -------------------- | ---------------------------- | +| bundleName | Yes | No | string | Bundle name. | +| code | Yes | No | number | Result code of the common event. | +| data | Yes | No | string | Custom result data of the common event.| +| subscriberPermissions | Yes | No | Array\ | Permissions required for subscribers to receive the common event. | +| isOrdered | Yes | No | boolean | Whether the common event is an ordered one. | +| isSticky | Yes | No | boolean | Whether the common event is a sticky one. | +| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | ## CommonEventSubscribeInfo **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | -| events | Read only | Array\ | Yes | Name of the common event to publish. | -| publisherPermission | Read only | string | No | Permissions required for publishers to publish the common event. | -| publisherDeviceId | Read only | string | No | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Read only | number | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Read only | number | No | Subscriber priority. The value ranges from -100 to 1000. | +| Name | Readable| Writable| Type | Description | +| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | +| events | Yes | No | Array\ | Name of the common event to publish. | +| publisherPermission | Yes | No | string | Permissions required for publishers to publish the common event. | +| publisherDeviceId | Yes | No | string | Device ID. The value must be the ID of an existing device on the same network. | +| userId | Yes | No | number | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | Yes | No | number | Subscriber priority. The value ranges from -100 to 1000. | 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..499dafec721fd280beee9e9ccfcab76ae895bd14 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,37 @@ 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. + ## 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. + ## 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. + ## 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. + ## 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..82941689b8d2d511ca1878b0b03fac2e1c32dafd 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -56,6 +56,8 @@ let options = {trim : false, declarationKey:"_declaration", nameKey : "_name", elementsKey : "_elements"} let result = JSON.stringify(conv.convert(xml, options)); 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-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md index dc239c35cbe017f7c5edc0a9fd8ff1bd74b3c366..22ae3fc33e27b1dc0b859848fdb8e0ea6c6f2122 100644 --- a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md @@ -2,9 +2,11 @@ The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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 provided by this module are system APIs. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index c3b59a85ab9e2945a8375a61b44c7e45c5d1c385..a5f16c8c04d650608231c4757224c662c23bf387 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -2,9 +2,13 @@ The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> 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 provided by this module are system APIs. +> +> The APIs of this module can be used only in the stage model. ## Modules to Import @@ -87,85 +91,12 @@ dataShare.createDataShareHelper(this.context, uri).then((data) => { Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). -This API can be used only in the stage model. - -### openFile - -openFile(uri: string, mode: string, callback: AsyncCallback<number>): void - -Opens a file. This API uses an asynchronous callback to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------------------------------- | -| uri | string | Yes | URI of the file to open. | -| mode | string | Yes | File open mode.
**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.| -| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the file descriptor. Otherwise, **err** is an error object.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.openFile(uri, "rwt", (err, data) => { - if (err != undefined) { - console.info("openFile failed, error message : " + err); - }else { - console.info("openFile succeed, data : " + data); - let fd = data; - } -}); -``` - -### openFile - -openFile(uri: string, mode: string): Promise<number> - -Opens a file. This API uses a promise to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | ------------------------------------------------------------ | -| uri | string | Yes | URI of the file to open. | -| mode | string | Yes | File open mode.
**r** means to open a file for reading; **w** means to open a file for writing (erasing any data in the file); **wa** means to open a file in append mode for writing at the end of the file; **rw** means to open a file for both reading and writing.| - -**Return value** - -| Type | Description | -| --------------- | ---------------- | -| Promise<number> | Promise used to return the file descriptor.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.openFile(uri, "rwt").then((data) => { - console.info("openFile succeed, data : " + data); - let fd = data; -}).catch((err) => { - console.info("openFile failed, error message : " + err); -}) -``` - ### on('dataChange') on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -174,7 +105,7 @@ This API can be used only in the stage model. | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | Yes | Called when the change notification is triggered. In this case, **err** is **undefined**. Otherwise, it is not called or **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.| **Example** @@ -193,8 +124,6 @@ off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void Unsubscribes from the changes of the specified data. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -222,8 +151,6 @@ insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): Inserts a single data record into the database. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -259,8 +186,6 @@ insert(uri: string, value: ValuesBucket): Promise<number> Inserts a single data record into the database. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -299,8 +224,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callbac Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -335,8 +258,6 @@ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promis Deletes one or more data records from the database. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -374,8 +295,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Queries data in the database. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -412,8 +331,6 @@ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Queries data in the database. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -453,8 +370,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: Updates data in the database. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -496,8 +411,6 @@ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: Updates data in the database. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -542,8 +455,6 @@ batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallb Batch inserts data into the database. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -577,8 +488,6 @@ batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number&g Batch inserts data into the database. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -609,149 +518,12 @@ dataShareHelper.batchInsert(uri, vbs).then((data) => { }); ``` -### getType - -getType(uri: string, callback: AsyncCallback<string>): void - -Obtains the Multipurpose Internet Mail Extensions (MIME) type of the specified data. This API uses an asynchronous callback to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | --------------------------------------------- | -| uri | string | Yes | URI of the data. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME type obtained. Otherwise, **err** is an error object.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.getType(uri, (err, data)=>{ - if (err != undefined) { - console.log("getType failed, error message : " + err); - }else{ - console.log("getType succeed, data : " + data); - let result = data; - } -}); -``` - -### getType - -getType(uri: string): Promise<string> - -Obtains the MIME type of the specified data. This API uses a promise to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | -------------------- | -| uri | string | Yes | URI of the data.| - -**Return value** - -| Type | Description | -| ---------------- | ----------------------------------- | -| Promise<string> | Promise used to return the MIME type obtained.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -dataShareHelper.getType(uri).then((data) => { - console.log("getType succeed, data : " + data); -}).catch((err) => { - console.log("getType failed, error message : " + err); -}); -``` - -### getFileTypes - -getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>): void - -Obtains the supported MIME types. This API uses an asynchronous callback to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: Obtain all supported types.
**image/\***: Obtain the MIMEs with the main type of **image**.
**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.| -| callback | AsyncCallback> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the MIME types obtained. Otherwise, **err** is an error object.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let mimeTypeFilter = "image/*"; -dataShareHelper.getFileTypes(uri, mimeTypeFilter, (err,data) => { - if (err != undefined) { - console.log("getFileTypes failed, error message : " + err); - }else{ - console.log("getFileTypes succeed, data : " + data); - } -}); -``` - -### getFileTypes - -getFileTypes(uri: string, mimeTypeFilter: string): Promise<Array<string>> - -Obtains the supported MIME types. This API uses a promise to return the result. - -This API can be used only in the stage model. - -**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | ------------------------------------------------------------ | -| uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME types to match. Example:
**\*/\***: Obtain all supported types.
**image/\***: Obtain the MIMEs with the main type of **image**.
**\*/jpg**: Obtain the MIMEs with the subtype of **jpg**.| - -**Return value** - -| Type | Description | -| ------------------------ | ------------------------ | -| Promise<Array<string>> | Promise used to return the MIME types obtained.| - -**Example** - -```ts -import Ability from '@ohos.application.Ability' -let uri = ("datashare:///com.samples.datasharetest.DataShare"); -let mimeTypeFilter = "image/*"; -dataShareHelper.getFileTypes(uri, mimeTypeFilter).then((data) => { - console.log("getFileTypes succeed, data : " + data); -}).catch((err) => { - console.log("getFileTypes failed, error message : " + err); -}); -``` - ### normalizeUri normalizeUri(uri: string, callback: AsyncCallback<string>): void Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -781,8 +553,6 @@ normalizeUri(uri: string): Promise<string> Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -815,8 +585,6 @@ denormalizeUri(uri: string, callback: AsyncCallback<string>): void Denormalizes a URI. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -846,8 +614,6 @@ denormalizeUri(uri: string): Promise<string> Denormalizes a URI. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -880,8 +646,6 @@ notifyChange(uri: string, callback: AsyncCallback<void>): void Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -907,8 +671,6 @@ notifyChange(uri: string): Promise<void> Notifies the registered observer of data changes. This API uses a promise to return the result. -This API can be used only in the stage model. - **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 560696c1ca48cb404aa0a29e95f8c3c1a1841198..6803d4edf50fc219bc37c4be79fc71687dd91457 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,15 +1,18 @@ # Preferences -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, the keys are of the string type, and the values can be of the number, string, Boolean, Array\, Array\, or Array\ type. +The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. + +The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. > **NOTE**
+> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```ts +```js import data_preferences from '@ohos.data.preferences'; ``` @@ -17,36 +20,39 @@ import data_preferences from '@ohos.data.preferences'; **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| +| Name | Type| Readable| Writable| Description | +| ---------------- | -------- | ---- | ---- | --------------------------------------- | +| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. The key must be less than 80 bytes. | +| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. The value must be less than 8192 bytes.| ## data_preferences.getPreferences getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void -Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses an asynchronous callback to return the result. - +Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| **Example** -```ts -data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + +```js +var preferences = null; +data_preferences.getPreferences(this.context, 'mystore', function (err, object) { if (err) { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences. Cause: " + err); return; } - console.info("Got preferences successfully.") + preferences = object; + console.info("Got the preferences successfully."); }) ``` @@ -55,28 +61,31 @@ data_preferences.getPreferences(this.context, 'mystore', function (err, preferen getPreferences(context: Context, name: string): Promise<Preferences> -Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses a promise to return the result. +Obtains a **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Preferences](#preferences)> | Promise used to return the result.| +| Type | Description | +| ------------------------------------------ | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| **Example** -```ts + +```js +var preferences = null; let promise = data_preferences.getPreferences(this.context, 'mystore') -promise.then((preferences) => { - console.info("Got preferences successfully.") +promise.then((object) => { + preferences = object; + console.info("Got the preferences successfully."); }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences. Cause: " + err); }) ``` @@ -85,26 +94,29 @@ promise.then((preferences) => { deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void -Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory. -Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result. +Deletes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result. + +If the **Preferences** instance has a persistent file, this API also deletes the persistent file. + +The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js data_preferences.deletePreferences(this.context, 'mystore', function (err) { if (err) { - console.info("Failed to delete data, err: " + err) + console.info("Failed to delete the preferences. Cause: " + err); return } - console.info("Deleted preferences successfully.") + console.info("Deleted the preferences successfully." ); }) ``` @@ -113,29 +125,32 @@ data_preferences.deletePreferences(this.context, 'mystore', function (err) { deletePreferences(context: Context, name: string): Promise<void> -Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory. -Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the result. +Deletes a **Preferences** instance from the memory. This API uses a promise to return the result. + +If the **Preferences** instance has a persistent file, this API also deletes the persistent file. + +The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = data_preferences.deletePreferences(this.context, 'mystore') promise.then(() => { - console.info("Deleted preferences successfully.") + console.info("Deleted the preferences successfully."); }).catch((err) => { - console.info("Failed to delete preferences, err: " + err) + console.info("Failed to delete the preferences. Cause: " + err); }) ``` @@ -144,27 +159,27 @@ promise.then(() => { removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void -Removes a **Preferences** singleton instance from the memory. +Removes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result. -When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result. +The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to remove. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { if (err) { - console.info("Failed to remove preferences from cache, err: " + err) - return + console.info("Failed to remove the preferences. Cause: " + err); + return; } - console.info("Removed preferences from cache successfully.") + console.info("Removed the preferences successfully."); }) ``` @@ -173,62 +188,65 @@ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (e removePreferencesFromCache(context: Context, name: string): Promise<void> -Removes a **Preferences** singleton instance from the memory. +Removes a **Preferences** instance from the memory. This API uses a promise to return the result. -When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the execution result. +The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') promise.then(() => { - console.info("Removed preferences from cache successfully.") + console.info("Removed the preferences successfully."); }).catch((err) => { - console.info("Failed to remove preferences from cache, err: " + err) + console.info("Failed to remove the preferences. Cause: " + err); }) ``` ## Preferences -Provides APIs for obtaining and modifying storage data. +Provides methods for obtaining and modifying data. + +Before calling any method of **Preferences**, you must obtain a **Preferences** instance by using [data_preferences.getPreferences](#data_preferencesgetpreferences). ### get get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void -Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses an asynchronous callback to return the result. +Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not the type of the default value, the default value is returned. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to obtain. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. -| callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<[ValueType](#valuetype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is** undefined** and **data** is the value obtained. Otherwise, **err** is an error code.| **Example** -```ts -preferences.get('startup', 'default', function(err, value) { + +```js +preferences.get('startup', 'default', function(err, data) { if (err) { - console.info("Failed to get the value of startup, err: " + err) - return + console.info("Failed to get the value of 'startup'. Cause: " + err); + return; } - console.info("The value of startup is " + value) + console.info("Got the value of 'startup'. Data: " + data); }) ``` @@ -237,28 +255,29 @@ preferences.get('startup', 'default', function(err, value) { get(key: string, defValue: ValueType): Promise<ValueType> -Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses a promise to return the result. +Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not the type of the default value, the default value is returned. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. + **Parameters** +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** -```ts -let promise = preferences.get('startup', 'default') -promise.then((value) => { - console.info("The value of startup is " + value) +```js +let promise = preferences.get('startup', 'default'); +promise.then((data) => { + console.info("Got the value of 'startup'. Data: " + data); }).catch((err) => { - console.info("Failed to get the value of startup, err: " + err) + console.info("Failed to get the value of 'startup'. Cause: " + err); }) ``` @@ -266,25 +285,26 @@ promise.then((value) => { getAll(callback: AsyncCallback<Object>): void; -Obtains the **Object** instance that contains all KV pairs. +Obtains an **Object** instance that contains all KV pairs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| **Example** -```ts + +```js preferences.getAll(function (err, value) { if (err) { - console.info("getAll failed, err: " + err) - return + console.info("Failed to get all KV pairs. Cause: " + err); + return; } - let keys = Object.keys(value) - console.info('getAll keys = ' + keys) - console.info("getAll object = " + JSON.stringify(value)) + let allKeys = Object.keys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }); ``` @@ -293,24 +313,24 @@ preferences.getAll(function (err, value) { getAll(): Promise<Object> -Obtains the **Object** instance that contains all KV pairs. +Obtains an **Object** instance that contains all KV pairs. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Object> | Promise used to return the **Object** instance obtained.| +| Type | Description | +| --------------------- | ------------------------------------------- | +| Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** -```ts -let promise = preferences.getAll() +```js +let promise = preferences.getAll(); promise.then((value) => { - let keys = Object.keys(value) - console.info('getAll keys = ' + keys) - console.info("getAll object = " + JSON.stringify(value)) + let allKeys = Object.keys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }).catch((err) => { - console.info("getAll failed, err: " + err) + console.info("Failed to get all KV pairs. Cause: " + err); }) ``` @@ -318,25 +338,25 @@ promise.then((value) => { put(key: string, value: ValueType, callback: AsyncCallback<void>): void -Puts a new value to this **Preferences** instance and its persistence file. This API uses an asynchronous callback to return the result. +Writes data to this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** -```ts +```js preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }) ``` @@ -345,28 +365,28 @@ preferences.put('startup', 'auto', function (err) { put(key: string, value: ValueType): Promise<void> -Puts a new value to this **Preferences** instance and its persistence file. This API uses a promise to return the result. +Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.put('startup', 'auto') +```js +let promise = preferences.put('startup', 'auto'); promise.then(() => { - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to put the value of startup, err: " + err) + console.info("Failed to put the value of 'startup'. Cause: " + err); }) ``` @@ -375,27 +395,27 @@ promise.then(() => { has(key: string, callback: AsyncCallback<boolean>): void -Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result. +Checks whether this **Preferences** instance contains a KV pair of the given key. This API uses an asynchronous callback to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to check. It cannot be empty. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** -```ts +```js preferences.has('startup', function (err, isExist) { if (err) { - console.info("Failed to check the key of startup, err: " + err) - return + console.info("Failed to check the key 'startup'. Cause: " + err); + return; } if (isExist) { - console.info("The key of startup is contained.") + console.info("The key 'startup' is contained."); } else { - console.info("The key of startup is not contained.") + console.info("The key 'startup' is not contained."); } }) ``` @@ -405,31 +425,32 @@ preferences.has('startup', function (err, isExist) { has(key: string): Promise<boolean> -Checks whether this **Preferences** instance contains data with a given key. This API uses a promise to return the result. +Checks whether this **Preferences** instance contains data with the given key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** -```ts -let promise = preferences.has('startup') + +```js +let promise = preferences.has('startup'); promise.then((isExist) => { if (isExist) { - console.info("The key of startup is contained.") + console.info("The key 'startup' is contained."); } else { - console.info("The key of startup is not contained.") + console.info("The key 'startup' is not contained."); } }).catch((err) => { - console.info("Failed to check the key of startup, err: " + err) + console.info("Failed to check the key 'startup'. Cause: " + err); }) ``` @@ -438,24 +459,24 @@ promise.then((isExist) => { delete(key: string, callback: AsyncCallback<void>): void -Deletes a KV pair of the specified key from this **Preferences** instance. This API uses an asynchronous callback to return the result. +Deletes a KV pair from this **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.delete('startup', function (err) { if (err) { - console.info("Failed to delete startup key, err: " + err) - return + console.info("Failed to delete the key 'startup'. Cause: " + err); + return; } - console.info("Deleted startup key successfully.") + console.info("Deleted the key 'startup'."); }) ``` @@ -464,27 +485,27 @@ preferences.delete('startup', function (err) { delete(key: string): Promise<void> -Deletes a KV pair of the specified key from this **Preferences** instance. This API uses a promise to return the result. +Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.delete('startup') +```js +let promise = preferences.delete('startup'); promise.then(() => { - console.info("Deleted startup key successfully.") + console.info("Deleted the key 'startup'."); }).catch((err) => { - console.info("Failed to delete startup key, err: " + err) + console.info("Failed to delete the key 'startup'. Cause: " + err); }) ``` @@ -493,23 +514,23 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses an asynchronous callback to return the result. +Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") + console.info("Flushed data successfully."); }) ``` @@ -518,22 +539,22 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses a promise to return the result. +Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.flush() +```js +let promise = preferences.flush(); promise.then(() => { console.info("Flushed data to file successfully.") }).catch((err) => { - console.info("Failed to flush data to file, err: " + err) + console.info("Failed to flush data. Cause: " + err); }) ``` @@ -542,23 +563,23 @@ promise.then(() => { clear(callback: AsyncCallback<void>): void -Clears data of this **Preferences** instance. This API uses an asynchronous callback to return the result. +Clears this **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.clear(function (err) { if (err) { - console.info("Failed to clear data, err: " + err) - return + console.info("Failed to clear data. Cause: " + err); + return; } - console.info("Cleared to file successfully.") + console.info("Cleared data successfully."); }) ``` @@ -567,22 +588,22 @@ preferences.clear(function (err) { clear(): Promise<void> -Clears data of this **Preferences** instance. This API uses a promise to return the result. +Clears this **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = preferences.clear() promise.then(() => { - console.info("Cleared to file successfully.") + console.info("Cleared data successfully."); }).catch((err) => { - console.info("Failed to clear data, err: " + err) + console.info("Failed to clear data. Cause: " + err); }) ``` @@ -591,40 +612,40 @@ promise.then(() => { on(type: 'change', callback: Callback<{ key : string }>): void -Subscribes to data changes. When the value of the subscribed key changes, a callback will be invoked after **flush()** is executed. +Subscribes to data changes. A callback will be triggered to return the new value if the value of the subscribed key is changed and [flushed](#flush). **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** -```ts +```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences.") + console.info("Failed to get the preferences."); return; } var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key " + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) }) }) @@ -640,37 +661,37 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | +| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| **Example** -```ts +```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences.") + console.info("Failed to get preferences."); return; } var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key " + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) - preferences.off('change', observer) + preferences.off('change', observer); }) }) ``` @@ -681,11 +702,11 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Type | Description | -| -------------- | ------------------------------ | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type. | +| Type | Description | +| --------------- | ------------------------------ | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | | Array\ | The value is an array of numbers. | | Array\ | The value is a Boolean array. | | Array\ | The value is an array of the strings.| diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index b2dbdfdccbb0b42259da73235976a6cd320daba7..9d51475957c8e9c891980c0d42880a6b1db649de 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -89,9 +89,9 @@ Enumerates the device states. | Name | Default Value | Description | | ------- | ---- | --------------- | -| ONLINE | 0 | The device is online. | -| READY | 1 | The device is ready, and the device information has been synchronized.| -| OFFLINE | 2 | The device is offline. | +| ONLINE | 0 | The device is physically online. | +| READY | 1 | The information between devices has been synchronized in the Distributed Data Service (DDS) module, and the device is ready for running distributed services.| +| OFFLINE | 2 | The device is physically offline. | | CHANGE | 3 | The device information is changed. | ## SubscribeInfo 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-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-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index c684f0ea4f3c4cdd77de4e189b00e15f41a82855..9f1110f241e37530914961c21f688e67d44b05af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -2,7 +2,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. -> ![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. @@ -12,75 +12,210 @@ This module provides the application event logging functions, such as writing ap import hiAppEvent from '@ohos.hiAppEvent'; ``` +## How to Use -## hiAppEvent.write +Before using application event logging, you need to understand the requirements for related parameters. + +**Event Domain** + +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). + +**Event Name** + +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). + +**Event Type** + +An event type is an enumerated value of [EventType](#eventtype). + +**Event Parameter** + +An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: + +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter value is a string, number, boolean, or array. +- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. +- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. +- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded. + +**Event Callback** + +Event callback can be a callback or promise that carries the return value obtained by invoking the event logging API. You can add the processing of the return value in the event callback as follows: + +- If the return value is **0**, the event verification is successful, and the event will be directly written to the event file. +- If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored. +- If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file. + +**Subscription Callback** + +A subscription callback carries the subscription data obtained by invoking the watcher API. The input parameters are defined as follows: + +- **curRow**: number of events. +- **curSize**: event data size, in bytes. +- **holder**: event data holder, which can be used for processing subscription events. + +## hiAppEvent.write(deprecated) write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -Writes event information to the event file of the current day. This API supports JSON parameters and uses an asynchronous callback to return the result. +> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9) instead. + +Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. | -| eventType | [EventType](#eventtype) | Yes | Application event type. | -| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated. | -| callback | AsyncCallback<void> | No | Callback used to process the received return value.
-  Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously.
-  A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
-  A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file. | +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------- | +| eventName | string | Yes | Event name. | +| eventType | [EventType](#eventtype) | Yes | Event type. | +| keyValues | object | Yes | Event parameters. | +| callback | AsyncCallback<void> | No | Event callback.| **Example** ```js hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { if (err) { - // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. console.error(`failed to write event because ${err.code}`); return; } - // Event writing succeeded. + // Event writing success console.log(`success to write event: ${value}`); }); ``` -## hiAppEvent.write +## hiAppEvent.write(deprecated) write(eventName: string, eventType: EventType, keyValues: object): Promise<void> -Writes event information to the event file of the current day. This API supports JSON parameters and uses a promise to return the result. +> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9-1) instead. + +Writes event information to the event file of the current day. This API uses a promise to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------------------------------------------------------ | -| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. | -| eventType | [EventType](#eventtype) | Yes | Application event type. | -| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------- | +| eventName | string | Yes | Event name.| +| eventType | [EventType](#eventtype) | Yes | Event type.| +| keyValues | object | Yes | Event parameters.| **Return value** | Type | Description | | ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed. | +| Promise<void> | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.| **Example** ```js hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) .then((value) => { - // Event writing succeeded. + // Event writing success console.log(`success to write event: ${value}`); }).catch((err) => { - // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. console.error(`failed to write event because ${err.code}`); }); ``` +## hiAppEvent.write9+ + +write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback<void>): void + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| +| callback | AsyncCallback<void> | No | Event callback.| + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}, (err, value) => { + if (err) { + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Event writing success + console.log(`success to write event: ${value}`); +}); +``` + +## hiAppEvent.write9+ + +write(info: [AppEventInfo](#appeventinfo9)): Promise<void> + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.| + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}).then((value) => { + // Event writing success + console.log(`success to write event: ${value}`); +}).catch((err) => { + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); +}); +``` + +## AppEventInfo9+ + +Defines parameters for an **AppEventInfo** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------- | +| domain | string | Yes | Event domain.| +| name | string | Yes | Event name.| +| eventType | [EventType](#eventtype) | Yes | Event type.| +| params | object | Yes | Event parameters.| ## hiAppEvent.configure @@ -94,15 +229,16 @@ Configures the application event logging function, such as setting the event log | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | ------------------------ | -| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging. | +| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| **Return value** | Type | Description | | ------- | ----------------------------------------------------------- | -| boolean | Returns **true** if the configuration is successful; returns **false** otherwise. | +| boolean | Returns **true** if the configuration is successful; returns **false** otherwise.| **Example** + ```js // Set the application event logging switch. hiAppEvent.configure({ @@ -115,7 +251,6 @@ hiAppEvent.configure({ }); ``` - ## ConfigOption Provides the configuration items for application event logging. @@ -124,8 +259,205 @@ Provides the configuration items for application event logging. | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------------------------------------ | -| disable | boolean | No | Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite. | -| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space. | +| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.| +| maxStorage | string | No | Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| + +## hiAppEvent.addWatcher9+ + +addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9) + +Adds an event watcher. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher9) | Yes | Event watcher.| + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ------------------------------------ | +| [AppEventPackageHolder](#appeventpackageholder9) | Subscription data holder. If the subscription fails, **null** will be returned.| + +**Example** + +```js +// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered. +hiAppEvent.addWatcher({ + name: "watcher1", + appEventFilters: [ + { + domain: "domain_test1", + eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] + } + ], + triggerCondition: { + row: 10, + size: 1000, + timeOut: 1 + }, + onTrigger: function (curRow, curSize, holder) { + if (holder == null) { + console.error("holder is null"); + return; + } + while (true) { + let eventPkg = holder.takeNext(); + if (eventPkg == null) { + return; + } + console.info("eventPkg.packageId=" + eventPkg.packageId); + console.info("eventPkg.row=" + eventPkg.row); + console.info("eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("eventPkg.data=" + eventInfo); + } + } + } +}); + +// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder. +let holder = hiAppEvent.addWatcher({ + name: "watcher2", +}); +if (holder != null) { + let eventPkg = holder.takeNext(); + if (eventPkg == null) { + return; + } + console.info("eventPkg.packageId=" + eventPkg.packageId); + console.info("eventPkg.row=" + eventPkg.row); + console.info("eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("eventPkg.data=" + eventInfo); + } +} +``` + +## hiAppEvent.removeWatcher9+ + +removeWatcher(watcher: [Watcher](#watcher9)): void + +Removes an event watcher. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher9) | Yes | Event watcher.| + +**Example** + +```js +// 1. Define a watcher. +let watcher = { + name: "watcher1", +} + +// 2. Add the watcher to subscribe to application events. +hiAppEvent.addWatcher(watcher); + +// 3. Remove the watcher to unsubscribe from application events. +hiAppEvent.removeWatcher(watcher); +``` + +## Watcher9+ + +Defines parameters for a **Watcher** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- | +| name | string | Yes | Unique watcher name.| +| triggerCondition | [TriggerCondition](#triggercondition9) | No | Subscription callback trigger condition. | +| appEventFilters | [AppEventFilter](#appeventfilter9)[] | No | Application event filter criteria. | +| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | No | Subscription callback. | + +## TriggerCondition9+ + +Defines parameters for a **TriggerCondition** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | -------------------------------------- | +| row | number | No | Number of events. | +| size | number | No | Event data size, in bytes.| +| timeOut | number | No | Timeout interval, in unit of 30s. | + +## AppEventFilter9+ + +Defines parameters for an **AppEventFilter** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------ | +| domain | string | Yes | Event domain. | +| eventTypes | [EventType](#eventtype)[] | No | Event types.| + +## AppEventPackageHolder9+ + +Defines a subscription data holder for processing subscription events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +### setSize9+ + +setSize(size: number): void + +Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. + +**Example** + +```js +holder.setSize(1000); +``` + +### takeNext9+ + +takeNext(): [AppEventPackage](#appeventpackage9) + +Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. + +**Example** + +```js +let eventPkg = holder.takeNext(); +``` + +## AppEventPackage9+ + +Defines parameters for an **AppEventPackage** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Description | +| --------- | -------- | ------------------------------ | +| packageId | number | Event package ID, which is named from **0** in ascending order. | +| row | number | Number of events in the event package. | +| size | number | Data size of the event package, in bytes.| +| data | string[] | Event data in the event package. | + +## hiAppEvent.clearData9+ + +clearData(): void + +Clears local logging data. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +hiAppEvent.clearData(); +``` ## EventType @@ -136,10 +468,10 @@ Enumerates event types. | Name | Default Value| Description | | --------- | ------ | -------------- | -| FAULT | 1 | Fault event| -| STATISTIC | 2 | Statistical event| -| SECURITY | 3 | Security event| -| BEHAVIOR | 4 | Behavior event| +| FAULT | 1 | Fault event.| +| STATISTIC | 2 | Statistical event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | Behavior event.| ## Event @@ -152,7 +484,7 @@ Provides constants that define the names of all predefined events. | ------------------------- | -------- | ---- | ---- | -------------------- | | USER_LOGIN | string | Yes | No | User login event. | | USER_LOGOUT | string | Yes | No | User logout event. | -| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| ## Param @@ -161,8 +493,8 @@ Provides constants that define the names of all predefined event parameters. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type | Readable | Writable | Description | +| Name | Type| Readable| Writable| Description | | ------------------------------- | -------- | ---- | ---- | ------------------ | | USER_ID | string | Yes | No | Custom user ID. | -| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID. | \ No newline at end of file +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index e856ee20a4c8956ff0f05707b596935b68ca9e7a..04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,8 +1,9 @@ # Performance Tracing -This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; startTrace(name: string, taskId: number): void -Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. +Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index a21e4ddb660cba43fef79e5e509464eca986aea9..b68a5b15487f310dd6b05058c68af75840098062 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -676,7 +676,7 @@ Formats a phone number. ### getLocationName9+ -static getLocationName(number: string, locale: string): string +getLocationName(number: string, locale: string): string Obtains the home location of a phone number. 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-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 1e9fa33963ed6eb07302ddfbb9db44973e9be4d4..2f6cd9a66dcd1a5dcd1d92e126461e307643814f 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover Generally, only system applications have the permission to subscribe to and unsubscribe from notifications. -> **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. @@ -24,10 +24,10 @@ Publishes a notification. This API uses an asynchronous callback to return the r **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | ---- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -61,6 +61,12 @@ Publishes a notification. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| + **Example** ```js @@ -96,11 +102,11 @@ Publishes a notification. This API uses an asynchronous callback to return the r **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| userId | Yes | No |number | Yes | ID of the user who receives the notification. | -| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| +| userId | number | Yes | ID of the user who receives the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -140,10 +146,10 @@ Publishes a notification. This API uses a promise to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| userId | Yes | No |number | Yes | ID of the user who receives the notification. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| +| userId | number | Yes | ID of the user who receives the notification. | **Example** @@ -178,11 +184,11 @@ Cancels a notification with the specified ID and label. This API uses an asynchr **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | --------------------- | ---- | -------------------- | -| id | Yes | No | number | Yes | Notification ID. | -| label | Yes | No | string | Yes | Notification label. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| id | number | Yes | Notification ID. | +| label | string | Yes | Notification label. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -206,10 +212,10 @@ Cancels a notification with the specified ID and label. This API uses a promise **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | ------ | ---- | -------- | -| id | Yes | No | number | Yes | Notification ID. | -| label | Yes | No | string | No | Notification label.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | -------- | +| id | number | Yes | Notification ID. | +| label | string | No | Notification label.| **Example** @@ -231,10 +237,10 @@ Cancels a notification with the specified ID. This API uses an asynchronous call **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| id | Yes | No | number | Yes | Notification ID. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| id | number | Yes | Notification ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -258,9 +264,9 @@ Cancels all notifications. This API uses an asynchronous callback to return the **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -306,10 +312,10 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -341,9 +347,9 @@ Adds a notification slot. This API uses a promise to return the result. **Parameters** -| Name| Readable| Writable| Type | Mandatory| Description | -| ---- | ---- | --- | ---------------- | ---- | -------------------- | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| Name| Type | Mandatory| Description | +| ---- | ---------------- | ---- | -------------------- | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| **Example** @@ -369,10 +375,10 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ---------------------- | -| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| type | [SlotType](#slottype) | Yes | Type of the notification slot to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -396,9 +402,9 @@ Adds a notification slot. This API uses a promise to return the result. **Parameters** -| Name| Readable| Writable| Type | Mandatory| Description | -| ---- | ---- | --- | -------- | ---- | ---------------------- | -| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| +| Name| Type | Mandatory| Description | +| ---- | -------- | ---- | ---------------------- | +| type | [SlotType](#slottype) | Yes | Type of the notification slot to add.| **Example** @@ -424,10 +430,10 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------- | ---- | ------------------------ | -| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -463,9 +469,9 @@ Adds multiple notification slots. This API uses a promise to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | ---- | --- | ------------------------- | ---- | ------------------------ | -| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| Name | Type | Mandatory| Description | +| ----- | ------------------------- | ---- | ------------------------ | +| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| **Example** @@ -495,10 +501,10 @@ Obtains a notification slot of the specified type. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------------------- | ---- | ----------------------------------------------------------- | -| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | **Example** @@ -523,9 +529,9 @@ Obtains a notification slot of the specified type. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | -| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| **Return value** @@ -554,9 +560,9 @@ Obtains all notification slots. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------------------- | ---- | -------------------- | -| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | -------------------- | +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| **Example** @@ -604,10 +610,10 @@ Removes a notification slot of the specified type. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ----------------------------------------------------------- | -| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -632,9 +638,9 @@ Removes a notification slot of the specified type. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | -| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| **Example** @@ -657,9 +663,9 @@ Removes all notification slots. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -704,11 +710,11 @@ Subscribes to a notification with the subscription information specified. This A **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | ---- | --- | ------------------------- | ---- | ---------------- | -| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | -| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Subscription information. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Subscription information. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -745,10 +751,10 @@ Subscribes to a notification with the subscription information specified. This A **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | ---- | --- | ---------------------- | ---- | ---------------- | -| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | ---------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -781,10 +787,10 @@ Subscribes to a notification with the subscription information specified. This A **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | ---- | --- | ------------------------- | ---- | ------------ | -| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| -| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Subscription information. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------ | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Subscription information. | **Example** @@ -816,10 +822,10 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | ---- | --- | ---------------------- | ---- | -------------------- | -| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | -------------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -852,9 +858,9 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | ---- | --- | ---------------------- | ---- | ------------ | -| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | ------------ | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| **Example** @@ -886,11 +892,11 @@ Sets whether to enable notification for a specified bundle. This API uses an asy **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| enable | Yes | No | boolean | Yes | Whether to enable notification. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | boolean | Yes | Whether to enable notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -920,10 +926,10 @@ Sets whether to enable notification for a specified bundle. This API uses a prom **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | boolean | Yes | Whether to enable notification. | **Example** @@ -952,10 +958,10 @@ Checks whether notification is enabled for a specified bundle. This API uses an **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ------------------------ | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -985,9 +991,9 @@ Checks whether notification is enabled for a specified bundle. This API uses a p **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| **Return value** @@ -1022,9 +1028,9 @@ Checks whether notification is enabled for this application. This API uses an as **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ------------------------ | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1052,9 +1058,9 @@ Checks whether notification is enabled for this application. This API uses a pro **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| **Return value** @@ -1086,11 +1092,11 @@ Sets whether to enable the notification badge for a specified bundle. This API u **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| enable | Yes | No | boolean | Yes | Whether to enable notification. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | boolean | Yes | Whether to enable notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1120,10 +1126,10 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | boolean | Yes | Whether to enable notification. | **Example** @@ -1152,10 +1158,10 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ------------------------ | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1185,9 +1191,9 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| **Return value** @@ -1222,11 +1228,11 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1259,10 +1265,10 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Whether to enable notification. | +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| slot | [NotificationSlot](#notificationslot) | Yes | Whether to enable notification. | **Example** @@ -1294,10 +1300,10 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ---------------------------------------- | ---- | -------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Example** @@ -1327,9 +1333,9 @@ Obtains the notification slots of a specified bundle. This API uses a promise to **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| **Return value** @@ -1364,10 +1370,10 @@ Obtains the number of notification slots of a specified bundle. This API uses an **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------- | ---- | ---------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1397,9 +1403,9 @@ Obtains the number of notification slots of a specified bundle. This API uses a **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| **Return value** @@ -1434,11 +1440,11 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------------- | ---- | --- | ----------------------------------- | ---- | -------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1472,10 +1478,10 @@ Removes a notification for a specified bundle. This API uses a promise to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------------- | ---- | --- | --------------- | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | +| Name | Type | Mandatory| Description | +| --------------- | --------------- | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | **Example** @@ -1508,10 +1514,10 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| hashCode | Yes | No | string | Yes | Unique notification ID. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| hashCode | string | Yes | Unique notification ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1541,9 +1547,9 @@ Removes a notification for a specified bundle. This API uses a promise to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ---------- | ---- | ---------- | -| hashCode | Yes | No | string | Yes | Unique notification ID.| +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | ---------- | +| hashCode | string | Yes | Unique notification ID.| **Example** @@ -1571,10 +1577,10 @@ Removes all notifications for a specified bundle. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ---------------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1604,9 +1610,9 @@ Removes all notifications. This API uses an asynchronous callback to return the **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | -------------------- | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1634,9 +1640,9 @@ Removes all notifications for a specified user. This API uses a promise to retur **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | No | Bundle information.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | No | Bundle information.| **Example** @@ -1660,10 +1666,10 @@ Removes all notifications for a specified user. This API uses an asynchronous ca **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| userId | Yes | No | number | Yes | ID of the user who receives the notification.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| userId | number | Yes | ID of the user who receives the notification.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1691,9 +1697,9 @@ Removes all notifications for a specified user. This API uses a promise to retur **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------------ | ---- | ---------- | -| userId | Yes | No | number | Yes | ID of the user who receives the notification.| +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| userId | number | Yes | ID of the user who receives the notification.| **Example** @@ -1722,9 +1728,9 @@ Obtains all active notifications. This API uses an asynchronous callback to retu **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------------------------------------------ | ---- | -------------------- | -| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------- | +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Example** @@ -1748,7 +1754,7 @@ Obtains all active notifications. This API uses a promise to return the result. **Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER -**System API**: This is a system API and cannot be called by third-party applications.removeGroupByBundle +**System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -1776,9 +1782,9 @@ Obtains the number of active notifications. This API uses an asynchronous callba **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ---------------------- | ---- | ---------------------- | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1826,9 +1832,9 @@ Obtains active notifications of this application. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------------------ | -| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return the result.| **Example** @@ -1876,10 +1882,10 @@ Cancels a notification group of this application. This API uses an asynchronous **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | -| groupName | Yes | No | string | Yes | Name of the notification group. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------- | +| groupName | string | Yes | Name of the notification group. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1905,9 +1911,9 @@ Cancels a notification group of this application. This API uses a promise to ret **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------- | ---- | --- | ------ | ---- | -------------- | -| groupName | Yes | No | string | Yes | Name of the notification group.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------- | +| groupName | string | Yes | Name of the notification group.| **Example** @@ -1934,11 +1940,11 @@ Removes a notification group for a specified bundle. This API uses an asynchrono **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| groupName | Yes | No | string | Yes | Name of the notification group. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | string | Yes | Name of the notification group. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1969,10 +1975,10 @@ Removes a notification group for a specified bundle. This API uses a promise to **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| --------- | ---- | --- | ------------ | ---- | -------------- | -| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | -| groupName | Yes | No | string | Yes | Name of the notification group.| +| Name | Type | Mandatory| Description | +| --------- | ------------ | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | string | Yes | Name of the notification group.| **Example** @@ -2000,10 +2006,10 @@ Sets the DND time. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ---------------------- | -| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2037,9 +2043,9 @@ Sets the DND time. This API uses a promise to return the result. **Parameters** -| Name| Readable| Writable| Type | Mandatory| Description | -| ---- | ---- | --- | ---------------- | ---- | -------------- | -| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| Name| Type | Mandatory| Description | +| ---- | ---------------- | ---- | -------------- | +| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| **Example** @@ -2069,11 +2075,11 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------- | ---- | ---------------------- | -| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | -| userId | Yes | No | number | Yes | User ID.| -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2109,10 +2115,10 @@ Sets the DND time for a specified user. This API uses a promise to return the re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ---------------- | ---- | -------------- | -| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| -| userId | Yes | No | number | Yes | User ID.| +| Name | Type | Mandatory| Description | +| ------ | ---------------- | ---- | -------------- | +| date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| userId | number | Yes | User ID.| **Example** @@ -2145,9 +2151,9 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | -| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| **Example** @@ -2202,10 +2208,10 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | -| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| -| userId | Yes | No | number | Yes | User ID.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| userId | number | Yes | User ID.| **Example** @@ -2235,9 +2241,9 @@ Obtains the DND time of a specified user. This API uses a promise to return the **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | -| userId | Yes | No | number | Yes | User ID.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| userId | number | Yes | User ID.| **Return value** @@ -2270,9 +2276,9 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------ | ---- | -------------------------------- | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2836,10 +2842,13 @@ Cancels a notification published by the reminder agent. This API uses an asynchr **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER -**Parameters** +**System API**: This is a system API and cannot be called by third-party applications. +**Parameters** | Name | Type | Mandatory| Description | | -------------------- | ------------- | ---- | ------------------------ | @@ -2871,10 +2880,13 @@ Publishes a notification through the reminder agent. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER -**Parameters** +**System API**: This is a system API and cannot be called by third-party applications. +**Parameters** | Name | Type | Mandatory| Description | | -------------------- | ------ | ---- | ------------------ | @@ -3035,9 +3047,9 @@ Notification.isNotificationSlotEnabled( ``` -## Notification.setSyncNotificationEnabledForUninstallApp9+ +## Notification.setSyncNotificationEnabledWithoutApp9+ -setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean, callback: AsyncCallback\): void +setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void Sets whether to sync notifications to devices where the application is not installed. This API uses an asynchronous callback to return the result. @@ -3052,8 +3064,8 @@ Sets whether to sync notifications to devices where the application is not insta | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether to sync notifications to devices where the application is not installed. The value **true** means to sync notifications to devices where the application is not installed, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| enable | boolean | Yes | Whether the feature is enabled.
**true**: enabled
**false**: disabled | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -3061,17 +3073,17 @@ Sets whether to sync notifications to devices where the application is not insta let userId = 100; let enable = true; -function setSyncNotificationEnabledForUninstallAppCallback(err) { - console.log('setSyncNotificationEnabledForUninstallAppCallback'); +function setSyncNotificationEnabledWithoutAppCallback(err) { + console.log('setSyncNotificationEnabledWithoutAppCallback'); } -Notification.setSyncNotificationEnabledForUninstallApp(userId, enable, setSyncNotificationEnabledForUninstallAppCallback); +Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); ``` -## Notification.setSyncNotificationEnabledForUninstallApp9+ +## Notification.setSyncNotificationEnabledWithoutApp9+ -setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean): Promise\ +setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ Sets whether to sync notifications to devices where the application is not installed. This API uses a promise to return the result. @@ -3086,7 +3098,13 @@ Sets whether to sync notifications to devices where the application is not insta | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether to sync notifications to devices where the application is not installed. The value **true** means to sync notifications to devices where the application is not installed, and **false** means the opposite.| +| enable | boolean | Yes | Whether the feature is enabled.
**true**: enabled
**false**: disabled | + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| **Example** @@ -3094,21 +3112,21 @@ Sets whether to sync notifications to devices where the application is not insta let userId = 100; let enable = true; -Notification.setSyncNotificationEnabledForUninstallApp(userId, enable) +Notification.setSyncNotificationEnabledWithoutApp(userId, enable) .then((data) => { - console.log('setSyncNotificationEnabledForUninstallApp, data:', data); + console.log('setSyncNotificationEnabledWithoutApp'); }) .catch((err) => { - console.log('setSyncNotificationEnabledForUninstallApp, err:', err); + console.log('setSyncNotificationEnabledWithoutApp, err:', err); }); ``` -## Notification.getSyncNotificationEnabledForUninstallApp9+ +## Notification.getSyncNotificationEnabledWithoutApp9+ -getSyncNotificationEnabledForUninstallApp(userId: number, callback: AsyncCallback\): void +getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void -Checks whether notifications are synced to devices where the application is not installed. This API uses an asynchronous callback to return the result. +Obtains whether notifications are synced to devices where the application is not installed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3121,26 +3139,30 @@ Checks whether notifications are synced to devices where the application is not | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that notifications are synced to devices where the application is not installed, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Notifications are synced to devices where the application is not installed.
**false**: Notifications are not synced to devices where the application is not installed.| **Example** ```js let userId = 100; -function getSyncNotificationEnabledForUninstallAppCallback(err, data) { - console.log('getSyncNotificationEnabledForUninstallAppCallback, data: ', data); +function getSyncNotificationEnabledWithoutAppCallback(data, err) { + if (err) { + console.log('getSyncNotificationEnabledWithoutAppCallback, err' + err); + } else { + console.log('getSyncNotificationEnabledWithoutAppCallback, data' + data); + } } -Notification.getSyncNotificationEnabledForUninstallApp(userId, getSyncNotificationEnabledForUninstallAppCallback); +Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEnabledWithoutAppCallback); ``` -## Notification.getSyncNotificationEnabledForUninstallApp9+ +## Notification.getSyncNotificationEnabledWithoutApp9+ -getSyncNotificationEnabledForUninstallApp(userId: number): Promise\ +getSyncNotificationEnabledWithoutApp(userId: number): Promise\ -Checks whether notifications are synced to devices where the application is not installed. This API uses a promise to return the result. +Obtains whether notifications are synced to devices where the application is not installed. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3158,19 +3180,19 @@ Checks whether notifications are synced to devices where the application is not | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. The value **true** means that notifications are synced to devices where the application is not installed, and **false** means the opposite.| +| Promise\ | Promise used to return the result.
**true**: Notifications are synced to devices where the application is not installed.
**false**: Notifications are not synced to devices where the application is not installed.| **Example** ```js let userId = 100; -Notification.getSyncNotificationEnabledForUninstallApp(userId) +Notification.getSyncNotificationEnabledWithoutApp(userId) .then((data) => { - console.log('getSyncNotificationEnabledForUninstallApp, data: ', data); + console.log('getSyncNotificationEnabledWithoutApp, data:', data); }) .catch((err) => { - console.log('getSyncNotificationEnabledForUninstallApp, err: ', err); + console.log('getSyncNotificationEnabledWithoutApp, err:', err); }); ``` @@ -3487,13 +3509,13 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Mandatory| Description | -| --------------- | ---- | --- | ------------------------------------------------- | ---- | -------- | -| request | Yes | No | [NotificationRequest](#notificationrequest) | Yes | Notification content.| -| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | No | Notification sorting information.| -| reason | Yes | No | number | No | Reason for deletion.| -| sound | Yes | No | string | No | Sound used for notification.| -| vibrationValues | Yes | No | Array\ | No | Vibration used for notification.| +| Name | Readable| Writable| Type | Description | +| --------------- | ---- | --- | ------------------------------------------------- | -------- | +| request | Yes | No | [NotificationRequest](#notificationrequest) | Notification content.| +| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | Notification sorting information.| +| reason | Yes | No | number | Reason for deletion.| +| sound | Yes | No | string | Sound used for notification.| +| vibrationValues | Yes | No | Array\ | Vibration used for notification.| ## EnabledNotificationCallbackData8+ @@ -3502,11 +3524,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------- | ---- | ---------------- | -| bundle | Yes | No | string | Yes | Bundle name of the application. | -| uid | Yes | No | number | Yes | UID of the application. | -| enable | Yes | No | boolean | Yes | Notification enabled status of the application.| +| Name | Readable| Writable| Type | Description | +| ------ | ---- | --- | ------- | ---------------- | +| bundle | Yes | No | string | Bundle name of the application. | +| uid | Yes | No | number | UID of the application. | +| enable | Yes | No | boolean | Notification enabled status of the application.| ## DoNotDisturbDate8+ @@ -3566,10 +3588,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ------ | ---- | --- | ------ | ---- | ------ | -| bundle | Yes | Yes | string | Yes | Bundle name. | -| uid | Yes | Yes | number | No | User ID.| +| Name | Readable| Writable| Type | Description | +| ------ | ---- | --- | ------ | ------ | +| bundle | Yes | Yes | string | Bundle name. | +| uid | Yes | Yes | number | User ID.| @@ -3577,10 +3599,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | ---- | --- | ------ | ---- | -------- | -| id | Yes | Yes | number | Yes | Notification ID. | -| label | Yes | Yes | string | No | Notification label.| +| Name | Readable| Writable| Type | Description | +| ----- | ---- | --- | ------ | -------- | +| id | Yes | Yes | number | Notification ID. | +| label | Yes | Yes | string | Notification label.| ## SlotType @@ -3600,78 +3622,78 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| --------- | --- | ---- | ----------------------------------------------- | ---- | ------------------------- | -| title | Yes | Yes | string | Yes | Button title. | -| wantAgent | Yes | Yes | WantAgent | Yes | **WantAgent** of the button.| -| extras | Yes | Yes | { [key: string]: any } | No | Extra information of the button. | -| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | No | User input object. | +| Name | Readable| Writable| Type | Description | +| --------- | --- | ---- | ----------------------------------------------- | ------------------------- | +| title | Yes | Yes | string | Button title. | +| wantAgent | Yes | Yes | WantAgent | **WantAgent** of the button.| +| extras | Yes | Yes | { [key: string]: any } | Extra information of the button. | +| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | User input object. | ## NotificationBasicContent **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | ---- | ---- | ------ | ---- | ---------------------------------- | -| title | Yes | Yes | string | Yes | Notification title. | -| text | Yes | Yes | string | Yes | Notification content. | -| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| Name | Readable| Writable| Type | Description | +| -------------- | ---- | ---- | ------ | ---------------------------------- | +| title | Yes | Yes | string | Notification title. | +| text | Yes | Yes | string | Notification content. | +| additionalText | Yes | Yes | string | Additional information of the notification.| ## NotificationLongTextContent **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | ---- | --- | ------ | ---- | -------------------------------- | -| title | Yes | Yes | string | Yes | Notification title. | -| text | Yes | Yes | string | Yes | Notification content. | -| additionalText | Yes | Yes | string | No | Additional information of the notification.| -| longText | Yes | Yes | string | Yes | Long text of the notification. | -| briefText | Yes | Yes | string | Yes | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | +| Name | Readable| Writable| Type | Description | +| -------------- | ---- | --- | ------ | -------------------------------- | +| title | Yes | Yes | string | Notification title. | +| text | Yes | Yes | string | Notification content. | +| additionalText | Yes | Yes | string | Additional information of the notification.| +| longText | Yes | Yes | string | Long text of the notification. | +| briefText | Yes | Yes | string | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | ## NotificationMultiLineContent **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | --- | --- | --------------- | ---- | -------------------------------- | -| title | Yes | Yes | string | Yes | Notification title. | -| text | Yes | Yes | string | Yes | Notification content. | -| additionalText | Yes | Yes | string | No | Additional information of the notification.| -| briefText | Yes | Yes | string | Yes | Brief text of the notification.| -| longTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | -| lines | Yes | Yes | Array\ | Yes | Multi-line text of the notification. | +| Name | Readable| Writable| Type | Description | +| -------------- | --- | --- | --------------- | -------------------------------- | +| title | Yes | Yes | string | Notification title. | +| text | Yes | Yes | string | Notification content. | +| additionalText | Yes | Yes | string | Additional information of the notification.| +| briefText | Yes | Yes | string | Brief text of the notification.| +| longTitle | Yes | Yes | string | Title of the notification in the expanded state. | +| lines | Yes | Yes | Array\ | Multi-line text of the notification. | ## NotificationPictureContent **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | ---- | --- | -------------- | ---- | -------------------------------- | -| title | Yes | Yes | string | Yes | Notification title. | -| text | Yes | Yes | string | Yes | Notification content. | -| additionalText | Yes | Yes | string | No | Additional information of the notification.| -| briefText | Yes | Yes | string | Yes | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | -| picture | Yes | Yes | image.PixelMap | Yes | Picture attached to the notification. | +| Name | Readable| Writable| Type | Description | +| -------------- | ---- | --- | -------------- | -------------------------------- | +| title | Yes | Yes | string | Notification title. | +| text | Yes | Yes | string | Notification content. | +| additionalText | Yes | Yes | string | Additional information of the notification.| +| briefText | Yes | Yes | string | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | +| picture | Yes | Yes | image.PixelMap | Picture attached to the notification. | ## NotificationContent **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ----------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------ | -| contentType | Yes | Yes | [ContentType](#contenttype) | Yes | Notification content type. | -| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | No | Normal text. | -| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | No | Long text.| -| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | No | Multi-line text. | -| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | No | Picture-attached. | +| Name | Readable| Writable| Type | Description | +| ----------- | ---- | --- | ------------------------------------------------------------ | ------------------ | +| contentType | Yes | Yes | [ContentType](#contenttype) | Notification content type. | +| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | Normal text. | +| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | Long text.| +| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | Multi-line text. | +| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | Picture-attached. | ## NotificationFlagStatus8+ @@ -3691,87 +3713,87 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------------- | ---- | ---- | ---------------------- | ---- | --------------------------------- | -| soundEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable the sound alert for the notification. | -| vibrationEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable vibration for the notification. | +| Name | Readable| Writable| Type | Description | +| ---------------- | ---- | ---- | ---------------------- | --------------------------------- | +| soundEnabled | Yes | No | NotificationFlagStatus | Whether to enable the sound alert for the notification. | +| vibrationEnabled | Yes | No | NotificationFlagStatus | Whether to enable vibration for the notification. | ## NotificationRequest **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| --------------------- | ---- | --- | --------------------------------------------- | ---- | -------------------------- | -| content | Yes | Yes | [NotificationContent](#notificationcontent) | Yes | Notification content. | -| id | Yes | Yes | number | No | Notification ID. | -| slotType | Yes | Yes | [SlotType](#slottype) | No | Slot type. | -| isOngoing | Yes | Yes | boolean | No | Whether the notification is an ongoing notification. | -| isUnremovable | Yes | Yes | boolean | No | Whether the notification can be removed. | -| deliveryTime | Yes | Yes | number | No | Time when the notification is sent. | -| tapDismissed | Yes | Yes | boolean | No | Whether the notification is automatically cleared. | -| autoDeletedTime | Yes | Yes | number | No | Time when the notification is automatically cleared. | -| wantAgent | Yes | Yes | WantAgent | No | **WantAgent** instance to which the notification will be redirected after being clicked. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extended parameters. | -| color | Yes | Yes | number | No | Background color of the notification. | -| colorEnabled | Yes | Yes | boolean | No | Whether the notification background color is enabled. | -| isAlertOnce | Yes | Yes | boolean | No | Whether the notification triggers an alert only once.| -| isStopwatch | Yes | Yes | boolean | No | Whether to display the stopwatch. | -| isCountDown | Yes | Yes | boolean | No | Whether to display the countdown time. | -| isFloatingIcon | Yes | Yes | boolean | No | Whether the notification is displayed as a floating icon. | -| label | Yes | Yes | string | No | Notification label. | -| badgeIconStyle | Yes | Yes | number | No | Notification badge type. | -| showDeliveryTime | Yes | Yes | boolean | No | Whether to display the time when the notification is delivered. | -| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | No | Buttons in the notification. Up to two buttons are allowed. | -| smallIcon | Yes | Yes | PixelMap | No | Small notification icon. | -| largeIcon | Yes | Yes | PixelMap | No | Large notification icon. | -| creatorBundleName | Yes | No | string | No | Name of the bundle that creates the notification. | -| creatorUid | Yes | No | number | No | UID used for creating the notification. | -| creatorPid | Yes | No | number | No | PID used for creating the notification. | -| creatorUserId8+| Yes | No | number | No | ID of the user who creates the notification. | -| hashCode | Yes | No | string | No | Unique ID of the notification. | -| classification | Yes | Yes | string | No | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+| Yes | Yes | string | No | Group notification name. | -| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | No | Notification template. | -| isRemoveAllowed8+ | Yes | No | boolean | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source8+ | Yes | No | number | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | No | Option of distributed notification. | -| deviceId8+ | Yes | No | string | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | No | Notification flags. | -| removalWantAgent9+ | Yes | Yes | WantAgent | No | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | Yes | Yes | number | No | Number of notifications displayed on the application icon. | +| Name | Readable| Writable| Type | Description | +| --------------------- | ---- | --- | --------------------------------------------- | -------------------------- | +| content | Yes | Yes | [NotificationContent](#notificationcontent) | Notification content. | +| id | Yes | Yes | number | Notification ID. | +| slotType | Yes | Yes | [SlotType](#slottype) | Slot type. | +| isOngoing | Yes | Yes | boolean | Whether the notification is an ongoing notification. | +| isUnremovable | Yes | Yes | boolean | Whether the notification can be removed. | +| deliveryTime | Yes | Yes | number | Time when the notification is sent. | +| tapDismissed | Yes | Yes | boolean | Whether the notification is automatically cleared. | +| autoDeletedTime | Yes | Yes | number | Time when the notification is automatically cleared. | +| wantAgent | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | Yes | Yes | {[key: string]: any} | Extended parameters. | +| color | Yes | Yes | number | Background color of the notification. | +| colorEnabled | Yes | Yes | boolean | Whether the notification background color is enabled. | +| isAlertOnce | Yes | Yes | boolean | Whether the notification triggers an alert only once.| +| isStopwatch | Yes | Yes | boolean | Whether to display the stopwatch. | +| isCountDown | Yes | Yes | boolean | Whether to display the countdown time. | +| isFloatingIcon | Yes | Yes | boolean | Whether the notification is displayed as a floating icon. | +| label | Yes | Yes | string | Notification label. | +| badgeIconStyle | Yes | Yes | number | Notification badge type. | +| showDeliveryTime | Yes | Yes | boolean | Whether to display the time when the notification is delivered. | +| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | Yes | Yes | PixelMap | Small notification icon. | +| largeIcon | Yes | Yes | PixelMap | Large notification icon. | +| creatorBundleName | Yes | No | string | Name of the bundle that creates the notification. | +| creatorUid | Yes | No | number | UID used for creating the notification. | +| creatorPid | Yes | No | number | PID used for creating the notification. | +| creatorUserId8+| Yes | No | number | ID of the user who creates the notification. | +| hashCode | Yes | No | string | Unique ID of the notification. | +| classification | Yes | Yes | string | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+| Yes | Yes | string | Group notification name. | +| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | Notification template. | +| isRemoveAllowed8+ | Yes | No | boolean | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | Yes | No | number | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | Option of distributed notification. | +| deviceId8+ | Yes | No | string | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | Notification flags. | +| removalWantAgent9+ | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | Yes | Yes | number | Number of notifications displayed on the application icon. | ## DistributedOptions8+ **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------------------- | ---- | ---- | -------------- | ---- | ---------------------------------- | -| isDistributed | Yes | Yes | boolean | No | Whether the notification is a distributed notification. | -| supportDisplayDevices | Yes | Yes | Array\ | Yes | Types of the devices to which the notification can be synchronized. | -| supportOperateDevices | Yes | Yes | Array\ | No | Devices on which notification can be enabled. | -| remindType | Yes | No | number | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | +| Name | Readable| Writable| Type | Description | +| ---------------------- | ---- | ---- | -------------- | ---------------------------------- | +| isDistributed | Yes | Yes | boolean | Whether the notification is a distributed notification. | +| supportDisplayDevices | Yes | Yes | Array\ | Types of the devices to which the notification can be synchronized. | +| supportOperateDevices | Yes | Yes | Array\ | Devices on which notification can be enabled. | +| remindType | Yes | No | number | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | ## NotificationSlot **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------------- | ---- | --- | --------------------- | ---- | ------------------------------------------ | -| type | Yes | Yes | [SlotType](#slottype) | Yes | Slot type. | -| level | Yes | Yes | number | No | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Yes | Yes | string | No | Notification slot description. | -| badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. | -| bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. | -| lockscreenVisibility | Yes | Yes | boolean | No | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | -| sound | Yes | Yes | string | No | Notification alert tone. | -| lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | -| lightColor | Yes | Yes | number | No | Indicator color of the notification. | -| vibrationValues | Yes | Yes | Array\ | No | Vibration mode of the notification. | -| enabled9+ | Yes | No | boolean | No | Enabled status of the notification slot. | +| Name | Readable| Writable| Type | Description | +| -------------------- | ---- | --- | --------------------- | ------------------------------------------ | +| type | Yes | Yes | [SlotType](#slottype) | Slot type. | +| level | Yes | Yes | number | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | Yes | Yes | string | Notification slot description. | +| badgeFlag | Yes | Yes | boolean | Whether to display the badge. | +| bypassDnd | Yes | Yes | boolean | Whether to bypass the DND mode in the system. | +| lockscreenVisibility | Yes | Yes | number | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | Yes | Yes | boolean | Whether vibration is supported for the notification. | +| sound | Yes | Yes | string | Notification alert tone. | +| lightEnabled | Yes | Yes | boolean | Whether the indicator blinks for the notification. | +| lightColor | Yes | Yes | number | Indicator color of the notification. | +| vibrationValues | Yes | Yes | Array\ | Vibration mode of the notification. | +| enabled9+ | Yes | No | boolean | Enabled status of the notification slot. | ## NotificationSorting @@ -3780,11 +3802,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | ---- | --- | ------------------------------------- | ---- | ------------ | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot content.| -| hashCode | Yes | No | string | Yes | Unique ID of the notification.| -| ranking | Yes | No | number | Yes | Notification sequence number.| +| Name | Readable| Writable| Type | Description | +| -------- | ---- | --- | ------------------------------------- | ------------ | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Notification slot content.| +| hashCode | Yes | No | string | Unique ID of the notification.| +| ranking | Yes | No | number | Notification sequence number.| ## NotificationSortingMap @@ -3793,10 +3815,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | ---- | --- | ------------------------------------------------------------ | ---- | ---------------- | -| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | Array of notification sorting information.| -| sortedHashCode | Yes | No | Array\ | Yes | Array of unique notification IDs.| +| Name | Readable| Writable| Type | Description | +| -------------- | ---- | --- | ------------------------------------------------------------ | ---------------- | +| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Array of notification sorting information.| +| sortedHashCode | Yes | No | Array\ | Array of unique notification IDs.| ## NotificationSubscribeInfo @@ -3805,10 +3827,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Mandatory| Description | -| ----------- | --- | ---- | --------------- | ---- | ------------------------------- | -| bundleNames | Yes | Yes | Array\ | No | Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Yes | Yes | number | No | User whose notifications are to be subscribed to. | +| Name | Readable| Writable| Type | Description | +| ----------- | --- | ---- | --------------- | ------------------------------- | +| bundleNames | Yes | Yes | Array\ | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | Yes | Yes | number | User whose notifications are to be subscribed to. | ## NotificationTemplate8+ @@ -3825,9 +3847,9 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | ------ | ---- | ----------------------------- | -| inputKey | Yes | Yes | string | Yes | Key to identify the user input.| +| Name | Readable| Writable| Type | Description | +| -------- | --- | ---- | ------ | ----------------------------- | +| inputKey | Yes | Yes | string | Key to identify the user input.| ## DeviceRemindType8+ diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index cf7fbb1caa02a7c9c8f6b434a227a3275574fa6c..00802493ea68efd037b17e0712d78b755d131059 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,8 +1,10 @@ # Pasteboard +The **pasteboard** module provides the pasteboard management client and pasteboard server. The pasteboard management client manages pasteboard APIs. Specifically, it provides pasteboard APIs in JavaScript for applications, creates pasteboard data on the application framework side, and requests the pasteboard SA to create, delete, query, convert text, and configure pasteboards. The pasteboard server manages pasteboard events as well as the pasteboard SA lifecycle, providing support for the copy and paste functions of the system. -> **NOTE**
The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** > +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -461,10 +463,10 @@ The pasteboard supports a maximum number of 128 data records. **Example** -```js -var pasteData = pasteboard.createPlainTextData("hello"); -pasteData.addTextRecord("good"); -``` + ```js + var pasteData = pasteboard.createPlainTextData("hello"); + pasteData.addTextRecord("good"); + ``` ### addHtmlRecord7+ @@ -1037,13 +1039,13 @@ Checks whether the system pasteboard contains content. This API uses a promise t **Example** -```js -systemPasteboard.hasPasteData().then((data) => { - console.info('Operation succeeded. ' + JSON.stringify(data)); -}).catch((error) => { - console.error('failed to hasPasteData because ' + JSON.stringify(error)); -}); -``` + ```js + systemPasteboard.hasPasteData().then((data) => { + console.info('success hasPasteData : ' + JSON.stringify(data)); + }).catch((error) => { + console.error('failed to hasPasteData because ' + JSON.stringify(error)); + }); + ``` ### clear7+ 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-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 6e3ee3ab521fd77e73a8085002296cd6b5883430..ee61f71f78a97411006f72225f5ac4a65e09e300 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -389,7 +389,7 @@ promise.then(data => { isNrSupported\(slotId: number\): boolean -Checks whether the current device supports 5G \(NR\). +Checks whether the current device supports 5G \(NR\) for the SIM card in the specified slot. **System capability**: SystemCapability.Telephony.CoreService @@ -470,7 +470,7 @@ radio.isRadioOn(slotId, (err, data) => { isRadioOn\(slotId?: number\): Promise -Checks whether the radio service is enabled. This API uses a promise to return the result. +Checks whether the radio service is enabled on the SIM card in the specified slot. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -505,7 +505,7 @@ promise.then(data => { getOperatorName\(slotId: number, callback: AsyncCallback\): void -Obtains the carrier name. This API uses an asynchronous callback to return the result. +Obtains the carrier name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -530,7 +530,7 @@ radio.getOperatorName(slotId, (err, data) => { getOperatorName\(slotId: number\): Promise -Obtains the carrier name. This API uses a promise to return the result. +Obtains the carrier name for the SIM card in the specified slot. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -905,7 +905,29 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback\): void Sends a cell location update request. This API uses an asynchronous callback to return the result. +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.sendUpdateCellLocationRequest((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.sendUpdateCellLocationRequest8+ + +sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): void +Sends a cell location update request for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -915,26 +937,34 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js -radio.sendUpdateCellLocationRequest((err, data) => { +let slotId = 0; +radio.sendUpdateCellLocationRequest(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` ## radio.sendUpdateCellLocationRequest8+ -sendUpdateCellLocationRequest\(\): Promise +sendUpdateCellLocationRequest\(slotId?: number): Promise -Sends a cell location update request. This API uses a promise to return the result. +Sends a cell location update request for the SIM card in the specified slot.This API uses a promise to return the result. This is a system API. **System capability**: SystemCapability.Telephony.CoreService +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + **Return value** | Type | Description | @@ -944,7 +974,8 @@ This is a system API. **Example** ```js -let promise = radio.sendUpdateCellLocationRequest(); +let slotId = 0; +let promise = radio.sendUpdateCellLocationRequest(slotId); promise.then(data => { console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -983,7 +1014,7 @@ radio.getCellInformation((err, data) => { getCellInformation(slotId: number, callback: AsyncCallback\>): void -Obtains cell information. This API uses an asynchronous callback to return the result. +Obtains cell information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1012,7 +1043,7 @@ radio.getCellInformation(slotId, (err, data) => { getCellInformation(slotId?: number): Promise\> -Obtains cell information. This API uses a promise to return the result. +Obtains cell information for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1134,7 +1165,7 @@ promise.then(data => { getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\): void -Obtains network search information. This API uses an asynchronous callback to return the result. +Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1161,7 +1192,7 @@ radio.getNetworkSearchInformation(0, (err, data) => { getNetworkSearchInformation\(slotId: number\): Promise -Obtains network search information. This API uses a promise to return the result. +Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1221,7 +1252,7 @@ radio.getNrOptionMode((err, data) => { getNrOptionMode(slotId: number, callback: AsyncCallback): void -Obtains the NR option mode. This API uses an asynchronous callback to return the result. +Obtains the NR option mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1248,7 +1279,7 @@ radio.getNrOptionMode(slotId, (err, data) => { getNrOptionMode(slotId?: number): Promise -Obtains the NR option mode. This API uses a promise to return the result. +Obtains the NR option mode for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1466,7 +1497,7 @@ promise.then(data => { setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\): void -Sets the preferred network. This API uses an asynchronous callback to return the result. +Sets the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1494,7 +1525,7 @@ radio.setPreferredNetwork(0, 1, (err, data) => { setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise -Sets the preferred network. This API uses a promise to return the result. +Sets the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1530,7 +1561,7 @@ promise.then(data => { getPreferredNetwork\(slotId: number, callback: AsyncCallback\): void -Obtains the preferred network. This API uses an asynchronous callback to return the result. +Obtains the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1557,7 +1588,7 @@ radio.getPreferredNetwork(0, (err, data) => { getPreferredNetwork(slotId: number): Promise -Obtains the preferred network. This API uses a promise to return the result. +Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1592,7 +1623,7 @@ promise.then(data => { getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback): void -Obtains the IMS registration status of the specified IMS service type. This API uses an asynchronous callback to return the result. +Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1620,7 +1651,7 @@ radio.getImsRegInfo(0, 1, (err, data) => { getImsRegInfo(slotId: number, imsType: ImsServiceType): Promise -Obtains the IMS registration status of the specified IMS service type. This API uses a promise to return the result. +Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1656,7 +1687,7 @@ promise.then(data => { on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback): void -Enables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. +Enables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1685,7 +1716,7 @@ radio.on('imsRegStateChange', 0, 1, (err, data) => { off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback): void -Disables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. +Disables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. 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-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index 832d9754db5e41a11d38b020e77673ee5fe4d346..bc42373a4589e4ab2fa4b268d1472a1c7bb60ad2 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -170,6 +170,63 @@ Unlocks the screen. This API uses a promise to return the result. }); ``` + +## screenlock.lockScreen9+ + +lockScreen(callback: AsyncCallback<void>): void + + +Locks the screen. This API uses an asynchronous callback to return the result. + + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation failed, an error message is returned.| + +**Example** + + ```js + screenlock.lockScreen((err) => { + if (err) { + console.error('lockScreen callback error -> ${JSON.stringify(err)}'); + return; + } + console.info('lockScreen callback success'); + }); + ``` + +## screenlock.lockScreen9+ + +lockScreen(): Promise<void> + +Locks the screen. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.ScreenLock + +**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.| + +**Example** + + ```js + screenlock.lockScreen().then(() => { + console.log('lockScreen success'); + }).catch((err) => { + console.error('lockScreen fail, promise: err->${JSON.stringify(err)}'); + }); + ``` + + ## screenlock.on9+ on(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' | 'unlockScreen' | 'beginExitAnimation', callback: Callback\): void @@ -231,7 +288,7 @@ Subscribes to screen lock status changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.| -| callback | Callback\ | Yes| Callback used to return the result.| +| callback | Callback\ | Yes| Callback used to return the result. | **Example** 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-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 681e5cdc6ac3dea7924feb25752e017052bef23e..f9475d2e7d76b6ccf20f6b0f32d01969fdccfbbb 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -64,7 +64,7 @@ let promise = sim.isSimActive(0); promise.then(data => { console.log(`isSimActive success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`isSimActive fail, promise: err->${JSON.stringify(err)}`); + console.log(`isSimActive failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -113,7 +113,7 @@ let promise = sim.getDefaultVoiceSlotId(); promise.then(data => { console.log(`getDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getDefaultVoiceSlotId fail, promise: err->${JSON.stringify(err)}`); + console.log(`getDefaultVoiceSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -167,7 +167,7 @@ let promise = sim.hasOperatorPrivileges(0); promise.then(data => { console.log(`hasOperatorPrivileges success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`hasOperatorPrivileges fail, promise: err->${JSON.stringify(err)}`); + console.log(`hasOperatorPrivileges failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -222,7 +222,7 @@ let promise = sim.getISOCountryCodeForSim(0); promise.then(data => { console.log(`getISOCountryCodeForSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getISOCountryCodeForSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`getISOCountryCodeForSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -278,7 +278,7 @@ let promise = sim.getSimOperatorNumeric(0); promise.then(data => { console.log(`getSimOperatorNumeric success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimOperatorNumeric fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimOperatorNumeric failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -334,7 +334,7 @@ let promise = sim.getSimSpn(0); promise.then(data => { console.log(`getSimSpn success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimSpn fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimSpn failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -390,7 +390,7 @@ let promise = sim.getSimState(0); promise.then(data => { console.log(`getSimState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimState fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -445,7 +445,7 @@ let promise = sim.getCardType(0); promise.then(data => { console.log(`getCardType success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getCardType fail, promise: err->${JSON.stringify(err)}`); + console.log(`getCardType failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -501,7 +501,7 @@ let promise = sim.hasSimCard(0); promise.then(data => { console.log(`hasSimCard success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`hasSimCard fail, promise: err->${JSON.stringify(err)}`); + console.log(`hasSimCard failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -564,7 +564,7 @@ let promise = sim.getSimAccountInfo(0); promise.then(data => { console.log(`getSimAccountInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimAccountInfo fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimAccountInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -620,7 +620,7 @@ let promise = sim.getActiveSimAccountInfoList(); promise.then(data => { console.log(`getActiveSimAccountInfoList success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getActiveSimAccountInfoList fail, promise: err->${JSON.stringify(err)}`); + console.log(`getActiveSimAccountInfoList failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -683,7 +683,7 @@ let promise = sim.setDefaultVoiceSlotId(0); promise.then(data => { console.log(`setDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setDefaultVoiceSlotId fail, promise: err->${JSON.stringify(err)}`); + console.log(`setDefaultVoiceSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -749,7 +749,7 @@ let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setShowName fail, promise: err->${JSON.stringify(err)}`); + console.log(`setShowName failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -812,7 +812,7 @@ let promise = sim.getShowName(0); promise.then(data => { console.log(`getShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getShowName fail, promise: err->${JSON.stringify(err)}`); + console.log(`getShowName failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -879,7 +879,7 @@ let promise = sim.setShowNumber(0, number); promise.then(data => { console.log(`setShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setShowNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`setShowNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -942,7 +942,7 @@ let promise = sim.getShowNumber(0); promise.then(data => { console.log(`getShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getShowNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getShowNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1005,7 +1005,7 @@ let promise = sim.activateSim(0); promise.then(data => { console.log(`activateSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`activateSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`activateSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1068,7 +1068,7 @@ let promise = sim.deactivateSim(0); promise.then(data => { console.log(`deactivateSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`deactivateSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`deactivateSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1090,7 +1090,7 @@ This is a system API. | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | **Example** @@ -1123,7 +1123,7 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | **Return value** @@ -1143,7 +1143,7 @@ let promise = sim.setLockState(0, lockInfo); promise.then(data => { console.log(`setLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setLockState fail, promise: err->${JSON.stringify(err)}`); + console.log(`setLockState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1204,7 +1204,7 @@ let promise = sim.getLockState(0, 1); promise.then(data => { console.log(`getLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getLockState fail, promise: err->${JSON.stringify(err)}`); + console.log(`getLockState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1271,7 +1271,7 @@ let promise = sim.alterPin(0, "1234", "0000"); promise.then(data => { console.log(`alterPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`alterPin fail, promise: err->${JSON.stringify(err)}`); + console.log(`alterPin failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1338,7 +1338,7 @@ let promise = sim.alterPin2(0, "1234", "0000"); promise.then(data => { console.log(`alterPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`alterPin2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`alterPin2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1405,7 +1405,7 @@ let promise = sim.unlockPin(0, pin); promise.then(data => { console.log(`unlockPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPin fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPin failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1476,7 +1476,7 @@ let promise = sim.unlockPuk(0, newPin, puk); promise.then(data => { console.log(`unlockPuk success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPuk fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPuk failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1543,7 +1543,7 @@ let promise = sim.unlockPin2(0,pin2); promise.then(data => { console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPin2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPin2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1614,7 +1614,7 @@ let promise = sim.unlockPuk2(0, newPin2, puk2); promise.then(data => { console.log(`unlockPuk2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPuk2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPuk2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1697,7 +1697,7 @@ let promise = sim.getSimIccId(0); promise.then(data => { console.log(`getSimIccId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimIccId fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimIccId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1760,7 +1760,7 @@ let promise = sim.getVoiceMailIdentifier(0); promise.then(data => { console.log(`getVoiceMailIdentifier success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getVoiceMailIdentifier fail, promise: err->${JSON.stringify(err)}`); + console.log(`getVoiceMailIdentifier failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1823,7 +1823,7 @@ let promise = sim.getVoiceMailNumber(0); promise.then(data => { console.log(`getVoiceMailNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getVoiceMailNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getVoiceMailNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1890,7 +1890,7 @@ let promise = sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com"); promise.then(data => { console.log(`setVoiceMailInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setVoiceMailInfo fail, promise: err->${JSON.stringify(err)}`); + console.log(`setVoiceMailInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1953,7 +1953,7 @@ let promise = sim.getSimTelephoneNumber(0); promise.then(data => { console.log(`getSimTelephoneNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimTelephoneNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimTelephoneNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2016,7 +2016,7 @@ let promise = sim.getSimGid1(0); promise.then(data => { console.log(`getSimGid1 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimGid1 fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimGid1 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2079,7 +2079,7 @@ let promise = sim.getIMSI(0); promise.then(data => { console.log(`getIMSI success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getIMSI fail, promise: err->${JSON.stringify(err)}`); + console.log(`getIMSI failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2142,7 +2142,7 @@ let promise = sim.getOperatorConfigs(0); promise.then(data => { console.log(`getOperatorConfigs success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOperatorConfigs fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOperatorConfigs failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2163,7 +2163,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | callback | AsyncCallback> | Yes | Callback used to return the result. | **Example** @@ -2192,7 +2192,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ----------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | **Return value** @@ -2207,7 +2207,7 @@ let promise = sim.queryIccDiallingNumbers(0, 1); promise.then(data => { console.log(`queryIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`queryIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`queryIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2228,7 +2228,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2264,7 +2264,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2286,7 +2286,7 @@ let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`addIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`addIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2307,7 +2307,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2343,7 +2343,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2365,7 +2365,7 @@ let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`delIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`delIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2386,7 +2386,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2422,7 +2422,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2444,7 +2444,7 @@ let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`updateIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`updateIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2509,7 +2509,7 @@ let promise = sim.sendEnvelopeCmd(0, "ls"); promise.then(data => { console.log(`sendEnvelopeCmd success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`sendEnvelopeCmd fail, promise: err->${JSON.stringify(err)}`); + console.log(`sendEnvelopeCmd failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2574,7 +2574,7 @@ let promise = sim.sendTerminalResponseCmd(0, "ls"); promise.then(data => { console.log(`sendTerminalResponseCmd success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`sendTerminalResponseCmd fail, promise: err->${JSON.stringify(err)}`); + console.log(`sendTerminalResponseCmd failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2647,7 +2647,7 @@ let promise = sim.unlockSimLock(0, persoLockInfo); promise.then(data => { console.log(`unlockSimLock success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockSimLock fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockSimLock failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2706,7 +2706,7 @@ let promise = sim.getOpKey(0); promise.then(data => { console.log(`getOpKey success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOpKey fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOpKey failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2765,7 +2765,7 @@ let promise = sim.getOpName(0); promise.then(data => { console.log(`getOpName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOpName fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOpName failed, promise: err->${JSON.stringify(err)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index a89640acc11ba359dfdf6011bbd4766cdd42b5ec..ec32f9279c250a823484d0894e5ce56c82386601 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,9 +1,10 @@ -# Setting the System Time +# System Time and Time Zone -This module provides the time, time zone, and timing services. Use the time and time zone services to set and obtain the system time and time zone, and use the timing service to manage and use the system time and time zone to implement alarms or other timing functions. - -> **NOTE**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. +> **NOTE** +>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -25,15 +26,15 @@ Sets the system time. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| time | number | Yes| Timestamp to set, in milliseconds.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| time | number | Yes | Timestamp to set, in milliseconds. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -// Set the system time to 2021-01-20 02:36:25. + // Set the system time to 2021-01-20 02:36:25. var time = 1611081385000; systemTime.setTime(time, (error, data) => { if (error) { @@ -57,26 +58,26 @@ Sets the system time. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| time | number | Yes| Timestamp to set, in milliseconds.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| time | number | Yes | Timestamp to set, in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** ```js -// Set the system time to 2021-01-20 02:36:25. -var time = 1611081385000; -systemTime.setTime(time).then((data) => { - console.log(`systemTime.setTime success data : ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); -}); + // Set the system time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time).then((data) => { + console.log(`systemTime.setTime success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + }); ``` @@ -90,10 +91,10 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -118,14 +119,14 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -149,10 +150,10 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| **Example** @@ -177,14 +178,14 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -208,10 +209,10 @@ Obtains the time elapsed since system start, including the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -236,14 +237,14 @@ Obtains the time elapsed since system start, including the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -269,10 +270,10 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| date | Date | Yes| Target date to set.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| date | Date | Yes | Target date to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -300,14 +301,14 @@ Sets the system date. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| date | Date | Yes| Target date to set.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------- | +| date | Date | Yes | Target date to set.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -332,9 +333,9 @@ Obtains the current system date. This API uses an asynchronous callback to retur **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Date> | Yes| Callback used to return the current system date.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| **Example** @@ -359,8 +360,8 @@ Obtains the current system date. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ----------------------------------------- | | Promise<Date> | Promise used to return the current system date.| **Example** @@ -386,10 +387,10 @@ Sets the system time zone. This API uses an asynchronous callback to return the **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timezone | string | Yes| System time zone to set.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| timezone | string | Yes | System time zone to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -416,14 +417,14 @@ Sets the system time zone. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timezone | string | Yes| System time zone to set.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| timezone | string | Yes | System time zone to set.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -447,9 +448,9 @@ Obtains the system time zone. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes| Callback used to return the system time zone.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone.| **Example** @@ -474,8 +475,8 @@ Obtains the system time zone. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------- | | Promise<string> | Promise used to return the system time zone.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md new file mode 100644 index 0000000000000000000000000000000000000000..f952b38c3de656864d42ad8c2c42b108b0c53f3d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -0,0 +1,319 @@ +# System Timer + +The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. + +> **NOTE**
+>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + + +``` +import systemTimer from '@ohos.systemTimer'; +``` + + +## systemTime.createTimer + +createTimer(options: TimerOptions, callback: AsyncCallback<number>): void + +Creates a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | +| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------------------------------------------------ | +| syncCallback<number>| Callback used to return the timer ID. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat: false + } + systemTimer.createTimer(options, (error, data) => { + if (error) { + console.error(`failed to systemTime.createTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.createTimer + +createTimer(options: TimerOptions): Promise<number> + +Creates a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | +| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------------ | +| Promise<number> | Promise used to return the timer ID. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + systemTimer.createTimer(options).then((data) => { + console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.createTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.startTimer + +startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void + +Starts a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | + + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 10000, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + +## systemTime.startTimer + +startTimer(timer: number, triggerTime: number): Promise<void> + +Starts a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | + + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.stopTimer + +stopTimer(timer: number, callback: AsyncCallback<void>): void + +Stops a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stoptTimer(timerId, 10000, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.stopTimer + +stopTimer(timer: number): Promise<void> + +Stops a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stoptTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.destroyTimer + +destroyTimer(timer: number, callback: AsyncCallback<void>): void + +Destroys a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stopTimer(timerId) + systemTimer.destroyTimer(timerId, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.destroyTimer + +destroyTimer(timer: number): Promise<void> + +Destroys a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stopTimer(timerId) + systemTimer.destroytTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` 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-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 073fdcd6778ccd28942841312f0f4e992a39e9fc..2eae3ec8e5599a6e2b0123f4f6fa7368e51365e7 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,5 +1,6 @@ # Wallpaper +The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 76bba2f5b15c6a9da9b2f4bb4f5201f4552a9cbd..4c716d142c2d773da09dec8e2c0d8b09d0d628aa 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** @@ -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..c7d28fe1bf86073c4453ea9e2cf9cbcb3698062e 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 +// Notes: +// The key represents the current event type, and the value represents the depth of the current parsing. You can know the parsed event according to EVENTTYPE. For example, the result 'key: value' in this example means: +// 0(START_DOCUMENT):0(Parse to the START_DOCUMENT, and the depth is 0), 2(START_TAG):1(Parse to the START_TAG node, and the depth is 1), 10(WHITESPACE):1(Parse to the WHITESPACE space, and the depth is 1), 2(START_TAG):2(Parse to the START_TAG title, 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