diff --git a/CODEOWNERS b/CODEOWNERS index 59abea64af78d6f245925f04cb315afcb55bfac4..81d411b4860e6baaff515d258356e6c6e84b2a56 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -129,8 +129,10 @@ zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 -zh-cn/application-dev/ability/ @RayShih -zh-cn/application-dev/ui/ @HelloCrease +zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih zh-cn/application-dev/windowmanager/ @ge-yafang zh-cn/application-dev/webgl/ @ge-yafang @@ -445,8 +447,19 @@ zh-cn/application-dev/reference/apis/js-apis-formextensioncontext.md @RayShih @l zh-cn/application-dev/reference/apis/js-apis-formhost.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-formInfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-formprovider.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-usb.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-colorspace-manager.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-display.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen diff --git a/en/Legal-Notices.md b/en/Legal-Notices.md new file mode 100644 index 0000000000000000000000000000000000000000..80d301770e502de109fbcf861fe456168cd23ab1 --- /dev/null +++ b/en/Legal-Notices.md @@ -0,0 +1,21 @@ +# Legal Notices + +**Copyright (c) 2020-2022 OpenAtom OpenHarmony. All rights reserved.** + +## Copyright + +All copyrights of the OpenHarmony documents are reserved by OpenAtom OpenHarmony. + +The OpenHarmony documents are licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). For easier understanding, you can visit [Creative Commons](https://creativecommons.org/licenses/by/4.0/) to get a human-readable summary of the license. For the complete content, see [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode). + +## Trademarks and Permissions + +No content provided in the OpenHarmony documentation shall be deemed as a grant of the approval or right to use any trademark, name, or logo of the OpenAtom Foundation and OpenAtom OpenHarmony. No third parties shall use any of the aforementioned trademarks, names, or logos in any way without explicit prior written permission of the OpenAtom Foundation. + +## Disclaimer + +The information in the OpenHarmony documents is subject to change without notice. + +The OpenHarmony documents are provided without any express or implied warranty. In any case, the OpenAtom Foundation or the copyright owner is not liable for any direct or indirect loss arising from the use of the OpenHarmony documents, regardless of the cause or legal theory, even if the OpenHarmony documents have stated that there is a possibility of such loss. + + \ No newline at end of file diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index 1331ac52206cf1980ce59a7def62bfd32c27e406..75dc8b66607121be43c3bcfa13398ecee5b76401 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -150,7 +150,7 @@ Currently, the OpenHarmony community supports 17 types of development boards, wh | System Type| Board Model| Chip Model|
Function Description and Use Case
| Application Scenario| Code Repository | | -------- | -------- | -------- | -------- | -------- | -------- | -| Standard system| Runhe HH-SCDAYU200| RK3568 |
Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
Use case:
[DAYU200 Use Case](device-dev/porting/porting-dayu200-on_standard-demo.md)
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
| +| Standard system| Runhe HH-SCDAYU200| RK3568 |
Function description:
Bolstered by the Rockchip RK3568, the HH-SCDAYU200 development board integrates the dual-core GPU and efficient NPU. Its quad-core 64-bit Cortex-A55 processor uses the advanced 22 nm fabrication process and is clocked at up to 2.0 GHz. The board is packed with Bluetooth, Wi-Fi, audio, video, and camera features, with a wide range of expansion ports to accommodate various video input and outputs. It comes with dual GE auto-sensing RJ45 ports, so it can be used in multi-connectivity products, such as network video recorders (NVRs) and industrial gateways.
| Entertainment, easy travel, and smart home, such as kitchen hoods, ovens, and treadmills.| [device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
| | Small system| Hispark_Taurus | Hi3516DV300 |
Function Description:
Hi3516D V300 is the next-generation system on chip (SoC) for smart HD IP cameras. It integrates the next-generation image signal processor (ISP), H.265 video compression encoder, and high-performance NNIE engine, and delivers high performance in terms of low bit rate, high image quality, intelligent processing and analysis, and low power consumption.
| Smart device with screens, such as refrigerators with screens and head units.| [device_soc_hisilicon](https://gitee.com/openharmony/device_soc_hisilicon)
[device_board_hisilicon](https://gitee.com/openharmony/device_board_hisilicon)
[vendor_hisilicon](https://gitee.com/openharmony/vendor_hisilicon)
| | Mini system| Multi-modal V200Z-R | BES2600 |
Function description:
The multi-modal V200Z-R development board is a high-performance, multi-functional, and cost-effective AIoT SoC powered by the BES2600WM chip of Bestechnic. It integrates a quad-core ARM processor with a frequency of up to 1 GHz as well as dual-mode Wi-Fi and dual-mode Bluetooth. The board supports the 802.11 a/b/g/n/ and BT/BLE 5.2 standards. It is able to accommodate RAM of up to 42 MB and flash memory of up to 32 MB, and supports the MIPI display serial interface (DSI) and camera serial interface (CSI). It is applicable to various AIoT multi-modal VUI and GUI interaction scenarios.
Use case:
[Multi-modal V200Z-R Use Case](device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md)
| Smart hardware, and smart devices with screens, such as speakers and watches.| [device_soc_bestechnic](https://gitee.com/openharmony/device_soc_bestechnic)
[device_board_fnlink](https://gitee.com/openharmony/device_board_fnlink)
[vendor_bestechnic](https://gitee.com/openharmony/vendor_bestechnic)
| diff --git a/en/application-dev/IDL/idl-guidelines.md b/en/application-dev/IDL/idl-guidelines.md index 661b2532c49d36c79855c3e0530326ef590c7cd2..5b3a5d7990d4dfe55ddef2ad77ef7dab84033a2e 100644 --- a/en/application-dev/IDL/idl-guidelines.md +++ b/en/application-dev/IDL/idl-guidelines.md @@ -7,7 +7,7 @@ To ensure successful communications between the client and server, interfaces re ![IDL-interface-description](./figures/IDL-interface-description.png) -IDL provides the following functions: +**IDL provides the following functions:** - Declares interfaces provided by system services for external systems, and based on the interface declaration, generates C, C++, JS, or TS code for inter-process communication (IPC) or remote procedure call (RPC) proxies and stubs during compilation. @@ -17,7 +17,7 @@ IDL provides the following functions: ![IPC-RPC-communication-model](./figures/IPC-RPC-communication-model.png) -IDL has the following advantages: +**IDL has the following advantages:** - Services are defined in the form of interfaces in IDL. Therefore, you do not need to focus on implementation details. @@ -433,7 +433,7 @@ export default { console.log('ServiceAbility want:' + JSON.stringify(want)); console.log('ServiceAbility want name:' + want.bundleName) } catch(err) { - console.log("ServiceAbility error:" + err) + console.log('ServiceAbility error:' + err) } console.info('ServiceAbility onConnect end'); return new IdlTestImp('connect'); @@ -455,13 +455,13 @@ import featureAbility from '@ohos.ability.featureAbility'; function callbackTestIntTransaction(result: number, ret: number): void { if (result == 0 && ret == 124) { - console.log("case 1 success "); + console.log('case 1 success'); } } function callbackTestStringTransaction(result: number): void { if (result == 0) { - console.log("case 2 success "); + console.log('case 2 success'); } } @@ -472,17 +472,17 @@ var onAbilityConnectDone = { testProxy.testStringTransaction('hello', callbackTestStringTransaction); }, onDisconnect:function (elementName) { - console.log("onDisconnectService onDisconnect"); + console.log('onDisconnectService onDisconnect'); }, onFailed:function (code) { - console.log("onDisconnectService onFailed"); + console.log('onDisconnectService onFailed'); } }; function connectAbility: void { let want = { - "bundleName":"com.example.myapplicationidl", - "abilityName": "com.example.myapplicationidl.ServiceAbility" + bundleName: 'com.example.myapplicationidl', + abilityName: 'com.example.myapplicationidl.ServiceAbility' }; let connectionId = -1; connectionId = featureAbility.connectAbility(want, onAbilityConnectDone); @@ -495,7 +495,7 @@ function connectAbility: void { You can send a class from one process to another through IPC interfaces. However, you must ensure that the peer can use the code of this class and this class supports the **marshalling** and **unmarshalling** methods. OpenHarmony uses **marshalling** and **unmarshalling** to serialize and deserialize objects into objects that can be identified by each process. -To create a class that supports the sequenceable type, perform the following operations: +**To create a class that supports the sequenceable type, perform the following operations:** 1. Implement the **marshalling** method, which obtains the current state of the object and serializes the object into a **Parcel** object. 2. Implement the **unmarshalling** method, which deserializes the object from a **Parcel** object. @@ -595,7 +595,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _reply = new rpc.MessageParcel(); _data.writeInt(data); this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_INT_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode === 0) { + if (result.errCode == 0) { let _errCode = result.reply.readInt(); if (_errCode != 0) { let _returnValue = undefined; @@ -605,7 +605,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _returnValue = result.reply.readInt(); callback(_errCode, _returnValue); } else { - console.log("sendRequest failed, errCode: " + result.errCode); + console.log('sendRequest failed, errCode: ' + result.errCode); } }) } @@ -617,11 +617,11 @@ export default class IdlTestServiceProxy implements IIdlTestService { let _reply = new rpc.MessageParcel(); _data.writeString(data); this.proxy.sendRequest(IdlTestServiceProxy.COMMAND_TEST_STRING_TRANSACTION, _data, _reply, _option).then(function(result) { - if (result.errCode === 0) { + if (result.errCode == 0) { let _errCode = result.reply.readInt(); callback(_errCode); } else { - console.log("sendRequest failed, errCode: " + result.errCode); + console.log('sendRequest failed, errCode: ' + result.errCode); } }) } @@ -644,12 +644,12 @@ import nativeMgr from 'nativeManager'; function testIntTransactionCallback(errCode: number, returnValue: number) { - console.log("errCode: " + errCode + " returnValue: " + returnValue); + console.log('errCode: ' + errCode + ' returnValue: ' + returnValue); } function testStringTransactionCallback(errCode: number) { - console.log("errCode: " + errCode); + console.log('errCode: ' + errCode); } function jsProxyTriggerCppStub() @@ -660,6 +660,6 @@ function jsProxyTriggerCppStub() tsProxy.testIntTransaction(10, testIntTransactionCallback); // Call testStringTransaction. - tsProxy.testStringTransaction("test", testIntTransactionCallback); + tsProxy.testStringTransaction('test', testIntTransactionCallback); } ``` diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index ca2c2fda1462b991f8ea60f36b5c181783034874..dba77cf37aab62a7bb4d33b367839a0c0c88bc4e 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -8,14 +8,13 @@ - Quick Start - Getting Started - [Preparations](quick-start/start-overview.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 ArkTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with ArkTS 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) diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability/Readme-EN.md index 0589643e0f9426f76ac25d3616a41c3b54910e2a..6a11f497d375874b96bfed77a77dce033821d6e3 100644 --- a/en/application-dev/ability/Readme-EN.md +++ b/en/application-dev/ability/Readme-EN.md @@ -1,4 +1,5 @@ # Ability Development + - [Ability Framework Overview](ability-brief.md) - [Context Usage](context-userguide.md) - FA Model @@ -19,5 +20,3 @@ - [Ability Assistant Usage](ability-assistant-guidelines.md) - [ContinuationManager Development](continuationmanager.md) - [Test Framework Usage](ability-delegator.md) - - diff --git a/en/application-dev/ability/continuationmanager.md b/en/application-dev/ability/continuationmanager.md index a1f5a66478cd53aeabe03ed9be21e08596cb2b6b..20c272e75a16c2bcf14d567c1cbc7afa28a3a69a 100644 --- a/en/application-dev/ability/continuationmanager.md +++ b/en/application-dev/ability/continuationmanager.md @@ -14,20 +14,20 @@ As the entry of the ability continuation capability, **continuationManager** is ## 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.| +| registerContinuation(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.| +| registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\): void | Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.| +| registerContinuation(options?: ContinuationExtraParams): Promise\ | Registers the continuation management service and obtains a token. This API uses a promise to return the result.| +| on(type: "deviceSelected", token: number, callback: Callback\>): void | Subscribes to device connection events. This API uses an asynchronous callback to return the result.| +| on(type: "deviceUnselected", token: number, callback: Callback\>): void | Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.| +| off(type: "deviceSelected", token: number): void | Unsubscribes from device connection events.| +| off(type: "deviceUnselected", token: number): void | Unsubscribes from device disconnection events.| +| startContinuationDeviceManager(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.| +| startContinuationDeviceManager(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.| +| startContinuationDeviceManager(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.| +| updateContinuationState(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.| +| updateContinuationState(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.| +| unregisterContinuation(token: number, callback: AsyncCallback\): void | Deregisters the continuation management service. This API uses an asynchronous callback to return the result.| +| unregisterContinuation(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. @@ -36,7 +36,7 @@ As the entry of the ability continuation capability, **continuationManager** is import continuationManager from '@ohos.continuation.continuationManager'; ``` -2. Apply for permissions required for cross-device continuation or collaboration operations. +2. Apply for the **DISTRIBUTED_DATASYNC** permission. 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: @@ -57,6 +57,7 @@ As the entry of the ability continuation capability, **continuationManager** is ```ts import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; import bundle from '@ohos.bundle'; + import featureAbility from '@ohos.ability.featureAbility'; async function requestPermission() { let permissions: Array = [ @@ -124,7 +125,8 @@ As the entry of the ability continuation capability, **continuationManager** is // If the permission is not granted, call requestPermissionsFromUser to apply for the permission. if (needGrantPermission) { try { - await globalThis.abilityContext.requestPermissionsFromUser(permissions); + // globalThis.context is Ability.context, which must be assigned a value in the MainAbility.ts file in advance. + await globalThis.context.requestPermissionsFromUser(permissions); } catch (err) { console.error('app permission request permissions error' + JSON.stringify(err)); } @@ -140,13 +142,16 @@ As the entry of the ability continuation capability, **continuationManager** is ```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)); - }); + try { + continuationManager.registerContinuation().then((data) => { + console.info('registerContinuation finished, ' + JSON.stringify(data)); + token = data; // Obtain a token and assign a value to the token variable. + }).catch((err) => { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + } ``` 4. Listen for the device connection/disconnection state. @@ -156,28 +161,31 @@ As the entry of the ability continuation capability, **continuationManager** is ```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)); + try { + // The token parameter is the token obtained during the registration. + continuationManager.on("deviceSelected", token, (continuationResults) => { + console.info('registerDeviceSelectedCallback 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' + }; + globalThis.abilityContext.startAbility(want).then((data) => { + console.info('StartRemoteAbility finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('StartRemoteAbility failed, cause: ' + JSON.stringify(err)); + }); }); - }); + } catch (err) { + console.error('on 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). @@ -189,35 +197,43 @@ As the entry of the ability continuation capability, **continuationManager** is 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)); - }); + try { + continuationManager.updateContinuationState(token, remoteDeviceId, deviceConnectStatus).then((data) => { + console.info('updateContinuationState finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('updateContinuationState 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; - } + try { + // The token parameter is the token obtained during the registration. + continuationManager.on("deviceUnselected", token, (continuationResults) => { + console.info('onDeviceUnselected len: ' + continuationResults.length); + if (continuationResults.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. + // Update the device connection state. + let unselectedDeviceId: string = continuationResults[0].id; // 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)); + // The token parameter is the token obtained during the registration, and the unselectedDeviceId parameter is the unselectedDeviceId obtained. + continuationManager.updateContinuationState(token, unselectedDeviceId, deviceConnectStatus).then((data) => { + console.info('updateContinuationState finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + }); }); - }); + } catch (err) { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + } ``` 5. Start the device selection module to show the list of available devices on the network. @@ -231,12 +247,16 @@ As the entry of the ability continuation capability, **continuationManager** is 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)); - }); + try { + // The token parameter is the token obtained during the registration. + continuationManager.startContinuationDeviceManager(token, continuationExtraParams).then((data) => { + console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('startContinuationDeviceManager 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. @@ -244,10 +264,14 @@ As the entry of the ability continuation capability, **continuationManager** is 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)); - }); + try { + // The token parameter is the token obtained during the registration. + continuationManager.unregisterContinuation(token).then((data) => { + console.info('unregisterContinuation finished, ' + JSON.stringify(data)); + }).catch((err) => { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + } ``` diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md index 3a2629a79996660f48dfc247b9a560ea1abe09b4..f6eb70595322d3f3308c00afcc9a5907ff87054f 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability/fa-pageability.md @@ -1,12 +1,16 @@ # Page Ability Development ## Overview + ### Concepts -The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in DevEco Studio, DevEco Studio automatically creates template code. The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**. + +The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in DevEco Studio, DevEco Studio automatically creates template code. + +The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js** or **app.ets**. ### Page Ability Lifecycle -**Ability lifecycle** +Introduction to the Page ability lifecycle: The Page ability lifecycle defines all states of a Page ability, such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. @@ -27,27 +31,30 @@ Description of ability lifecycle states: - **BACKGROUND**: The Page ability runs in the background. After being re-activated, the Page ability enters the **ACTIVE** state. After being destroyed, the Page ability enters the **INITIAL** state. -**The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability.** +The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability. ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) You can override the lifecycle callbacks provided by the Page ability in the **app.js** or **app.ets** file. Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. ### Launch Type + The ability supports two launch types: singleton and multi-instance. + You can specify the launch type by setting **launchType** in the **config.json** file. -**Table 1** Introduction to startup mode +**Table 1** Startup modes | Launch Type | Description |Description | | ----------- | ------- |---------------- | | standard | Multi-instance | A new instance is started each time an ability starts.| -| singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.| +| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| By default, **singleton** is used. ## Development Guidelines + ### Available APIs **Table 2** APIs provided by featureAbility @@ -73,23 +80,21 @@ By default, **singleton** is used. ```javascript import featureAbility from '@ohos.ability.featureAbility' featureAbility.startAbility({ - want: - { - action: "", - entities: [""], - type: "", - deviceId: "", - bundleName: "com.example.myapplication", - /* In the FA model, abilityName consists of package and ability name. */ - abilityName: "com.example.entry.secondAbility", - uri: "" - }, - }, - ); + want: { + action: "", + entities: [""], + type: "", + deviceId: "", + bundleName: "com.example.myapplication", + /* In the FA model, abilityName consists of package and ability name. */ + abilityName: "com.example.entry.secondAbility", + uri: "" + } + }); ``` ### Starting a Remote Page Ability ->Note +>NOTE > >This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 1fddf868604e564e4b6a6701f8d3a8088c4d8326..0eeef8040da8abd9710f3996f0b5f2c65ecf71e2 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat | Class/Interface | Function | Description | | --------------- | -------- | ----------- | -| IRemoteBroker | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | +| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | @@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ``` class ITestAbility : public IRemoteBroker { public: - // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. - virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); + int TRANS_ID_PING_ABILITY = 1; // Define the message code. + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. }; ``` diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index 4c51f50e9c29c9df846011e80c06a46a59045794..a153f69fbfe2b71362a4b7e5808fe57c1b7a4216 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: - - - ``` - { - "module": { - "reqPermissions": [ - "name": "ohos.permission.LOCATION", - "reason": "$string:reason_description", - "usedScene": { - "ability": ["com.myapplication.LocationAbility"], - "when": "inuse" - } - ] - } - } - ``` - - For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 5f6e88fc07c88d3e5913058a26887e818a3cc3bc..07f3425ff5ab3c10beeac312740ff6e756c3cd85 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -1,23 +1,24 @@ # Media -- Audio - - [Audio Overview](audio-overview.md) - - [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) - - [Audio Interruption Mode Development](audio-interruptmode.md) - -- Video - - [Video Playback Development](video-playback.md) - - [Video Recording Development](video-recorder.md) - -- Image +- Audio + - [Audio Overview](audio-overview.md) + - [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) + - [Audio Interruption Mode Development](audio-interruptmode.md) + +- Video + - [Video Playback Development](video-playback.md) + - [Video Recording Development](video-recorder.md) + + +- Image - [Image Development](image.md) - -- Camera - - [Camera Development](camera.md) - - [Distributed Camera Development](remote-camera.md) + +- Camera + - [Camera Development](camera.md) + - [Distributed Camera Development](remote-camera.md) diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 0815ef31a288440271a27a8f03fb417923a46190..539de6bb5c5a0723aa68a8994f7ee1970f393a3f 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,106 +1,101 @@ # Audio Capture Development -## When to Use +## Introduction -You can use the APIs provided by **AudioCapturer** to record raw audio files. +You can use the APIs provided by **AudioCapturer** to record raw audio files, thereby implementing audio data collection. -### State Check +**Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. -During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. +## Working Principles -For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). +This following figure shows the audio capturer state transitions. + +**Figure 1** Audio capturer state transitions + +![audio-capturer-state](figures/audio-capturer-state.png) + +- **PREPARED**: The audio capturer enters this state by calling **create()**. +- **RUNNING**: The audio capturer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. +- **STOPPED**: The audio capturer in the **RUNNING** state can call **stop()** to stop playing audio data. +- **RELEASED**: The audio capturer in the **PREPARED** or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state. -**Figure 1** Audio capturer state +## Constraints -![](figures/audio-capturer-state.png) +Before developing the audio data collection feature, configure the **ohos.permission.MICROPHONE** permission for your application. For details about permission configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). ## How to Develop +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). + 1. Use **createAudioCapturer()** to create an **AudioCapturer** instance. - Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification. + Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording state, and register a callback for notification. ```js - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; - ``` - -2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. -If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md). + import audio from '@ohos.multimedia.audio'; - ```js - audioCapturer.on('stateChange',(state) => { - console.info('AudioCapturerLog: Changed State to : ' + state) - switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } - }); + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + let audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 0 // 0 is the extended flag bit of the audio capturer. The default value is 0. + } + + let audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + console.log('AudioRecLog: Create audio capturer success.'); ``` -3. Use **start()** to start audio recording. +2. Use **start()** to start audio recording. The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers. ```js - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } - ``` - -4. Use **getBufferSize()** to obtain the minimum buffer size to read. + import audio from '@ohos.multimedia.audio'; + + async function startCapturer() { + let state = audioCapturer.state; + // The audio capturer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. + if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || + state != audio.AudioState.STATE_STOPPED) { + console.info('Capturer is not in a correct state to start'); + return; + } + await audioCapturer.start(); - ```js - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); + let state = audioCapturer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.error('AudioRecLog: Capturer start failed'); + } + } ``` -5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording. +3. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application stops the recording. The following example shows how to write recorded data into a file. ```js import fileio from '@ohos.fileio'; + + let state = audioCapturer.state; + // The read operation can be performed only when the state is STATE_RUNNING. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Capturer is not in a correct state to read'); + return; + } - const path = '/data/data/.pulse_dir/capture_js.wav'; + const path = '/data/data/.pulse_dir/capture_js.wav'; // Path for storing the collected audio file. let fd = fileio.openSync(path, 0o102, 0o777); if (fd !== null) { console.info('AudioRecLog: file fd created'); @@ -115,38 +110,140 @@ If an application needs to perform some operations when the audio renderer state console.info('AudioRecLog: file fd opened in append mode'); } - var numBuffersToCapture = 150; + let numBuffersToCapture = 150; // Write data for 150 times. while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); + let buffer = await audioCapturer.read(bufferSize, true); if (typeof(buffer) == undefined) { - console.info('read buffer failed'); + console.info('AudioRecLog: read buffer failed'); } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); + let number = fileio.writeSync(fd, buffer); + console.info(`AudioRecLog: data written: ${number}`); } numBuffersToCapture--; } ``` -6. Once the recording is complete, call **stop()** to stop the recording. +4. Once the recording is complete, call **stop()** to stop the recording. + ```js + async function StopCapturer() { + let state = audioCapturer.state; + // The audio capturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('AudioRecLog: Capturer is not running or paused'); + return; + } + + await audioCapturer.stop(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.error('AudioRecLog: Capturer stop failed'); + } + } ``` - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + +5. After the task is complete, call **release()** to release related resources. + + ```js + async function releaseCapturer() { + let state = audioCapturer.state; + // The audio capturer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('AudioRecLog: Capturer already released'); + return; + } + + await audioCapturer.release(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + } ``` -7. After the task is complete, call **release()** to release related resources. +6. (Optional) Obtain the audio capturer information. + + You can use the following code to obtain the audio capturer information: ```js - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } + // Obtain the audio capturer state. + let state = audioCapturer.state; + + // Obtain the audio capturer information. + let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); + + // Obtain the audio stream information. + let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); + + // Obtain the audio stream ID. + let audioStreamId : number = await audioCapturer.getAudioStreamId(); + + // Obtain the Unix timestamp, in nanoseconds. + let audioTime : number = await audioCapturer.getAudioTime(); + + // Obtain a proper minimum buffer size. + let bufferSize : number = await audioCapturer.getBuffersize(); ``` + +7. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. + + After the mark reached event is subscribed to, when the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. + + ```js + audioCapturer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + ``` + +8. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. + + After the period reached event is subscribed to, each time the number of frames collected by the audio capturer reaches the specified value, a callback is triggered and the specified value is returned. + + ```js + audioCapturer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + ``` + +9. If your application needs to perform some operations when the audio capturer state is updated, it can subscribe to the state change event. When the audio capturer state is updated, the application receives a callback containing the event type. + + ```js + audioCapturer.on('stateChange', (state) => { + console.info(`AudioCapturerLog: Changed State to : ${state}`) + switch (state) { + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } + }); + ``` diff --git a/en/application-dev/media/audio-interruptmode.md b/en/application-dev/media/audio-interruptmode.md index 8be8a00cedd10ff4ecd08ee46d746d9803b3c71a..48a53bf5d5990ac88aae1271466a6aa36d52ac98 100644 --- a/en/application-dev/media/audio-interruptmode.md +++ b/en/application-dev/media/audio-interruptmode.md @@ -1,49 +1,50 @@ # Audio Interruption Mode Development -## When to Use -The audio interruption mode is used to control the playback of multiple audio streams.
-Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**.
-In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID. +## Introduction +The audio interruption mode is used to control the playback of multiple audio streams. + +Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**. -### Asynchronous Operations +In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID. -To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. +**Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. ## How to Develop For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). +1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. + + Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. -1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
- Set parameters of the **AudioRenderer** instance in **audioRendererOptions**.
- This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
- - ```js + This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + +```js import audio from '@ohos.multimedia.audio'; - - 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 audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 - } + 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 audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 + } - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } + var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); +let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` - -2. Set the audio interruption mode. +2. Set the audio interruption mode. + After the **AudioRenderer** instance is initialized, you can set the audio interruption mode.
```js diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 5227f6cdd1b9ec89818b0d1762c99267ec7eba97..92aa1cd4fc35a4b64ad9b1044c1a7bd59f24453d 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -1,25 +1,35 @@ # Audio Playback Development -## When to Use +## Introduction -You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks. +You can use audio playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, and obtain track information. -**Figure 1** Playback status +## Working Principles + +The following figures show the audio playback status changes and the interaction with external modules for audio playback. + +**Figure 1** Audio playback state transition ![en-us_image_audio_state_machine](figures/en-us_image_audio_state_machine.png) -**Note**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value. +**NOTE**: If the status is **Idle**, setting the **src** attribute does not change the status. In addition, after the **src** attribute is set successfully, you must call **reset()** before setting it to another value. -**Figure 2** Layer 0 diagram of audio playback +**Figure 2** Interaction with external modules for audio playback ![en-us_image_audio_player](figures/en-us_image_audio_player.png) +**NOTE**: When a third-party application calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework and outputs the audio data decoded by the software to the audio HDI of the hardware interface layer to implement audio playback. + ## How to Develop For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md#audioplayer). +> **NOTE** +> +> The method for obtaining the path in the FA model is different from that in the stage model. **pathDir** used in the sample code below is an example. You need to obtain the path based on project requirements. For details about how to obtain the path, see [Application Sandbox Path Guidelines](../reference/apis/js-apis-fileio.md#guidelines). + ### Full-Process Scenario The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting the player, and releasing resources. @@ -99,8 +109,9 @@ async function audioPlayerDemo() { setCallBack(audioPlayer); // Set the event callbacks. // 2. Set the URI of the audio file. let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; + let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -118,6 +129,7 @@ async function audioPlayerDemo() { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { @@ -139,8 +151,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; + let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -159,6 +172,7 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // Set the player callbacks. private isNextMusic = false; @@ -185,8 +199,9 @@ export class AudioDemo { async nextMusic(audioPlayer) { this.isNextMusic = true; let nextFdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. - let nextpath = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/02.mp3'; + let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. + let nextpath = pathDir + '/02.mp3' await fileIO.open(nextpath).then((fdNumber) => { nextFdPath = nextFdPath + '' + fdNumber; console.info('open fd success fd is' + nextFdPath); @@ -202,8 +217,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; + let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -222,6 +238,7 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' + export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { @@ -239,8 +256,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. this.setCallBack(audioPlayer); // Set the event callbacks. let fdPath = 'fd://' - // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile" command. - let path = '/data/app/el1/bundle/public/ohos.acts.multimedia.audio.audioplayer/ohos.acts.multimedia.audio.audioplayer/assets/entry/resources/rawfile/01.mp3'; + let pathDir = "/data/storage/el2/base/haps/entry/files" // The method for obtaining pathDir in the FA model is different from that in the stage model. For details, see NOTE just below How to Develop. You need to obtain pathDir based on project requirements. + // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" command. + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index f465db2b88118b77c9a4e64307170da07c3e8918..78650a61d0a803811394e623ab0bc46155438ba9 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -1,8 +1,12 @@ # Audio Recording Development -## When to Use +## Introduction -During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and file path for audio recording. +During audio recording, audio signals are captured, encoded, and saved to files. You can specify parameters such as the sampling rate, number of audio channels, encoding format, encapsulation format, and output file path for audio recording. + +## Working Principles + +The following figures show the audio recording state transition and the interaction with external modules for audio recording. **Figure 1** Audio recording state transition @@ -10,10 +14,16 @@ During audio recording, audio signals are captured, encoded, and saved to files. -**Figure 2** Layer 0 diagram of audio recording +**Figure 2** Interaction with external modules for audio recording ![en-us_image_audio_recorder_zero](figures/en-us_image_audio_recorder_zero.png) +**NOTE**: When a third-party recording application or recorder calls the JS interface provided by the JS interface layer to implement a feature, the framework layer invokes the audio component through the media service of the native framework to obtain the audio data captured through the audio HDI. The framework layer then encodes the audio data through software and saves the encoded and encapsulated audio data to a file to implement audio recording. + +## Constraints + +Before developing audio recording, configure the **ohos.permission.MICROPHONE** permission for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). + ## How to Develop For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md#audiorecorder). diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index 82a0753b66384e6f1a991ba97f7d6c7580936e0e..699eb7cb6cae5f198c1620e22b7c3f0df4a90813 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,214 +1,197 @@ # Audio Rendering Development -## When to Use +## Introduction **AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks. -### Audio Interruption +Before calling the APIs, be familiar with the following terms: -When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop). +- **Audio interruption**: When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. +- **Status check**: During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. +- **Asynchronous operation**: To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). +- **Audio interruption mode**: OpenHarmony provides two audio interruption modes: **shared mode** and **independent mode**. In shared mode, all **AudioRenderer** instances created by the same application share one focus object, and there is no focus transfer inside the application. Therefore, no callback will be triggered. In independent mode, each **AudioRenderer** instance has an independent focus object, and focus preemption occurs. Focus preemption triggers focus transfer, and the **AudioRenderer** instance that originally has the focus receives a notification through the callback. By default, the shared mode is used. You can call **setInterruptMode()** to set the independent mode. -### State Check +## Working Principles -During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior. +The following figure shows the audio renderer state transitions. -**Figure 1** Audio renderer state +Figure 1 Audio renderer state transitions -![](figures/audio-renderer-state.png) +![audio-renderer-state](figures/audio-renderer-state.png) -### Asynchronous Operations - -To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). +- **PREPARED**: The audio renderer enters this state by calling **create()**. +- **RUNNING**: The audio renderer enters this state by calling **start()** when it is in the **PREPARED** state or by calling **start()** when it is in the **STOPPED** state. +- **PAUSED**: The audio renderer in the **RUNNING** state can call **pause()** to pause the audio playback. After the audio playback is paused, it can call **start()** to resume the playback. +- **STOPPED**: The audio renderer in the **PAUSED** or **RUNNING** state can call **stop()** to stop the playback. +- **RELEASED**: The audio renderer in the **PREPARED**, **PAUSED**, or **STOPPED** state can use **release()** to release all occupied hardware and software resources. It will not transit to any other state after it enters the **RELEASED** state. ## How to Develop +For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8). + 1. Use **createAudioRenderer()** to create an **AudioRenderer** instance. - Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. + + +Set parameters of the **AudioRenderer** instance in **audioRendererOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification. ```js - var audioStreamInfo = { + import audio from '@ohos.multimedia.audio'; + + let 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 audioRendererInfo = { + let audioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 + rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. } - - var audioRendererOptions = { + let audioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo - } + } let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + console.log("Create audio renderer success."); ``` -2. Use **on('interrupt')** to subscribe to audio interruption events. - - Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device. - - In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. +2. Use **start()** to start audio rendering. - In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). - ```js - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); + async function startRenderer() { + let state = audioRenderer.state; + // The audio renderer should be in the STATE_PREPARED, STATE_PAUSED, or STATE_STOPPED state after being started. + if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && + state != audio.AudioState.STATE_STOPPED) { + console.info('Renderer is not in a correct state to start'); + return; + } - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); - ``` - -3. Use **start()** to start audio rendering. + await audioRenderer.start(); + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + } + } + ``` The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers. - ```js - async function startRenderer() { - var state = audioRenderer.state; - // The state should be prepared, paused, or stopped. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Renderer is not in a correct state to start'); - return; - } - - await audioRenderer.start(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('Renderer started'); - } else { - console.error('Renderer start failed'); - } - } - ``` -4. Call **write()** to write data to the buffer. +3. Call **write()** to write data to the buffer. Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer. ```js - async function writeBuffer(buf) { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - isPlay = false; - return; - } - let writtenbytes = await audioRenderer.write(buf); - - console.info('Actual written bytes: ' + writtenbytes); - if (writtenbytes < 0) { - console.error('Write buffer failed. check the state of renderer'); - } - } - - // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. - const bufferSize = await audioRenderer.getBufferSize(); - const path = '/data/file_example_WAV_2MG.wav'; - let ss = fileio.createStreamSync(path, 'r'); - const totalSize = 2146166; // file_example_WAV_2MG.wav - let rlen = 0; - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - rlen += 44; - - var id = setInterval(() => { - if (isPlay || isRelease) { - if (rlen >= totalSize || isRelease) { - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - let buf = new ArrayBuffer(bufferSize); - rlen += ss.readSync(buf); - console.info('Total bytes read from file: ' + rlen); - writeBuffer(buf); - } else { - console.info('check after next interval'); - } - } , 30); // interval to be set based on audio file format + import fileio from '@ohos.fileio'; + import audio from '@ohos.multimedia.audio'; + + async function writeBuffer(buf) { + // The write operation can be performed only when the state is STATE_RUNNING. + if (audioRenderer.state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + return; + } + let writtenbytes = await audioRenderer.write(buf); + console.info(`Actual written bytes: ${writtenbytes} `); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } + } + + // Set a proper buffer size for the audio renderer. You can also select a buffer of another size. + const bufferSize = await audioRenderer.getBufferSize(); + let dir = globalThis.fileDir; // You must use the sandbox path. + const path = dir + '/file_example_WAV_2MG.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav + console.info(`file path: ${ path}`); + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = fileio.statSync(path).size; // Size of the file to render. + let discardHeader = new ArrayBuffer(bufferSize); + ss.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + let id = setInterval(() => { + if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + if (audioRenderer.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize) { // The rendering stops if the file finishes reading. + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + }, 30); // The timer interval is set based on the audio format. The unit is millisecond. ``` -5. (Optional) Call **pause()** or **stop()** to pause or stop rendering. +4. (Optional) Call **pause()** or **stop()** to pause or stop rendering. ```js async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } + let state = audioRenderer.state; + // The audio renderer can be paused only when it is in the STATE_RUNNING state. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } } - + async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } - } + let state = audioRenderer.state; + // The audio renderer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` + +5. (Optional) Call **drain()** to clear the buffer. + + ```js + async function drainRenderer() { + let state = audioRenderer.state; + // drain() can be used only when the audio renderer is in the STATE_RUNNING state. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.drain(); + + state = audioRenderer.state; + } ``` 6. After the task is complete, call **release()** to release related resources. @@ -217,19 +200,349 @@ To ensure that the UI thread is not blocked, most **AudioRenderer** calls are as ```js async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } + let state = audioRenderer.state; + // The audio renderer can be released only when it is not in the STATE_RELEASED or STATE_NEW state. + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('Renderer already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + } + ``` - await audioRenderer.release(); +7. (Optional) Obtain the audio renderer information. + + You can use the following code to obtain the audio renderer information: - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } + ```js + // Obtain the audio renderer state. + let state = audioRenderer.state; + + // Obtain the audio renderer information. + let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo(); - } + // Obtain the audio stream information. + let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo(); + + // Obtain the audio stream ID. + let audioStreamId : number = await audioRenderer.getAudioStreamId(); + + // Obtain the Unix timestamp, in nanoseconds. + let audioTime : number = await audioRenderer.getAudioTime(); + + // Obtain a proper minimum buffer size. + let bufferSize : number = await audioRenderer.getBuffersize(); + + // Obtain the audio renderer rate. + let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); ``` + +8. (Optional) Set the audio renderer information. + + You can use the following code to set the audio renderer information: + + ```js + // Set the audio renderer rate to RENDER_RATE_NORMAL. + let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; + await audioRenderer.setRenderRate(renderRate); + + // Set the interruption mode of the audio renderer to SHARE_MODE. + let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; + await audioRenderer.setInterruptMode(interruptMode); + + // Set the volume of the stream to 10. + let volume : number = 10; + await audioRenderer.setVolume(volume); + ``` + +9. (Optional) Use **on('audioInterrupt')** to subscribe to the audio interruption event, and use **off('audioInterrupt')** to unsubscribe from the event. + + Audio interruption means that Stream A will be interrupted when Stream B with a higher or equal priority requests to become active and use the output device. + + In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it. + + In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption-unaware applications can use **audioRenderer.state** to check the audio renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9). + + It should be noted that the audio interruption event subscription of the **AudioRenderer** module is slightly different from **on('interrupt')** in [AudioManager](../reference/apis/js-apis-audio.md#audiomanager). The **on('interrupt')** and **off('interrupt')** APIs are deprecated since API version 9. In the **AudioRenderer** module, you only need to call **on('audioInterrupt')** to listen for focus change events. When the **AudioRenderer** instance created by the application performs actions such as start, stop, and pause, it requests the focus, which triggers focus transfer and in return enables the related **AudioRenderer** instance to receive a notification through the callback. For instances other than **AudioRenderer**, such as frequency modulation (FM) and voice wakeup, the application does not create an instance. In this case, the application can call **on('interrupt')** in **AudioManager** to receive a focus change notification. + + ```js + audioRenderer.on('audioInterrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info(`InterruptType: ${interruptEvent.eventType}`); + console.info(`InterruptForceType: ${interruptEvent.forceType}`); + console.info(`AInterruptHint: ${interruptEvent.hintType}`); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Forcible pausing initiated by the audio framework. To prevent data loss, stop the write operation. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Forcible stopping initiated by the audio framework. To prevent data loss, stop the write operation. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Forcible ducking initiated by the audio framework. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Undocking initiated by the audio framework. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Notify the application that the rendering starts. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Notify the application that the audio stream is interrupted. The application determines whether to continue. (In this example, the application pauses the rendering.) + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); + + audioRenderer.off('audioInterrupt'); // Unsubscribe from the audio interruption event. This event will no longer be received. + ``` + +10. (Optional) Use **on('markReach')** to subscribe to the mark reached event, and use **off('markReach')** to unsubscribe from the event. + + After the mark reached event is subscribed to, when the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. + + ```js + audioRenderer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The renderer reached frame: ${reachNumber}`); + }); + + audioRenderer.off('markReach'); // Unsubscribe from the mark reached event. This event will no longer be listened for. + ``` + +11. (Optional) Use **on('periodReach')** to subscribe to the period reached event, and use **off('periodReach')** to unsubscribe from the event. + + After the period reached event is subscribed to, each time the number of frames rendered by the audio renderer reaches the specified value, a callback is triggered and the specified value is returned. + + ```js + audioRenderer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); + + audioRenderer.off('periodReach'); // Unsubscribe from the period reached event. This event will no longer be listened for. + ``` + +12. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes. + + After the **stateChange** event is subscribed to, when the audio renderer state changes, a callback is triggered and the audio renderer state is returned. + + ```js + audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + ``` + +13. (Optional) Handle exceptions of **on()**. + + If the string or the parameter type passed in **on()** is incorrect , the application throws an exception. In this case, you can use **try catch** to capture the exception. + + ```js + try { + audioRenderer.on('invalidInput', () => { // The string does not match. + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // The application throws exception 401. + } + try { + audioRenderer.on(1, () => { // The type of the input parameter is incorrect. + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // The application throws exception 6800101. + } + ``` + +14. (Optional) Refer to the complete example of **on('audioInterrupt')**. + + Create **AudioRender1** and **AudioRender2** in an application, configure the independent interruption mode, and call **on('audioInterrupt')** to subscribe to audio interruption events. At the beginning, **AudioRender1** has the focus. When **AudioRender2** attempts to obtain the focus, **AudioRenderer1** receives a focus transfer notification and the related log information is printed. If the shared mode is used, the log information will not be printed during application running. + + ```js + async runningAudioRender1(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + // 1.1 Create an instance. + audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 1 success."); + + // 1.2 Set the independent mode. + audioRenderer1.setInterruptMode(1).then( data => { + console.info('audioRenderer1 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); + }); + + // 1.3 Set the listener. + audioRenderer1.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + // 1.4 Start rendering. + await audioRenderer1.start(); + console.info('startAudioRender1 success'); + + // 1.5 Obtain the buffer size, which is the proper minimum buffer size of the audio renderer. You can also select a buffer of another size. + const bufferSize = await audioRenderer1.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + // 1.6 Obtain the original audio data file. + let dir = globalThis.fileDir; // You must use the sandbox path. + const path1 = dir + '/music001_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav + console.info(`audioRender1 file path: ${ path1}`); + let ss1 = await fileio.createStream(path1,'r'); + const totalSize1 = fileio.statSync(path1).size; // Size of the file to render. + console.info(`totalSize1 -------: ${totalSize1}`); + let discardHeader = new ArrayBuffer(bufferSize); + ss1.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + // 1.7 Render the original audio data in the buffer by using audioRenderer. + let id = setInterval(async () => { + if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. + ss1.closeSync(); + audioRenderer1.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize1) { // The rendering stops if the file finishes reading. + ss1.closeSync(); + await audioRenderer1.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss1.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer1); + } else { + console.info('check after next interval'); + } + }, 30); // The timer interval is set based on the audio format. The unit is millisecond. + } + + async runningAudioRender2(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0 is the extended flag bit of the audio renderer. The default value is 0. + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + // 2.1 Create another instance. + audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 2 success."); + + // 2.2 Set the independent mode. + audioRenderer2.setInterruptMode(1).then( data => { + console.info('audioRenderer2 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); + }); + + // 2.3 Set the listener. + audioRenderer2.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + // 2.4 Start rendering. + await audioRenderer2.start(); + console.info('startAudioRender2 success'); + + // 2.5 Obtain the buffer size. + const bufferSize = await audioRenderer2.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + // 2.6 Read the original audio data file. + let dir = globalThis.fileDir; // You must use the sandbox path. + const path2 = dir + '/music002_48000_32_1.wav'; // The file to render is in the following path: /data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav + console.error(`audioRender1 file path: ${ path2}`); + let ss2 = await fileio.createStream(path2,'r'); + const totalSize2 = fileio.statSync(path2).size; // Size of the file to render. + console.error(`totalSize2 -------: ${totalSize2}`); + let discardHeader2 = new ArrayBuffer(bufferSize); + ss2.readSync(discardHeader2); + let rlen = 0; + rlen += bufferSize; + + // 2.7 Render the original audio data in the buffer by using audioRenderer. + let id = setInterval(async () => { + if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // The rendering stops if the audio renderer is in the STATE_RELEASED state. + ss2.closeSync(); + that.audioRenderer2.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize2) { // The rendering stops if the file finishes reading. + ss2.closeSync(); + await audioRenderer2.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss2.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer2); + } else { + console.info('check after next interval'); + } + }, 30); // The timer interval is set based on the audio format. The unit is millisecond. + } + + async writeBuffer(buf, audioRender) { + let writtenbytes; + await audioRender.write(buf).then((value) => { + writtenbytes = value; + console.info(`Actual written bytes: ${writtenbytes} `); + }); + if (typeof(writtenbytes) != 'number' || writtenbytes < 0) { + console.error('get Write buffer failed. check the state of renderer'); + } + } + + // Integrated invoking entry. + async test(){ + await runningAudioRender1(); + await runningAudioRender2(); + } + + ``` diff --git a/en/application-dev/media/audio-stream-manager.md b/en/application-dev/media/audio-stream-manager.md index eb89957e9b8793b149c368445f1232bf0ff3b563..44ec37cd11f3666131214e5e908a1ce761fea111 100644 --- a/en/application-dev/media/audio-stream-manager.md +++ b/en/application-dev/media/audio-stream-manager.md @@ -1,57 +1,61 @@ # Audio Stream Management Development -## When to Use +## Introduction You can use **AudioStreamManager** to manage audio streams. -### Development Process +## Working Principles -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. +The following figure shows the calling relationship of **AudioStreamManager** APIs. -For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). +**Figure 1** AudioStreamManager API calling relationship -**Figure 1** Audio stream management invoking relationship +![en-us_image_audio_stream_manager](figures/en-us_image_audio_stream_manager.png) -![](figures/en-us_image_audio_stream_manager.png) +**NOTE**: 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. ## How to Develop +For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9). + 1. Create an **AudioStreamManager** instance. Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. ```js - var audioStreamManager = audio.getStreamManager(); + var audioManager = audio.getAudioManager(); + var audioStreamManager = audioManager.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); - } - } - }); - ``` + 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. @@ -61,30 +65,31 @@ If an application needs to receive notifications when the audio playback applica ``` 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); - } - } - }); - ``` + 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. @@ -94,65 +99,66 @@ If an application needs to receive notifications when the audio recording applic ``` 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('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); - } - } - } - }).catch((err) => { - console.log('getCurrentAudioRendererInfoArray :ERROR: ' + err.message); - }); - ``` + + 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('ChannelMask:' + 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); - }); - ``` + 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/camera.md b/en/application-dev/media/camera.md index 06439dd049be835cdf5a96a35e2a2a42012ee6f8..25e5e573057661487895bc003c143393287b4829 100644 --- a/en/application-dev/media/camera.md +++ b/en/application-dev/media/camera.md @@ -2,7 +2,13 @@ ## When to Use -You can use the camera module to develop basic camera functions, including previewing, photographing, and video recording. +With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zooming control, and many others. + +Before calling camera APIs, be familiar with the following concepts: + +- **Static camera capabilities**: A series of parameters used to describe inherent capabilities of a camera, such as orientation and supported resolution. +- **Physical camera**: An independent camera device. The physical camera ID is a string that uniquely identifies a physical camera. +- **Asynchronous operation**: To prevent the UI thread from being blocked, most **Camera** calls are asynchronous. Each API provides the callback and promise functions. ## How to Develop @@ -12,152 +18,298 @@ For details about the APIs, see [Camera Management](../reference/apis/js-apis-ca ### Full-Process Scenario -The full process includes creating an instance, setting parameters, managing sessions, taking photos, recording videos, and releasing resources. +The full process includes applying for permissions, creating an instance, setting parameters, managing sessions, taking photos, recording videos, and releasing resources. + +#### Applying for Permissions + +You must apply for the permission for your application to access the camera device and other functions. The following table lists camera-related permissions. + +| Permission| Attribute Value | +| -------- | ------------------------------ | +| Camera| ohos.permission.CAMERA | +| Call recording| ohos.permission.MICROPHONE | +| Storage| ohos.permission.WRITE_MEDIA | +| Read| ohos.permission.READ_MEDIA | +| Location| ohos.permission.MEDIA_LOCATION | -The method for creating an XComponent is also provided. For details, see [XComponent Creation](#xcomponent-creation). +The code snippet is as follows: -For details about the APIs used to save images, see [Image Processing](../reference/apis/js-apis-image.md). +```typescript +const PERMISSIONS: Array = [ + 'ohos.permission.CAMERA', + 'ohos.permission.MICROPHONE', + 'ohos.permission.MEDIA_LOCATION', + 'ohos.permission.READ_MEDIA', + 'ohos.permission.WRITE_MEDIA' +] + +function applyPermission() { + console.info('[permission] get permission'); + globalThis.abilityContext.requestPermissionFromUser(PERMISSIONS) + } +``` #### Creating an Instance -```js +You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. If the list is not empty, each ID in the list can be used to create an independent camera instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows: + +```typescript 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); -}) +context: any = getContext(this) +let cameraManager = await camera.getCameraManager(this.context) +if (!cameraManager) { + console.error('Failed to get the CameraManager instance'); +} // Obtain the camera list. -let cameraArray -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 -}) +let cameraArray = await cameraManager.getSupportedCameras() +if (!cameraArray) { + console.error('Failed to get the 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. +for (let index = 0; index < cameraArray.length; index++) { + console.log('cameraId : ' + cameraArray[index].cameraId) // Obtain the camera ID. + console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // Obtain the camera position. + console.log('cameraType : ' + cameraArray[index].cameraType) // Obtain the camera type. + console.log('connectionType : ' + cameraArray[index].connectionType) // Obtain the camera connection type. } // Create a camera input stream. -let cameraInput -await cameraManager.createCameraInput(cameraArray[0].cameraId).then((input) => { - console.log('Promise returned with the CameraInput instance'); - cameraInput = input -}) +let cameraInput = await cameraManager.createCameraInput(cameraArray[0]) + +// Obtain the output stream capabilities supported by the camera. +let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]); +if (!cameraOutputCap) { + console.error("outputCapability outputCapability == null || undefined") +} else { + console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); +} -// Create a preview output stream. -let previewOutput -camera.createPreviewOutput((globalThis.surfaceId), (err, output) => { - if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with previewOutput instance'); - previewOutput = output -}); +let previewProfilesArray = cameraOutputCap.GetPreviewProfiles(); +if (!previewProfilesArray) { + console.error("createOutput previewProfilesArray == null || undefined") +} + +let photoProfilesArray = cameraOutputCap.GetPhotoProfiles(); +if (!photoProfilesArray) { + console.error("createOutput photoProfilesArray == null || undefined") +} + +let videoProfilesArray = cameraOutputCap.GetVideoProfiles(); +if (!videoProfilesArray) { + console.error("createOutput videoProfilesArray == null || undefined") +} + +let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType(); +if (!metadataObjectTypesArray) { + console.error("createOutput metadataObjectTypesArray == null || undefined") +} + +// Create a preview stream. For details about the surfaceId parameter, see the XComponent section. The preview stream is the surface provided by the XComponent. +let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId) +if (!previewOutput) { + console.error("Failed to create the PreviewOutput instance.") +} -// Create an ImageReceiver object and set image parameters. +// Create an ImageReceiver object and set photo parameters. The resolution is set based on the photographing resolutions supported by the current device, which are obtained by photoProfilesArray. let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) // Obtain the surface ID for displaying the photos. let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() // Create a photographing output stream. -let photoOutput -camera.createPhotoOutput((photoSurfaceId), (err, output) => { - if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with the PhotoOutput instance.'); - photoOutput = output -}); +let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId) +if (!photoOutput) { + console.error('Failed to create the PhotoOutput instance.'); + return; +} // Define video recording parameters. -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url : 'file:///data/media/01.mp4', - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, + audioSourceType: 1, + videoSourceType: 1, + profile: { + audioBitrate: 48000, + audioChannels: 2, + audioCodec: 'audio/mp4v-es', + audioSampleRate: 48000, + durationTime: 1000, + fileFormat: 'mp4', + videoBitrate: 48000, + videoCodec: 'video/mp4v-es', + videoFrameWidth: 640, + videoFrameHeight: 480, + videoFrameRate: 30 + }, + url: 'file:///data/media/01.mp4', + orientationHint: 0, + maxSize: 100, + maxDuration: 500, + rotation: 0 } // Create a video recording output stream. let videoRecorder -await media.createVideoRecorder().then((recorder) => { +media.createVideoRecorder().then((recorder) => { console.log('createVideoRecorder called') videoRecorder = recorder }) // Set video recording parameters. -await videoRecorder.prepare(videoConfig) +videoRecorder.prepare(videoConfig) // Obtain the surface ID for video recording. -await videoRecorder.getInputSurface().then((id) => { +let videoSurfaceId +videoRecorder.getInputSurface().then((id) => { console.log('getInputSurface called') videoSurfaceId = id }) -``` -For details about how to create a video recorder, see [Video Recording Development](./video-recorder.md). -```js + // Create a VideoOutput object. -let videoOutput -camera.createVideoOutput((surfaceId), (err, output) => { - if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); - return; +let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId) +if (!videoOutput) { + console.error('Failed to create the videoOutput instance.'); + return; +} +``` +Surfaces must be created in advance for the preview, shooting, and video recording stream. The preview stream is the surface provided by the **XComponent**, the shooting stream is the surface provided by **ImageReceiver**, and the video recording stream is the surface provided by **VideoRecorder**. + +**XComponent** + +```typescript +mXComponentController: XComponentController = new XComponentController // Create an XComponentController. + +build() { + Flex() { + XComponent({ // Create an XComponent. + id: '', + type: 'surface', + libraryname: '', + controller: this.mXComponentController + }) + .onload(() => { // Set the onload callback. + // Set the surface width and height (1920 x 1080). For details about how to set the preview size, see the preview resolutions supported by the current device, which are obtained by previewProfilesArray. + this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) + // Obtain the surface ID. + globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() + }) + .width('1920px') // Set the width of the XComponent. + .height('1080px') // Set the height of the XComponent. } - console.log('Callback returned with the VideoOutput instance'); - videoOutput = output -}); +} +``` + +**ImageReceiver** + +```typescript +function getImageReceiverSurfaceId() { + let receiver = image.createImageReceiver(640, 480, 4, 8) + console.log(TAG + 'before ImageReceiver check') + if (receiver !== undefined) { + console.log('ImageReceiver is ok') + surfaceId1 = receiver.getReceivingSurfaceId() + console.log('ImageReceived id: ' + JSON.stringify(surfaceId1)) + } else { + console.log('ImageReceiver is not ok') + } + } +``` + +**VideoRecorder** + +```typescript +function getVideoRecorderSurface() { + await getFd('CameraManager.mp4'); + mVideoConfig.url = mFdPath; + media.createVideoRecorder((err, recorder) => { + console.info('Entering create video receiver') + mVideoRecorder = recorder + console.info('videoRecorder is :' + JSON.stringify(mVideoRecorder)) + console.info('videoRecorder.prepare called.') + mVideoRecorder.prepare(mVideoConfig, (err) => { + console.info('videoRecorder.prepare success.') + mVideoRecorder.getInputSurface((err, id) => { + console.info('getInputSurface called') + mVideoSurface = id + console.info('getInputSurface surfaceId: ' + JSON.stringify(mVideoSurface)) + }) + }) + }) + } +``` + +#### Managing Sessions + +##### Creating a Session + +```typescript +// Create a session. +let captureSession = await camera.createCaptureSession() +if (!captureSession) { + console.error('Failed to create the CaptureSession instance.'); + return; +} +console.log('Callback returned with the CaptureSession instance.' + session); + +// Start configuration for the session. +await captureSession.beginConfig() + +// Add the camera input stream to the session. +await captureSession.addInput(cameraInput) + +// Add the preview input stream to the session. +await captureSession.addOutput(previewOutput) + +// Add the photographing output stream to the session. +await captureSession.addOutput(photoOutput) + +// Commit the session configuration. +await captureSession.commitConfig() + +// Start the session. +await captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); +}) +``` +##### Switching a Session + +```typescript +// Stop the session. +await captureSession.stop() + +// Start configuration for the session. +await captureSession.beginConfig() + +// Remove the photographing output stream from the session. +await captureSession.removeOutput(photoOutput) + +// Add a video recording output stream to the session. +await captureSession.addOutput(videoOutput) + +// Commit the session configuration. +await captureSession.commitConfig() + +// Start the session. +await captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); +}) ``` #### Setting Parameters -```js +```typescript // Check whether the camera has flash. -let flashStatus -await cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); - flashStatus = status -}) -if(flashStatus) { +let flashStatus = await captureSession.hasFlash() +if (!flashStatus) { + console.error('Failed to check whether the device has the flash mode.'); +} +console.log('Promise returned with the flash light support status:' + flashStatus); + +if (flashStatus) { // Check whether the auto flash mode is supported. let flashModeStatus - cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { + captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => { if (err) { console.error('Failed to check whether the flash mode is supported. ${err.message}'); return; @@ -167,7 +319,7 @@ if(flashStatus) { }) if(flashModeStatus) { // Set the flash mode to auto. - cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { + captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => { if (err) { console.error('Failed to set the flash mode ${err.message}'); return; @@ -179,7 +331,7 @@ if(flashStatus) { // Check whether the continuous auto focus is supported. let focusModeStatus -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err, status) => { +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => { if (err) { console.error('Failed to check whether the focus mode is supported. ${err.message}'); return; @@ -187,9 +339,9 @@ cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (e console.log('Callback returned with the focus mode support status: ' + status); focusModeStatus = status }) -if(focusModeStatus) { +if (focusModeStatus) { // Set the focus mode to continuous auto focus. - cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, (err) => { + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => { if (err) { console.error('Failed to set the focus mode ${err.message}'); return; @@ -199,18 +351,14 @@ if(focusModeStatus) { } // Obtain the zoom ratio range supported by the camera. -let zoomRatioRange -cameraInput.getZoomRatioRange((err, range) => { - if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); - return; - } - console.log('Callback returned with zoom ratio range: ' + range.length); - zoomRatioRange = range -}) +let zoomRatioRange = await captureSession.getZoomRatioRange() +if (!zoomRatioRange) { + console.error('Failed to get the zoom ratio range.'); + return; +} // Set a zoom ratio. -cameraInput.setZoomRatio(zoomRatioRange[0], (err) => { +captureSession.setZoomRatio(zoomRatioRange[0], async (err) => { if (err) { console.error('Failed to set the zoom ratio value ${err.message}'); return; @@ -219,139 +367,15 @@ cameraInput.setZoomRatio(zoomRatioRange[0], (err) => { }) ``` -#### Managing Sessions - -##### Creating a Session - -```js -// Create a Context object. -let context = featureAbility.getContext() - -// Create a session. -let captureSession -await camera.createCaptureSession((context), (err, session) => { - if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); - return; - } - console.log('Callback returned with the CaptureSession instance.' + session); - captureSession = session -}); - -// Start configuration for the session. -await captureSession.beginConfig((err) => { - if (err) { - console.error('Failed to start the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the begin config success.'); -}); - -// Add the camera input stream to the session. -await captureSession.addInput(cameraInput, (err) => { - if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is added.'); -}); - -// Add the preview input stream to the session. -await captureSession.addOutput(previewOutput, (err) => { - if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); -}); - -// Add the photographing output stream to the session. -await captureSession.addOutput(photoOutput, (err) => { - if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); -}); - -// Commit the session configuration. -await captureSession.commitConfig((err) => { - if (err) { - console.error('Failed to commit the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the commit config success.'); -}); - -// Start the session. -await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); -}) -``` - -##### Switching a Session - -```js -// Stop the session. -await captureSession.stop((err) => { - if (err) { - console.error('Failed to stop the session ${err.message}'); - return; - } - console.log('Callback invoked to indicate the session stop success.'); -}); - -// Start configuration for the session. -await captureSession.beginConfig((err) => { - if (err) { - console.error('Failed to start the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the begin config success.'); -}); - -// Remove the photographing output stream from the session. -await captureSession.removeOutput(photoOutput, (err) => { - if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); -}); - -// Add a video recording output stream to the session. -await captureSession.addOutput(videoOutput, (err) => { - if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); -}); - -// Commit the session configuration. -await captureSession.commitConfig((err) => { - if (err) { - console.error('Failed to commit the configuration. ${err.message}'); - return; - } - console.log('Callback invoked to indicate the commit config success.'); -}); - -// Start the session. -await captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); -}) -``` - #### Taking Photos -```js +```typescript let settings = { quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the image quality to high. rotation: camera.ImageRotation.ROTATION_0 // Set the image rotation angle to 0. } // Use the current photographing settings to take photos. -photoOutput.capture(settings, (err) => { +photoOutput.capture(settings, async (err) => { if (err) { console.error('Failed to capture the photo ${err.message}'); return; @@ -362,9 +386,9 @@ photoOutput.capture(settings, (err) => { #### Recording Videos -```js +```typescript // Start the video recording output stream. -videoOutput.start((err) => { +videoOutput.start(async (err) => { if (err) { console.error('Failed to start the video output ${err.message}'); return; @@ -373,17 +397,17 @@ videoOutput.start((err) => { }); // Start video recording. -await videoRecorder.start().then(() => { +videoRecorder.start().then(() => { console.info('videoRecorder start success'); } // Stop video recording. -await videoRecorder.stop().then(() => { +videoRecorder.stop().then(() => { console.info('stop success'); } // Stop the video recording output stream. -await videoOutput.stop((err) => { +videoOutput.stop((err) => { if (err) { console.error('Failed to stop the video output ${err.message}'); return; @@ -392,81 +416,34 @@ await videoOutput.stop((err) => { }); ``` +For details about the APIs used for saving photos, see [Image Processing](image.md#using-imagereceiver). + #### Releasing Resources -```js +```typescript // Stop the session. -await captureSession.stop((err) => { - if (err) { - console.error('Failed to stop the session ${err.message}'); - return; - } - console.log('Callback invoked to indicate the session stop success.'); -}); +captureSession.stop() + // Release the camera input stream. -await cameraInput.release((err) => { - if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); +cameraInput.release() + // Release the preview output stream. -await previewOutput.release((err) => { - if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); +previewOutput.release() + // Release the photographing output stream. -await photoOutput.release((err) => { - if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); -}); +photoOutput.release() + // Release the video recording output stream. -await videoOutput.release((err) => { - if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); +videoOutput.release() + // Release the session. -await captureSession.release((err) => { - if (err) { - console.error('Failed to release the CaptureSession instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); -}); -``` +captureSession.release() -#### XComponent Creation -The surface ID must be obtained for image preview. +// Set the session to null. +captureSession = null +``` -```js -mXComponentController: XComponentController = new XComponentController // Create an XComponentController. +## Process Flowchart -build() { - Flex() { - XComponent({ // Create an XComponent. - id: '', - type: 'surface', - libraryname: '', - controller: this.mXComponentController - }) - .onload(() => { // Set the onload callback. - // Set the width and height of the surface to 1920 and 1080, respectively. - this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) - // Obtain the surface ID. - globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() - }) - .width('1920px') // Set the width of the XComponent. - .height('1080px') // Set the height of the XComponent. - } -} -``` +The following figure shows the process of using the camera. +![camera_framework process](figures/camera_framework_process.jpg) diff --git a/en/application-dev/media/figures/camera_framework_process.jpg b/en/application-dev/media/figures/camera_framework_process.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1207a9a4adb5d5886f9427b07f0ec7d717fc5bf8 Binary files /dev/null and b/en/application-dev/media/figures/camera_framework_process.jpg differ diff --git a/en/application-dev/media/opensles-capture.md b/en/application-dev/media/opensles-capture.md index 0d0946ca87256f6409a62b81958a2ad784af8161..4e1775e178db20e01f15ee7a9b8f685a5c47b07b 100644 --- a/en/application-dev/media/opensles-capture.md +++ b/en/application-dev/media/opensles-capture.md @@ -1,6 +1,6 @@ # OpenSL ES Audio Recording Development -## When to Use +## Introduction You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. diff --git a/en/application-dev/media/opensles-playback.md b/en/application-dev/media/opensles-playback.md index 661bf70ca1551964b05b086d7ec0ab25f46c984d..fe89bc9553da3163e1e18ca43922ff99e13c1307 100644 --- a/en/application-dev/media/opensles-playback.md +++ b/en/application-dev/media/opensles-playback.md @@ -1,6 +1,6 @@ # OpenSL ES Audio Playback Development -## When to Use +## Introduction You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. @@ -58,7 +58,7 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform 5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. - ``` + ```c++ SLOHBufferQueueItf bufferQueueItf; (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index 6ee5cf660069294f717c5cac614ed707db9f1a8c..b324f19b3cf0f3621bd74809c4f1a2d0b57d0abd 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -1,17 +1,23 @@ # Video Playback Development -## When to Use +## Introduction -You can use video playback APIs to convert video data into visible signals, play the signals using output devices, and manage playback tasks. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback. +You can use video playback APIs to convert audio data into audible analog signals and play the signals using output devices. You can also manage playback tasks. For example, you can start, suspend, stop playback, release resources, set the volume, seek to a playback position, set the playback speed, and obtain track information. This document describes development for the following video playback scenarios: full-process, normal playback, video switching, and loop playback. + +## Working Principles + +The following figures show the video playback state transition and the interaction with external modules for video playback. **Figure 1** Video playback state transition ![en-us_image_video_state_machine](figures/en-us_image_video_state_machine.png) -**Figure 2** Layer 0 diagram of video playback +**Figure 2** Interaction with external modules for video playback ![en-us_image_video_player](figures/en-us_image_video_player.png) +**NOTE**: When a third-party application calls a JS interface provided by the JS interface layer, the framework layer invokes the audio component through the media service of the native framework to output the audio data decoded by the software to the audio HDI. The graphics subsystem outputs the image data decoded by the codec HDI at the hardware interface layer to the display HDI. In this way, video playback is implemented. + *Note: Video playback requires hardware capabilities such as display, audio, and codec.* 1. A third-party application obtains a surface ID from the XComponent. diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md index 62e81cf05c384a7cd1a780c562697be046153d05..bef55899bcb51359a6b6d68ef6d7894d70e435ae 100644 --- a/en/application-dev/media/video-recorder.md +++ b/en/application-dev/media/video-recorder.md @@ -1,17 +1,27 @@ # Video Recording Development -## When to Use +## Introduction -During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording. +You can use video recording APIs to capture audio and video signals, encode them, and save them to files. You can start, suspend, resume, and stop recording, and release resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for video recording. + +## Working Principles + +The following figures show the video recording state transition and the interaction with external modules for video recording. **Figure 1** Video recording state transition ![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) -**Figure 2** Layer 0 diagram of video recording +**Figure 2** Interaction with external modules for video recording ![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) +**NOTE**: When a third-party camera application or system camera calls a JS interface provided by the JS interface layer, the framework layer uses the media service of the native framework to invoke the audio component. Through the audio HDI, the audio component captures audio data, encodes the audio data through software, and saves the encoded audio data to a file. The graphics subsystem captures image data through the video HDI, encodes the image data through the video codec HDI, and saves the encoded image data to a file. In this way, video recording is implemented. + +## Constraints + +Before developing video recording, configure the permissions **ohos.permission.MICROPHONE** and **ohos.permission.CAMERA** for your application. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md). + ## How to Develop For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md#videorecorder9). @@ -147,3 +157,4 @@ export class VideoRecorderDemo { } } ``` + diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index bf16d91435bf68ebd6f93a1a52b5f6da35e67169..0030d1d3cceb059a7f0d4d8308b3ae223e8de990 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -4,6 +4,4 @@ - [Drawing Development](drawing-guidelines.md) - [Raw File Development](rawfile-guidelines.md) - [Native Window Development](native-window-guidelines.md) -- [Using MindSpore Lite for Model Inference](native-window-guidelines.md) - - +- [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md) diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md new file mode 100644 index 0000000000000000000000000000000000000000..06862c299448fea4052c690ac45eb29caae1c636 --- /dev/null +++ b/en/application-dev/quick-start/arkts-rendering-control.md @@ -0,0 +1,282 @@ +# Rendering Control + +ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration. + +## Conditional Rendering + +Use **if/else** for conditional rendering. + + +> **NOTE** +> +> - State variables can be used in the **if/else** statement. +> +> - The **if/else** statement can be used to implement rendering of child components. +> +> - The **if/else** statement must be used in container components. +> +> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\** container component, whose child components can only be **\**, only the **\** component can be used in the **if/else** statement. + + +```ts +Column() { + if (this.count < 0) { + Text('count is negative').fontSize(14) + } else if (this.count % 2 === 0) { + Text('count is even').fontSize(14) + } else { + Text('count is odd').fontSize(14) + } +} +``` + +## Loop Rendering + +You can use **ForEach** to obtain data from arrays and create components for each data item. + +``` +ForEach( + arr: any[], + itemGenerator: (item: any, index?: number) => void, + keyGenerator?: (item: any, index?: number) => string +) +``` + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.| +| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.| +| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.| + +> **NOTE** +> +> - **ForEach** must be used in container components. +> +> - The generated child components should be allowed in the parent container component of **ForEach**. +> +> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**. +> +> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage: +> +> ```ts +> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }), +> item => Text(`${item.i}. item.data.label`), +> item => item.data.id.toString()) +> ``` + +## Example + +```ts +// xxx.ets +@Entry +@Component +struct MyComponent { + @State arr: number[] = [10, 20, 30] + + build() { + Column({ space: 5 }) { + Button('Reverse Array') + .onClick(() => { + this.arr.reverse() + }) + + ForEach(this.arr, (item: number) => { + Text(`item value: ${item}`).fontSize(18) + Divider().strokeWidth(2) + }, (item: number) => item.toString()) + } + } +} +``` + +![forEach1](figures/forEach1.gif) + +## Lazy Loading + +You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration. + +```ts +LazyForEach( + dataSource: IDataSource, + itemGenerator: (item: any) => void, + keyGenerator?: (item: any) => string +): void + +interface IDataSource { + totalCount(): number; + getData(index: number): any; + registerDataChangeListener(listener: DataChangeListener): void; + unregisterDataChangeListener(listener: DataChangeListener): void; +} + +interface DataChangeListener { + onDataReloaded(): void; + onDataAdd(index: number): void; + onDataMove(from: number, to: number): void; + onDataDelete(index: number): void; + onDataChange(index: number): void; +} +``` + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------------------- | ---- | ------------------------------------------------------------ | +| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. | +| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.| +| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.| + +### Description of IDataSource + +| Name | Description | +| ------------------------------------------------------------ | ---------------------- | +| totalCount(): number | Obtains the total number of data records. | +| getData(index: number): any | Obtains the data corresponding to the specified index. | +| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.| +| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.| + +### Description of DataChangeListener + +| Name | Description | +| -------------------------------------------------------- | -------------------------------------- | +| onDataReloaded(): void | Invoked when all data is reloaded. | +| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. | +| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.| +| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. | +| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. | +| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. | +| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.| +| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. | +| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. | + +## Example + +```ts +// xxx.ets +class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = [] + + public totalCount(): number { + return 0 + } + + public getData(index: number): any { + return undefined + } + + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) + } + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + console.info('remove listener') + this.listeners.splice(pos, 1) + } + } + + notifyDataReload(): void { + this.listeners.forEach(listener => { + listener.onDataReloaded() + }) + } + + notifyDataAdd(index: number): void { + this.listeners.forEach(listener => { + listener.onDataAdd(index) + }) + } + + notifyDataChange(index: number): void { + this.listeners.forEach(listener => { + listener.onDataChange(index) + }) + } + + notifyDataDelete(index: number): void { + this.listeners.forEach(listener => { + listener.onDataDelete(index) + }) + } + + notifyDataMove(from: number, to: number): void { + this.listeners.forEach(listener => { + listener.onDataMove(from, to) + }) + } +} + +class MyDataSource extends BasicDataSource { + // Initialize the data list. + private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png'] + + public totalCount(): number { + return this.dataArray.length + } + + public getData(index: number): any { + return this.dataArray[index] + } + + public addData(index: number, data: string): void { + this.dataArray.splice(index, 0, data) + this.notifyDataAdd(index) + } + + public pushData(data: string): void { + this.dataArray.push(data) + this.notifyDataAdd(this.dataArray.length - 1) + } +} + +@Entry +@Component +struct MyComponent { + private data: MyDataSource = new MyDataSource() + + build() { + List({ space: 3 }) { + LazyForEach(this.data, (item: string) => { + ListItem() { + Row() { + Image(item).width(50).height(50) + Text(item).fontSize(20).margin({ left: 10 }) + }.margin({ left: 10, right: 10 }) + } + .onClick(() => { + // The count increases by one each time the list is clicked. + this.data.pushData('/path/image' + this.data.totalCount() + '.png') + }) + }, item => item) + } + } +} +``` + +> **NOTE** +> +> - **LazyForEach** must be used in the container component. Currently, only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time. +> +> - **LazyForEach** must create and only one child component in each iteration. +> +> - The generated child components must be allowed in the parent container component of **LazyForEach**. +> +> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement. +> +> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**. +> +> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage: +> +> ```ts +> LazyForEach(dataSource, +> item => Text(`${item.i}. item.data.label`)), +> item => item.data.id.toString()) +> ``` + +![lazyForEach](figures/lazyForEach.gif) diff --git a/en/application-dev/quick-start/figures/forEach1.gif b/en/application-dev/quick-start/figures/forEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..8e9e35e98b8c5fec6baf58997ae78992a554e069 Binary files /dev/null and b/en/application-dev/quick-start/figures/forEach1.gif differ diff --git a/en/application-dev/quick-start/figures/lazyForEach.gif b/en/application-dev/quick-start/figures/lazyForEach.gif new file mode 100644 index 0000000000000000000000000000000000000000..e8f92b92fd63c572e22964d8caa6132d318cf5bd Binary files /dev/null and b/en/application-dev/quick-start/figures/lazyForEach.gif differ diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index b0496b23ece03d1698df3b88f1002908bd033797..6c2b77d3f903657f7a64bef17799d5ebebd2d88b 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -45,6 +45,7 @@ - [@ohos.application.formInfo](js-apis-formInfo.md) - [@ohos.application.formProvider](js-apis-formprovider.md) - [@ohos.application.missionManager](js-apis-missionManager.md) + - [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md) - [@ohos.application.Want](js-apis-application-Want.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md) @@ -90,8 +91,8 @@ - UI Page - [@ohos.animator](js-apis-animator.md) - [@ohos.mediaquery](js-apis-mediaquery.md) + - [@ohos.promptAction](js-apis-promptAction.md) - [@ohos.router](js-apis-router.md) - - [@ohos.uiAppearance](js-apis-uiappearance.md) - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) @@ -145,7 +146,10 @@ - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) + - [@ohos.data.fileAccess](js-apis-fileAccess.md) + - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileio](js-apis-fileio.md) + - [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) @@ -213,6 +217,7 @@ - [@ohos.geolocation](js-apis-geolocation.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md) - [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md) - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) @@ -261,6 +266,7 @@ - [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) - APIs No Longer Maintained + - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.data.storage](js-apis-data-storage.md) - [@ohos.data.distributedData](js-apis-distributed-data.md) diff --git a/en/application-dev/reference/apis/figures/en-us_image_0001.gif b/en/application-dev/reference/apis/figures/en-us_image_0001.gif new file mode 100644 index 0000000000000000000000000000000000000000..099acf91f8a1a6936c56e0ae09aaf7530b080828 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0001.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0002.gif b/en/application-dev/reference/apis/figures/en-us_image_0002.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e4c041811c24ffba57eee64c64d12532150fe4b Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0002.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0004.gif b/en/application-dev/reference/apis/figures/en-us_image_0004.gif new file mode 100644 index 0000000000000000000000000000000000000000..f622ab0eca3995baece321539984c289ab1b8b1a Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0004.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0005.gif b/en/application-dev/reference/apis/figures/en-us_image_0005.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d904fbfabdc50751afd51e9a29b0aa18c6e445f Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0005.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0006.gif b/en/application-dev/reference/apis/figures/en-us_image_0006.gif new file mode 100644 index 0000000000000000000000000000000000000000..7477b94b0437fadfc2d875841f182648d1bcccc9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0006.gif differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index f321aca70ed972845f73ca702501e574aeafe5e0..8701a6b80d7d54dc8bf6a30850c3551a741e77ed 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -24,7 +24,9 @@ SystemCapability.BundleManager.DistributedBundleFramework For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). -## distributedBundle.getRemoteAbilityInfo +## distributedBundle.getRemoteAbilityInfodeprecated + +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; @@ -51,7 +53,9 @@ This is a system API and cannot be called by third-party applications. -## distributedBundle.getRemoteAbilityInfo +## distributedBundle.getRemoteAbilityInfodeprecated + +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> @@ -81,7 +85,9 @@ This is a system API and cannot be called by third-party applications. | ------------------------------------------------------------ | --------------------------------- | | Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise used to return the remote ability information.| -## distributedBundle.getRemoteAbilityInfos +## distributedBundle.getRemoteAbilityInfosdeprecated + +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; @@ -104,11 +110,13 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.| +| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return the remote ability information.| + +## distributedBundle.getRemoteAbilityInfosdeprecated -## distributedBundle.getRemoteAbilityInfos +> This API is deprecated since API version 9. You are advised to use [getRemoteAbilityInfo](js-apis-distributedBundle.md) instead. getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> diff --git a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md b/en/application-dev/reference/apis/js-apis-application-quickFixManager.md new file mode 100644 index 0000000000000000000000000000000000000000..5abe8c19658d484fb335efc0d3fe8e2aa49bdc48 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-quickFixManager.md @@ -0,0 +1,186 @@ +# quickFixManager + +The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application. + +> **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 + +``` +import quickFixManager from '@ohos.application.quickFixManager'; +``` + +## HapModuleQuickFixInfo + +Defines the quick fix information at the HAP file level. + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| moduleName | Read only | string | Yes | Name of the HAP file. | +| originHapHash | Read only | string | Yes | Hash value of the HAP file. | +| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. | + +## ApplicationQuickFixInfo + +Defines the quick fix information at the application level. + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | Read only | string | Yes | Bundle name of the application. | +| bundleVersionCode | Read only | number | Yes | Internal version number of the application. | +| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. | +| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. | +| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. | +| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. | + +## quickFixManager.applyQuickFix + +applyQuickFix(hapModuleQuickFixFiles: Array\, callback: AsyncCallback\): void; + +Applies a quick fix patch. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| + | callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { + if (error) { + console.info( `applyQuickFix failed with error + ${error}`) + } else { + console.info( 'applyQuickFix success') + } + }) +``` + +## quickFixManager.applyQuickFix + +applyQuickFix(hapModuleQuickFixFiles: Array\): Promise\; + +Applies a quick fix patch. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\ | Promise used to return the result.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { + console.info('applyQuickFix success') + }).catch((error) => { + console.info(`applyQuickFix err: + ${error}`) + }) +``` + +## quickFixManager.getApplicationQuickFixInfo + +getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\): void; + +Obtains the quick fix information of the application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | No|Bundle name of the application. | + | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { + if (error) { + console.info(`getApplicationQuickFixInfo error: + ${error}`) + } else { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + } + }) +``` + +## quickFixManager.getApplicationQuickFixInfo + +getApplicationQuickFixInfo(bundleName: string): Promise\; + +Obtains the quick fix information of the application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | No| Bundle name of the application. | + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| + +**Example** + + ```js + import quickFixManager from '@ohos.application.quickFixManager' + + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + }).catch((error) => { + console.info(`getApplicationQuickFixInfo err: + ${error}`) + }) +``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index acd9ef20950cd35f4f25d0b63b5e33b4e4021e89..8296185a2866ab0148e68ee56e52eea68e708892 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -21,13 +21,11 @@ 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.| +| Name | Type | Readable | Writable| Description | +| --------------------------------------- | ----------| ---- | ---- | ------------------ | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | **Example** @@ -35,6 +33,8 @@ import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio'; const localNetworkId = audio.LOCAL_NETWORK_ID; +const defaultVolumeGroupId = audio.DEFAULT_VOLUME_GROUP_ID; +const defaultInterruptGroupId = audio.DEFAULT_INTERRUPT_GROUP_ID; ``` ## audio.getAudioManager @@ -53,7 +53,7 @@ Obtains an **AudioManager** instance. **Example** ```js -var audioManager = audio.getAudioManager(); +let audioManager = audio.getAudioManager(); ``` ## audio.createAudioRenderer8+ @@ -75,20 +75,20 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to ```js import audio from '@ohos.multimedia.audio'; -var audioStreamInfo = { +let 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 audioRendererInfo = { +let audioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 } -var audioRendererOptions = { +let audioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } @@ -128,25 +128,25 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res ```js import audio from '@ohos.multimedia.audio'; -var audioStreamInfo = { +let 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 audioRendererInfo = { +let audioRendererInfo = { content: audio.ContentType.CONTENT_TYPE_SPEECH, usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, rendererFlags: 0 } -var audioRendererOptions = { +let audioRendererOptions = { streamInfo: audioStreamInfo, rendererInfo: audioRendererInfo } -var audioRenderer; +let audioRenderer; audio.createAudioRenderer(audioRendererOptions).then((data) => { audioRenderer = data; console.info('AudioFrameworkRenderLog: AudioRenderer Created : Success : Stream Type: SUCCESS'); @@ -176,19 +176,19 @@ Creates an **AudioCapturer** instance. This API uses an asynchronous callback to ```js import audio from '@ohos.multimedia.audio'; -var audioStreamInfo = { +let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_2, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } -var audioCapturerInfo = { +let audioCapturerInfo = { source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0 } -var audioCapturerOptions = { +let audioCapturerOptions = { streamInfo: audioStreamInfo, capturerInfo: audioCapturerInfo } @@ -230,24 +230,24 @@ Creates an **AudioCapturer** instance. This API uses a promise to return the res ```js import audio from '@ohos.multimedia.audio'; -var audioStreamInfo = { +let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_2, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } -var audioCapturerInfo = { +let audioCapturerInfo = { source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0 } -var audioCapturerOptions = { +let audioCapturerOptions = { streamInfo: audioStreamInfo, capturerInfo: audioCapturerInfo } -var audioCapturer; +let audioCapturer; audio.createAudioCapturer(audioCapturerOptions).then((data) => { audioCapturer = data; console.info('AudioCapturer Created : Success : Stream Type: SUCCESS'); @@ -264,6 +264,8 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret **System capability**: SystemCapability.Multimedia.Audio.Tone +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -276,12 +278,12 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret ```js import audio from '@ohos.multimedia.audio'; -var audioRendererInfo = { +let audioRendererInfo = { "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, "rendererFlags": 0 } -var tonePlayer; +let tonePlayer; audio.createTonePlayer(audioRendererInfo, (err, data) => { console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`); @@ -302,6 +304,8 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Tone +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -319,12 +323,12 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result. ```js import audio from '@ohos.multimedia.audio'; async function createTonePlayer(){ - var audioRendererInfo = { + let audioRendererInfo = { "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, "rendererFlags": 0 } - let tonePlayer = await audio.createTonePlayer(this.audioRendererInfo); + let tonePlayer = await audio.createTonePlayer(audioRendererInfo); } ``` @@ -340,18 +344,31 @@ 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.| +| ALL9+ | 100 | All public audio streams.
This is a system API.| + +## InterruptRequestResultType9+ + +Enumerates the result types of audio interruption requests. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt + +**System API**: This is a system API. + +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| INTERRUPT_REQUEST_GRANT | 0 | The audio interruption request is accepted.| +| INTERRUPT_REQUEST_REJECT | 1 | The audio interruption request is denied. There may be a stream with a higher priority.| ## InterruptMode9+ Enumerates the audio interruption modes. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Interrupt | Name | Default Value| Description | | ---------------------------- | ------ | ---------- | -| SHARE_MODE | 0 | Shared mode.| -| INDEPENDENT_MODE| 1 | Independent mode. | +| SHARE_MODE | 0 | Shared mode.| +| INDEPENDENT_MODE | 1 | Independent mode.| ## DeviceFlag @@ -361,14 +378,13 @@ Enumerates the audio device flags. | Name | Default Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | -| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API and cannot be called by third-party applications. | +| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API. | | 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 device.
This is a system API and cannot be called by third-party applications. | - +| DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API. | +| DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API. | +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output device.
This is a system API. | ## DeviceRole @@ -381,7 +397,6 @@ Enumerates the audio device roles. | INPUT_DEVICE | 1 | Input role.| | OUTPUT_DEVICE | 2 | Output role.| - ## DeviceType Enumerates the audio device types. @@ -401,16 +416,15 @@ Enumerates the audio device types. | USB_HEADSET | 22 | USB Type-C headset. | | DEFAULT9+ | 1000 | Default device type. | -## ActiveDeviceType +## CommunicationDeviceType9+ -Enumerates the active device types. +Enumerates the device types used for communication. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | -| ------------- | ------ | ---------------------------------------------------- | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO links.| +| Name | Default Value| Description | +| ------------- | ------ | -------------| +| SPEAKER | 2 | Speaker. | ## AudioRingMode @@ -426,7 +440,7 @@ Enumerates the ringer modes. ## AudioSampleFormat8+ -Enumerate the audio sample formats. +Enumerates the audio sample formats. **System capability**: SystemCapability.Multimedia.Audio.Core @@ -439,6 +453,22 @@ Enumerate the audio sample formats. | SAMPLE_FORMAT_S32LE | 3 | Signed 32-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.| | SAMPLE_FORMAT_F32LE9+ | 4 | Signed 32-bit integer, little endian.
Due to system restrictions, only some devices support this sampling format.| +## AudioErrors9+ + +Enumerates the audio error codes. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +| Error Message | Error Code | Error Description | +| ---------------------| --------| ----------------- | +| ERROR_INVALID_PARAM | 6800101 | Invalid parameter. | +| ERROR_NO_MEMORY | 6800102 | Memory allocation failure. | +| ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. | +| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | +| ERROR_TIMEOUT | 6800105 | Processing timeout. | +| ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.| +| ERROR_SYSTEM | 6800301 | System error. | + ## AudioChannel8+ Enumerates the audio channels. @@ -510,18 +540,17 @@ Enumerates the audio stream usage. | STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Used for voice assistant.| | STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| -## FocusType9+ +## InterruptRequestType9+ -Enumerates the focus types. +Enumerates the audio interruption request types. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Core - -| Name | Default Value | Description | -| ---------------------------------- | ------ | ------------------------------- | -| FOCUS_TYPE_RECORDING | 0 | Other audios will be interrupted in recording scenarios. | +**System capability**: SystemCapability.Multimedia.Audio.Interrupt +| Name | Default Value | Description | +| ---------------------------------- | ------ | ------------------------- | +| INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | Default type, which can be used to interrupt audio requests. | ## AudioState8+ @@ -588,29 +617,18 @@ Enumerates the hints provided along with audio interruption. | INTERRUPT_HINT_DUCK | 4 | Ducked the playback. (In ducking, the audio volume is reduced, but not silenced.)| | INTERRUPT_HINT_UNDUCK8+ | 5 | Unducked the playback. | -## InterruptActionType - -Enumerates the returned event types for audio interruption events. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -| Name | Default Value| Description | -| -------------- | ------ | ------------------ | -| TYPE_ACTIVATED | 0 | Focus gain event.| -| TYPE_INTERRUPT | 1 | Audio interruption event.| - ## AudioStreamInfo8+ Describes audio stream information. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory| Description | -| ------------ | ---------------------------------------- | ---- | ------------------ | -| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.| -| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.| -| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. | -| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. | +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------- | ---- | ------------------ | +| samplingRate | [AudioSamplingRate](#audiosamplingrate8) | Yes | Audio sampling rate.| +| channels | [AudioChannel](#audiochannel8) | Yes | Number of audio channels.| +| sampleFormat | [AudioSampleFormat](#audiosampleformat8) | Yes | Audio sample format. | +| encodingType | [AudioEncodingType](#audioencodingtype8) | Yes | Audio encoding type. | ## AudioRendererInfo8+ @@ -624,6 +642,19 @@ Describes audio renderer information. | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| | rendererFlags | number | Yes | Audio renderer flags.| +## InterruptResult9+ + +Describes the audio interruption result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt + +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | +| --------------| -------------------------------------------------------------- | ---- | ---------------- | +| requestResult | [InterruptRequestResultType](#interruptrequestresulttype9) | Yes | Audio interruption request type.| +| interruptNode | number | Yes | Node to interrupt.| + ## AudioRendererOptions8+ Describes audio renderer configurations. @@ -647,31 +678,6 @@ Describes the interruption event received by the application when playback is in | forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.| | hintType | [InterruptHint](#interrupthint) | Yes | Hint provided along the interruption. | -## AudioInterrupt - -Describes input parameters of audio interruption events. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -| Name | Type | Mandatory| Description | -| --------------- | --------------------------- | ---- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | -| contentType | [ContentType](#contenttype) | Yes | Audio content type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite.| - -## InterruptAction - -Describes the callback invoked for audio interruption or focus gain events. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| -| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | -| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| - ## VolumeEvent8+ Describes the event received by the application when the volume is changed. @@ -683,24 +689,42 @@ Describes the event received by the application when the volume is changed. | Name | Type | Mandatory| Description | | ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | | volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume level. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| volume | number | Yes | Volume to set. 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. | +## MicStateChangeEvent9+ + +Describes the event received by the application when the microphone mute status changes. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| mute | boolean | Yes | Mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | + ## ConnectType9+ Enumerates the types of connected devices. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume | Name | Default Value| Description | | :------------------------------ | :----- | :--------------------- | | CONNECT_TYPE_LOCAL | 1 | Local device. | | CONNECT_TYPE_DISTRIBUTED | 2 | Distributed 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 + ## VolumeGroupInfo9+ Describes the volume group information. @@ -717,26 +741,6 @@ Describes the volume group information. | groupName9+ | number | Yes | No | Group name.| | type9+ | [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 Describes the device connection status and device information. @@ -803,889 +807,968 @@ Enumerates the audio scenes. | Name | Default Value| Description | | :--------------------- | :----- | :-------------------------------------------- | | AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | -| AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API and cannot be called by third-party applications.| -| AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.| +| AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API.| +| AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API.| | 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+ +### setAudioParameter + +setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void -getRoutingManager(callback: AsyncCallback<AudioRoutingManager>): void +Sets an audio parameter. This API uses an asynchronous callback to return the result. -Obtains an **AudioRoutingManager** instance. This API uses an asynchronous callback to return the result. +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**System capability**: SystemCapability.Multimedia.Audio.Device +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + +**System capability**: SystemCapability.Multimedia.Audio.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------------------- | ---- | --------------------------------- | -| callback | AsyncCallback<[AudioRoutingManager](#audioroutingmanager9)> | Yes | Callback used to return the **AudioRoutingManager** instance.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| key | string | Yes | Key of the audio parameter to set. | +| value | string | Yes | Value of the audio parameter to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** + ```js -audioManager.getRoutingManager((err, callback) => { +audioManager.setAudioParameter('key_example', 'value_example', (err) => { if (err) { - console.error(`Result ERROR: ${err}`); + console.error(`Failed to set the audio parameter. ${err}`); + return; } - console.info('getRoutingManager Callback SUCCESS.'); - var audioRoutingManager; - audioRoutingManager = callback; + console.info('Callback invoked to indicate a successful setting of the audio parameter.'); }); ``` -### getRoutingManager9+ +### setAudioParameter -getRoutingManager(): Promise<AudioRoutingManager> +setAudioParameter(key: string, value: string): Promise<void> -Obtains an **AudioRoutingManager** instance. This API uses a promise to return the result. +Sets an audio parameter. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. + +**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | string | Yes | Key of the audio parameter to set.| +| value | string | Yes | Value of the audio parameter to set.| **Return value** -| Type | Description | -| ----------------------------------------------------------- | --------------------------------------- | -| Promise<[AudioRoutingManager](#audioroutingmanager9)> | Promise used to return the **AudioRoutingManager** instance.| +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** + ```js -var audioManager = audio.getAudioManager(); -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - var routingManager = value; - console.info('getRoutingManager Promise SUCCESS.'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioManager.setAudioParameter('key_example', 'value_example').then(() => { + console.info('Promise returned to indicate a successful setting of the audio parameter.'); +}); ``` -### setVolume - -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void +### getAudioParameter -Sets the volume for a stream. This API uses an asynchronous callback to return the result. +getAudioParameter(key: string, callback: AsyncCallback<string>): void -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result. -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Core **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. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------------- | +| key | string | Yes | Key of the audio parameter whose value is to be obtained. | +| callback | AsyncCallback<string> | Yes | Callback used to return the value of the audio parameter.| **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioManager.getAudioParameter('key_example', (err, value) => { if (err) { - console.error(`Failed to set the volume. ${err}`); + console.error(`Failed to obtain the value of the audio parameter. ${err}`); return; } - console.info('Callback invoked to indicate a successful volume setting.'); + console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` -### setVolume - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> +### getAudioParameter -Sets the volume for a stream. This API uses a promise to return the result. +getAudioParameter(key: string): Promise<string> -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +Obtains the value of an audio parameter. This API uses a promise to return the result. -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Core **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**.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | string | Yes | Key of the audio parameter whose value is to be obtained.| **Return value** -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise<string> | Promise used to return the value of the audio parameter.| **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioManager.getAudioParameter('key_example').then((value) => { + console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); }); ``` -### getVolume +### setAudioScene8+ -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void -Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +Sets an audio scene. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------- | :--- | :------------------- | +| scene | AudioScene | Yes | Audio scene to set. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +let audioManager = audio.getAudioManager(); +audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { - console.error(`Failed to obtain the volume. ${err}`); + console.error(`Failed to set the audio scene mode.​ ${err}`); return; } - console.info('Callback invoked to indicate that the volume is obtained.'); + console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` -### getVolume +### setAudioScene8+ -getVolume(volumeType: AudioVolumeType): Promise<number> +setAudioScene\(scene: AudioScene\): Promise -Obtains the volume of a stream. This API uses a promise to return the result. +Sets an audio scene. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name| Type | Mandatory| Description | +| :----- | :----------------------------------- | :--- | :------------- | +| scene | AudioScene | Yes | Audio scene to set.| **Return value** -| Type | Description | -| --------------------- | ------------------------- | -| Promise<number> | Promise used to return the volume.| +| Type | Description | +| :------------- | :------------------- | +| Promise | Promise used to return the result.| **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +let audioManager = audio.getAudioManager(); +audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { + console.info('Promise returned to indicate a successful setting of the audio scene mode.'); +}).catch ((err) => { + console.error(`Failed to set the audio scene mode ${err}`); }); ``` -### getMinVolume +### getAudioScene8+ -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +getAudioScene\(callback: AsyncCallback\): void -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +Obtains the audio scene. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| - -**Example** +| Name | Type | Mandatory| Description | +| :------- | :-------------------------------------------------- | :--- | :--------------------------- | +| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene.| + +**Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +let audioManager = audio.getAudioManager(); +audioManager.getAudioScene((err, value) => { if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); + console.error(`Failed to obtain the audio scene mode.​ ${err}`); return; } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); + console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); }); ``` -### getMinVolume - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. +### getAudioScene8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getAudioScene\(\): Promise -**Parameters** +Obtains the audio scene. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +**System capability**: SystemCapability.Multimedia.Audio.Communication **Return value** -| Type | Description | -| --------------------- | ------------------------- | -| Promise<number> | Promise used to return the minimum volume.| +| Type | Description | +| :-------------------------------------------- | :--------------------------- | +| Promise<AudioScene> | Promise used to return the audio scene.| **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +let audioManager = audio.getAudioManager(); +audioManager.getAudioScene().then((value) => { + console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); +}).catch ((err) => { + console.error(`Failed to obtain the audio scene mode ${err}`); }); ``` -### getMaxVolume +### getVolumeManager9+ -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +getVolumeManager(): AudioVolumeManager -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +Obtains an **AudioVolumeManager** instance. **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 -audioManager.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}`); -}); +let audioVolumeManager = audioManager.getVolumeManager(); ``` -### getMaxVolume +### getStreamManager9+ -getMaxVolume(volumeType: AudioVolumeType): Promise<number> +getStreamManager(): AudioStreamManager -Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. +Obtains an **AudioStreamManager** instance. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Core -**Parameters** +**Example** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +```js +let audioStreamManager = audioManager.getStreamManager(); +``` -**Return value** +### getRoutingManager9+ -| Type | Description | -| --------------------- | ----------------------------- | -| Promise<number> | Promise used to return the maximum volume.| +getRoutingManager(): AudioRoutingManager + +Obtains an **AudioRoutingManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); -}); +let audioRoutingManager = audioManager.getRoutingManager(); ``` -### mute +## AudioVolumeManager9+ -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void +Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. -Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. +### getVolumeGroupInfos9+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Obtains the volume groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **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. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| **Example** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info('Callback invoked to indicate that the stream is muted.'); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### mute - -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> +### getVolumeGroupInfos9+ -Mutes or unmutes a stream. This API uses a promise to return the result. +getVolumeGroupInfos(networkId: string\): Promise -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +Obtains the volume groups. This API uses a promise to return the result. -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. **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.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------| ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | **Return value** | Type | Description | | ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); -}); +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} ``` +### getVolumeGroupManager9+ -### isMute - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void -Checks whether a stream is muted. 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.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.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| groupId | number | Yes | Volume group ID. | +| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Yes | Callback used to return the audio group manager.| **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); -``` +``` -### isMute +### getVolumeGroupManager9+ -isMute(volumeType: AudioVolumeType): Promise<boolean> +getVolumeGroupManager(groupId: number\): Promise -Checks whether a stream is muted. This method 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.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **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.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); -}); +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); +console.info('Callback invoked to indicate that the volume group infos list is obtained.'); ``` -### isActive +### on('volumeChange')9+ -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +on(type: 'volumeChange', callback: Callback\): void -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +Subscribes to system volume change events. 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 active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### isActive +## AudioVolumeGroupManager9+ -isActive(volumeType: AudioVolumeType): Promise<boolean> +Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -Checks whether a stream is active. This method uses a promise to return the result. +**System API**: This is a system API. **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 active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| - -**Example** - -```js -audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); -}); -``` - -### setRingerMode +### setVolume9+ -setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -Sets the ringer mode. This API uses an asynchronous callback to return the result. +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. +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------ | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| 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 -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { - console.error(`Failed to set the ringer mode.​ ${err}`); + console.error(`Failed to set the volume. ${err}`); return; } - console.info('Callback invoked to indicate a successful setting of the ringer mode.'); + console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### setRingerMode +### setVolume9+ -setRingerMode(mode: AudioRingMode): Promise<void> +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -Sets the ringer mode. This API uses a promise to return the result. +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. +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------- | ---- | -------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| +| 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 | -| ------------------- | ------------------------------- | +| Type | Description | +| ------------------- | ----------------------------- | | Promise<void> | Promise used to return the result.| **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.info('Promise returned to indicate a successful setting of the ringer mode.'); +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); }); ``` +### getVolume9+ -### getRingerMode - -getRingerMode(callback: AsyncCallback<AudioRingMode>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Obtains the ringer mode. This API uses an asynchronous callback to return the result. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| - -**Example** +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| + +**Example** ```js -audioManager.getRingerMode((err, value) => { +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` +### getVolume9+ -### getRingerMode +getVolume(volumeType: AudioVolumeType): Promise<number> -getRingerMode(): Promise<AudioRingMode> +Obtains the volume of a stream. This API uses a promise to return the result. -Obtains the ringer mode. This API uses a promise to return the result. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System capability**: SystemCapability.Multimedia.Audio.Communication +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ---------------------------------------------- | ------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| **Example** ```js -audioManager.getRingerMode().then((value) => { - console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); }); ``` -### setAudioParameter - -setAudioParameter(key: string, value: string, callback: AsyncCallback<void>): void - -Sets an audio parameter. This API uses an asynchronous callback to return the result. +### getMinVolume9+ -This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------ | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| **Example** ```js -audioManager.setAudioParameter('key_example', 'value_example', (err) => { +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the audio parameter. ${err}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.info('Callback invoked to indicate a successful setting of the audio parameter.'); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### setAudioParameter - -setAudioParameter(key: string, value: string): Promise<void> - -Sets an audio parameter. This API uses a promise to return the result. +### getMinVolume9+ -This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +getMinVolume(volumeType: AudioVolumeType): Promise<number> -**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| key | string | Yes | Key of the audio parameter to set.| -| value | string | Yes | Value of the audio parameter to set.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| **Example** ```js -audioManager.setAudioParameter('key_example', 'value_example').then(() => { - console.info('Promise returned to indicate a successful setting of the audio parameter.'); +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); }); ``` -### getAudioParameter - -getAudioParameter(key: string, callback: AsyncCallback<string>): void +### getMaxVolume9+ -Obtains the value of an audio parameter. This API uses an asynchronous callback to return the result. +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------- | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | -| callback | AsyncCallback<string> | Yes | Callback used to return the value of the audio parameter.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| **Example** ```js -audioManager.getAudioParameter('key_example', (err, value) => { +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the value of the audio parameter. ${err}`); + console.error(`Failed to obtain the maximum volume. ${err}`); return; } - console.info(`Callback invoked to indicate that the value of the audio parameter is obtained ${value}.`); + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getAudioParameter - -getAudioParameter(key: string): Promise<string> +### getMaxVolume9+ -Obtains the value of an audio parameter. This API uses a promise to return the result. +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| key | string | Yes | Key of the audio parameter whose value is to be obtained.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| --------------------- | ----------------------------------- | -| Promise<string> | Promise used to return the value of the audio parameter.| +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| **Example** ```js -audioManager.getAudioParameter('key_example').then((value) => { - console.info(`Promise returned to indicate that the value of the audio parameter is obtained ${value}.`); +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### getDevices +### mute9+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**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 API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +| 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 -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error(`Failed to obtain the device list. ${err}`); + console.error(`Failed to mute the stream. ${err}`); return; } - console.info('Callback invoked to indicate that the device list is obtained.'); + console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### getDevices +### mute9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +Mutes or unmutes a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**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 API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| +| 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<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### setDeviceActive +### isMute9+ -setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Sets a device to the active state. This API uses an asynchronous callback to return the result. +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| 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 -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the active status of the device. ${err}`); + console.error(`Failed to obtain the mute status. ${err}`); return; } - console.info('Callback invoked to indicate that the device is set to the active status.'); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### setDeviceActive +### isMute9+ -setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> +isMute(volumeType: AudioVolumeType): Promise<boolean> -Sets a device to the active state. This API uses a promise to return the result. +Checks whether a stream is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.| -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| 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 -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### isDeviceActive +### setRingerMode9+ -isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -Checks whether a device is active. This API uses an asynchronous callback to return the result. +Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); + console.error(`Failed to set the ringer mode.​ ${err}`); return; } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` +### setRingerMode9+ -### isDeviceActive +setRingerMode(mode: AudioRingMode): Promise<void> -isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> +Sets the ringer mode. This API uses a promise to return the result. -Checks whether a device is active. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the active state of the device.| +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); +}); +``` + +### getRingerMode9+ + +getRingerMode(callback: AsyncCallback<AudioRingMode>): void + +Obtains the ringer mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| + +**Example** + +```js +audioVolumeGroupManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; + } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); +}); +``` + +### getRingerMode9+ + +getRingerMode(): Promise<AudioRingMode> + +Obtains the ringer mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| + +**Example** + +```js +audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` -### setMicrophoneMute +### on('ringerModeChange')9+ + +on(type: 'ringerModeChange', callback: Callback\): void + +Subscribes to ringer mode change events. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| 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 system volume change event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | + +**Example** + +```js +audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); +``` +### setMicrophoneMute9+ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1697,7 +1780,7 @@ Mutes or unmutes the microphone. This API uses an asynchronous callback to retur **Example** ```js -audioManager.setMicrophoneMute(true, (err) => { +audioVolumeGroupManager.setMicrophoneMute(true, (err) => { if (err) { console.error(`Failed to mute the microphone. ${err}`); return; @@ -1706,15 +1789,15 @@ audioManager.setMicrophoneMute(true, (err) => { }); ``` -### setMicrophoneMute +### setMicrophoneMute9+ setMicrophoneMute(mute: boolean): Promise<void> Mutes or unmutes the microphone. This API uses a promise to return the result. -**Required permissions:** ohos.permission.MICROPHONE +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1731,20 +1814,18 @@ Mutes or unmutes the microphone. This API uses a promise to return the result. **Example** ```js -audioManager.setMicrophoneMute(true).then(() => { +audioVolumeGroupManager.setMicrophoneMute(true).then(() => { console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -### isMicrophoneMute +### isMicrophoneMute9+ isMicrophoneMute(callback: AsyncCallback<boolean>): void Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE - -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1755,7 +1836,7 @@ Checks whether the microphone is muted. This API uses an asynchronous callback t **Example** ```js -audioManager.isMicrophoneMute((err, value) => { +audioVolumeGroupManager.isMicrophoneMute((err, value) => { if (err) { console.error(`Failed to obtain the mute status of the microphone. ${err}`); return; @@ -1764,15 +1845,13 @@ audioManager.isMicrophoneMute((err, value) => { }); ``` -### isMicrophoneMute +### isMicrophoneMute9+ isMicrophoneMute(): Promise<boolean> Checks whether the microphone is muted. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE - -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Return value** @@ -1782,20 +1861,17 @@ Checks whether the microphone is muted. This API uses a promise to return the re **Example** - ```js -audioManager.isMicrophoneMute().then((value) => { +audioVolumeGroupManager.isMicrophoneMute().then((value) => { console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### on('volumeChange')8+ +### on('micStateChange')9+ -on(type: 'volumeChange', callback: Callback\): void - -Subscribes to system volume change events. +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void -**System API**: This is a system API. +Subscribes to system mic state change events. 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. @@ -1805,3709 +1881,4263 @@ Currently, when multiple **AudioManager** instances are used in a single process | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | +| type | string | Yes | Event type. The value **'micStateChange'** means the system mic state change event, which is triggered when the system mic state changes.| +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed micr state. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **Example** ```js -audioManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); }); ``` -### on('ringerModeChange')8+ +## AudioStreamManager9+ -on(type: 'ringerModeChange', callback: Callback\): void +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. -Subscribes to ringer mode change events. +### getCurrentAudioRendererInfoArray9+ -**System API**: This is a system API. +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void -**System capability**: SystemCapability.Multimedia.Audio.Communication +Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| 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 system volume change event. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| **Example** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +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}`); + } + } + } + } }); ``` -### on('deviceChange') +### getCurrentAudioRendererInfoArray9+ -on(type: 'deviceChange', callback: Callback): void +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Obtains the information about the current audio renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| 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.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Type | Description | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | **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} `); -}); +async function getCurrentAudioRendererInfoArray(){ + 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}`); + }); +} ``` -### off('deviceChange') +### getCurrentAudioCapturerInfoArray9+ -off(type: 'deviceChange', callback?: Callback): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -Unsubscribes from device change events. +Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| 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.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| **Example** ```js -audioManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +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}`); + } + } + } + } }); ``` -### on('interrupt') +### getCurrentAudioCapturerInfoArray9+ -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> -Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. +Obtains the information about the current audio capturer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | +**Return value** -**Example** +| Type | Description | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | + +**Example** ```js -var interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to gain the audio focus starts.'); - console.info(`Focus gain event: ${InterruptAction} `); - } - if (InterruptAction.actionType === 1) { - console.info('An audio interruption event starts.'); - console.info(`Audio interruption event: ${InterruptAction} `); - } -}); +async function getCurrentAudioCapturerInfoArray(){ + 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}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` -### off('interrupt') +### on('audioRendererChange')9+ -off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -Unsubscribes from audio interruption events. +Subscribes to audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | +| 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. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **Example** ```js -var interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release event: ${InterruptAction} `); +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}`); + } } }); ``` -### setAudioScene8+ +### off('audioRendererChange')9+ -setAudioScene\(scene: AudioScene, callback: AsyncCallback\): void +off(type: "audioRendererChange"): void -Sets an audio scene. This API uses an asynchronous callback to return the result. +Unsubscribes from audio renderer change events. -**System API**: This is a system API. +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**System capability**: SystemCapability.Multimedia.Audio.Communication +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------- | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | + +**Example** + +```js +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 | -| :------- | :----------------------------------- | :--- | :------------------- | -| scene | AudioScene | Yes | Audio scene to set. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| 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 -var audioManager = audio.getAudioManager(); -audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { - if (err) { - console.error(`Failed to set the audio scene mode.​ ${err}`); - return; +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}`); + let 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}`); + } } - console.info('Callback invoked to indicate a successful setting of the audio scene mode.'); }); ``` -### setAudioScene8+ - -setAudioScene\(scene: AudioScene\): Promise +### off('audioCapturerChange')9+ -Sets an audio scene. This API uses a promise to return the result. +off(type: "audioCapturerChange"): void; -**System API**: This is a system API. +Unsubscribes from audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----------------------------------- | :--- | :------------- | -| scene | AudioScene | Yes | Audio scene to set.| - -**Return value** - -| Type | Description | -| :------------- | :------------------- | -| Promise | Promise used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { - console.info('Promise returned to indicate a successful setting of the audio scene mode.'); -}).catch ((err) => { - console.error(`Failed to set the audio scene mode ${err}`); -}); +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); + ``` -### getAudioScene8+ +### isActive9+ -getAudioScene\(callback: AsyncCallback\): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Obtains the audio scene. This API uses an asynchronous callback to return the result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :-------------------------------------------------- | :--- | :--------------------------- | -| callback | AsyncCallback<AudioScene> | Yes | Callback used to return the audio scene.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.getAudioScene((err, value) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the audio scene mode.​ ${err}`); + console.error(`Failed to obtain the active status of the stream. ${err}`); return; } - console.info(`Callback invoked to indicate that the audio scene mode is obtained ${value}.`); + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` +### isActive9+ -### getAudioScene8+ +isActive(volumeType: AudioVolumeType): Promise<boolean> -getAudioScene\(\): Promise +Checks whether a stream is active. This API uses a promise to return the result. -Obtains the audio scene. This API uses a promise to return the result. +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**System capability**: SystemCapability.Multimedia.Audio.Communication +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| :-------------------------------------------- | :--------------------------- | -| Promise<AudioScene> | Promise used to return the audio scene.| +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.getAudioScene().then((value) => { - console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); -}).catch ((err) => { - console.error(`Failed to obtain the audio scene mode ${err}`); +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### getVolumeGroups9+ +## AudioRoutingManager9+ -getVolumeGroups(networkId: string, callback: AsyncCallback\): void +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. -Obtains the volume groups. This API uses an asynchronous callback to return the result. +### getDevices9+ -**System API**: This is a system API. +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -**System capability**: SystemCapability.Multimedia.Audio.Volume +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 | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| 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.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** + ```js -var audioManager = audio.getAudioManager(); -audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); + console.error(`Failed to obtain the device list. ${err}`); return; } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); + console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` -### getVolumeGroups9+ - -getVolumeGroups(networkId: string\): Promise +### getDevices9+ -Obtains the volume groups. This API uses a promise to return the result. +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -**System API**: This is a system API. +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **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. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| **Return value** -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```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)) -} +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); +}); ``` -### getGroupManager9+ - -getGroupManager(groupId: number, callback: AsyncCallback\): void +### on9+ -Obtains the audio group manager. This API uses an asynchronous callback to return the result. +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -**System API**: This is a system API. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | Yes | Volume group ID. | -| callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | Yes | Callback used to return the audio group manager.| - -**Example** - -```js -var audioManager = audio.getAudioManager(); -var audioGroupManager; -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.'); - }); - } -} -``` - -### getGroupManager9+ - -getGroupManager(groupId: number\): Promise - -Obtains the audio group manager. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** +| 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. | -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | Yes | Volume group ID. | +**Error codes** -**Return value** +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). -| Type | Description | -| ------------------- | ----------------------------- | -| Promise< [AudioGroupManager](#audiogroupmanager9) > | Promise used to return the audio group manager.| +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **Example** ```js -var audioManager = audio.getAudioManager(); -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(groupid) - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); - } -} +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); +}); ``` -### getStreamManager9+ +### off9+ -getStreamManager(callback: AsyncCallback\): void +off(type: 'deviceChange', callback?: Callback): void -Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Core +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| - -**Example** - -```js -var audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); -``` - -### getStreamManager9+ - -getStreamManager(): Promise - -Obtains an **AudioStreamManager** instance. This API uses a promise 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.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | -**System capability**: SystemCapability.Multimedia.Audio.Core +**Error codes** -**Return value** +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). -| Type | Description | -| ---------------------------------------------------- | ---------------- | -| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error. | **Example** ```js -var audioManager = audio.getAudioManager(); -var audioStreamManager; -audioManager.getStreamManager().then((data) => { - audioStreamManager = data; - console.info('getStreamManager: Success!'); -}).catch((err) => { - console.error(`getStreamManager: ERROR : ${err}`); +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### requestIndependentInterrupt9+ +### selectInputDevice9+ -requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Requests independent interruption and obtains an interruption session ID. This API uses an asynchronous callback to return the result. +Selects an audio input device. Currently, only one input device can be selected. 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.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ----------------- | -| focusType | [FocusType](#focustype) | Yes | Focus type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | 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'); - } +let inputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function selectInputDevice(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); } ``` -### requestIndependentInterrupt9+ -requestIndependentInterrupt(focusType: FocusType): Promise +### selectInputDevice9+ -Requests independent interruption and obtains an interruption session ID. This API uses a promise to return the result. +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name| Type| Mandatory| Description| -| ------ | ---- | ---- | ---- | -| focusType | [FocusType](#focustype) | Yes | Focus type. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | **Return value** -| Type | Description | -| --------------------------------------------------------- | ------------ | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | 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'); - }); +let inputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; + +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); } ``` -### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void +### setCommunicationDevice9+ -Abandons independent interruption. This API uses an asynchronous callback to return the result. +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void -**System API**: This is a system API. +Sets a communication device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ----------------- | -| focusType | [FocusType](#focustype) | Yes | Focus type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | 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'); +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { + if (err) { + console.error(`Failed to set the active status of the device. ${err}`); + return; } -} + console.info('Callback invoked to indicate that the device is set to the active status.'); +}); ``` -### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType): Promise +### setCommunicationDevice9+ -Abandons independent interruption. This API uses a promise to return the result. +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> -**System API**: This is a system API. +Sets a communication device to the active state. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name| Type| Mandatory| Description| -| ------ | ---- | ---- | ---- | -| focusType | [FocusType](#focustype) | Yes | Focus type. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** -| Type | Description | -| --------------------------------------------------------- | ------------ | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | 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'); - }); -} +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); +}); ``` -## 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 +### isCommunicationDeviceActive9+ -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void -**System API**: This is a system API. +Checks whether a communication device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **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. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to set the volume. ${err}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.info('Callback invoked to indicate a successful volume setting.'); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### 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 +### isCommunicationDeviceActive9+ -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> -**System API**: This is a system API. +Checks whether a communication device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **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**.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| **Return value** -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### getVolume9+ +### selectOutputDevice9+ -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the volume of a stream. 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 an asynchronous callback to return the result. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **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.'); -}); +let outputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +} ``` -### getVolume9+ - -getVolume(volumeType: AudioVolumeType): Promise<number> +### selectOutputDevice9+ -Obtains the volume of a stream. This API uses a promise to return the result. +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Volume +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.Device **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| --------------------- | ------------------------- | -| Promise<number> | Promise used to return the volume.| +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); -}); -``` - -### getMinVolume9+ +let outputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} +``` -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +### selectOutputDeviceByFilter9+ + +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Volume +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. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| +| 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 -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}`); -}); -``` +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 }]; -### getMinVolume9+ +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); +} +``` -getMinVolume(volumeType: AudioVolumeType): Promise<number> +### selectOutputDeviceByFilter9+ -Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Volume +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 | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| --------------------- | ------------------------- | -| Promise<number> | Promise used to return the minimum volume.| +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); -}); +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 }]; + +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +} ``` -### getMaxVolume9+ +## AudioRendererChangeInfoArray9+ -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +Defines an **AudioRenderChangeInfo** array, which is read-only. -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**System API**: This is a system API. +## AudioRendererChangeInfo9+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +Describes the audio renderer change event. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ---------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +import audio from '@ohos.multimedia.audio'; + +let audioStreamManager; +let resultFlag = false; +let audioManager = audio.getAudioManager(); + +audioManager.getStreamManager((err, data) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error(`Get AudioStream Manager : ERROR : ${err}`); + } else { + audioStreamManager = data; + console.info('Get AudioStream Manager : Success'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); -``` -### getMaxVolume9+ +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + 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}`); + let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { + 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(`ResultFlag for ${i} is: ${resultFlag}`); + } + } +}); +``` -getMaxVolume(volumeType: AudioVolumeType): Promise<number> -Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. +## AudioCapturerChangeInfoArray9+ -**System API**: This is a system API. +Defines an **AudioCapturerChangeInfo** array, which is read-only. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Parameters** +## AudioCapturerChangeInfo9+ -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +Describes the audio capturer change event. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Type | Description | -| --------------------- | ----------------------------- | -| Promise<number> | Promise used to return the maximum volume.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -audioGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); -}); -``` - -### mute9+ +import audio from '@ohos.multimedia.audio'; -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void +const audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); -Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. +let resultFlag = false; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + 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}`); + let 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(`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(`ResultFlag for element ${i} is: ${resultFlag}`); + } + } +}); +``` -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +## AudioDeviceDescriptors -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. -**System API**: This is a system API. +## AudioDeviceDescriptor -**System capability**: SystemCapability.Multimedia.Audio.Volume +Describes an audio device. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Device -| 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. | +| 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. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | **Example** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { - if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; +import audio from '@ohos.multimedia.audio'; + +function displayDeviceProp(value) { + deviceRoleValue = value.deviceRole; + deviceTypeValue = value.deviceType; +} + +let deviceRoleValue = null; +let deviceTypeValue = null; +const promise = audio.getAudioManager().getDevices(1); +promise.then(function (value) { + 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'); + } else { + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); } - 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 +## AudioRendererFilter9+ -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Volume +| 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 | -**Parameters** +**Example** -| 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.| +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` -**Return value** +## AudioRenderer8+ -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result.| +Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** ```js -audioGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); -}); +let state = audioRenderer.state; ``` -### isMute9+ - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### getRendererInfo8+ -Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +getRendererInfo(callback: AsyncCallback): void -**System API**: This is a system API. +Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Renderer **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.| +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **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}.`); +audioRenderer.getRendererInfo((err, rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); }); ``` -### isMute9+ - -isMute(volumeType: AudioVolumeType): Promise<boolean> - -Checks whether a stream is muted. This method uses a promise to return the result. - -**System API**: This is a system API. +### getRendererInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getRendererInfo(): Promise -**Parameters** +Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +**System capability**: SystemCapability.Multimedia.Audio.Renderer **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.| +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **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}.`); +audioRenderer.getRendererInfo().then((rendererInfo) => { + 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.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); }); ``` -## AudioStreamManager9+ - -Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. - -### getCurrentAudioRendererInfoArray9+ +### getStreamInfo8+ -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +getStreamInfo(callback: AsyncCallback): void -Obtains the information about the current audio renderers. This API uses an asynchronous callback to return the result. +Obtains the stream information of this **AudioRenderer** instance. 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.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -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}`); - } - } - } - } +audioRenderer.getStreamInfo((err, streamInfo) => { + 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}`); }); ``` -### getCurrentAudioRendererInfoArray9+ +### getStreamInfo8+ -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +getStreamInfo(): Promise -Obtains the information about the current audio renderers. This API uses a promise to return the result. +Obtains the stream information of this **AudioRenderer** instance. 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. | +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -async function getCurrentAudioRendererInfoArray(){ - 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}`); - }); -} +audioRenderer.getStreamInfo().then((streamInfo) => { + 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.error(`ERROR: ${err}`); +}); + ``` -### getCurrentAudioCapturerInfoArray9+ +### getAudioStreamId9+ -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +getAudioStreamId(callback: AsyncCallback): void -Obtains the information about the current audio capturers. This API uses an asynchronous callback to return the result. +Obtains the stream ID of this **AudioRenderer** instance. 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.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -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}`); - } - } - } - } +audioRenderer.getAudioStreamId((err, streamid) => { + console.info(`Renderer GetStreamId: ${streamid}`); }); + ``` -### getCurrentAudioCapturerInfoArray9+ +### getAudioStreamId9+ -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +getAudioStreamId(): Promise -Obtains the information about the current audio capturers. This API uses a promise to return the result. +Obtains the stream ID of this **AudioRenderer** instance. 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. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -async function getCurrentAudioCapturerInfoArray(){ - 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}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - }); -} -``` - -### on('audioRendererChange')9+ +audioRenderer.getAudioStreamId().then((streamid) => { + console.info(`Renderer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void +``` -Subscribes to audio renderer change events. +### start8+ + +start(callback: AsyncCallback): void + +Starts the renderer. This API uses an asynchronous callback to return the result. **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. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -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}`); - } +audioRenderer.start((err) => { + if (err) { + console.error('Renderer start failed.'); + } else { + console.info('Renderer start success.'); } }); + ``` -### off('audioRendererChange')9+ +### start8+ -off(type: "audioRendererChange"); +start(): Promise -Unsubscribes from audio renderer change events. +Starts the renderer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------- | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +audioRenderer.start().then(() => { + console.info('Renderer started'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); + ``` -### on('audioCapturerChange')9+ +### pause8+ -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +pause(callback: AsyncCallback\): void -Subscribes to audio capturer change events. +Pauses rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **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 | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -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}`); - } +audioRenderer.pause((err) => { + if (err) { + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); } }); + ``` -### off('audioCapturerChange')9+ +### pause8+ -off(type: "audioCapturerChange"); +pause(): Promise\ -Unsubscribes from audio capturer change events. +Pauses rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); +audioRenderer.pause().then(() => { + console.info('Renderer paused'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); ``` -## AudioRoutingManager9+ -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. - -### getDevices9+ +### drain8+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +drain(callback: AsyncCallback\): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +Drains the playback buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ +audioRenderer.drain((err) => { if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); + console.error('Renderer drain failed'); } 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.'); - }); + console.info('Renderer drained.'); } -}) -``` - -### getDevices9+ +}); -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +``` -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +### drain8+ -**System capability**: SystemCapability.Multimedia.Audio.Device +drain(): Promise\ -**Parameters** +Drains the playback buffer. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -var audioManager = audio.getAudioManager(); -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.'); - }); - } +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); + ``` -### on9+ +### stop8+ -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +stop(callback: AsyncCallback\): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Stops rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| 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. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ +audioRenderer.stop((err) => { 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); - }); + console.error('Renderer stop failed'); + } else { + console.info('Renderer stopped.'); } }); + ``` -### off9+ +### stop8+ -off(type: 'deviceChange', callback?: Callback): void +stop(): Promise\ -Unsubscribes from device change events. +Stops rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| 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.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -var audioManager = audio.getAudioManager(); -audioManager.getRoutingManager((err,AudioRoutingManager)=>{ - if (err) { - console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } else { - AudioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); - }); - } +audioRenderer.stop().then(() => { + console.info('Renderer stopped successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); -``` -### selectInputDevice9+ +``` -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### release8+ -Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. +release(callback: AsyncCallback\): void -**System API**: This is a system API. +Releases the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js -var audioManager = audio.getAudioManager(); -let inputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -var audioRoutingManager; -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select input devices result callback: SUCCESS'); } - }); - }); -} -``` - -### selectInputDevice9+ - -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +```js +audioRenderer.release((err) => { + if (err) { + console.error('Renderer release failed'); + } else { + console.info('Renderer released.'); + } +}); -**System API**: This is a system API. +``` -Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. +### release8+ -**System capability**: SystemCapability.Multimedia.Audio.Device +release(): Promise\ -**Parameters** +Releases the renderer. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -var audioManager = audio.getAudioManager(); -let inputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -var audioRoutingManager; +audioRenderer.release().then(() => { + console.info('Renderer released successfully'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); -async function getRoutingManager(){ - await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { - console.info('Select input devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); - }); -} ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### write8+ -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +write(buffer: ArrayBuffer, callback: AsyncCallback\): void -**System API**: This is a system API. +Writes the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** -```js -var audioManager = audio.getAudioManager(); -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -var audioRoutingManager; -async function getRoutingManager(){ - 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'); } - }); +```js +let bufferSize; +audioRenderer.getBufferSize().then((data)=> { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); +console.info(`Buffer size: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); } -``` - -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> +let 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.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } +}); -**System API**: This is a system API. +``` -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +### write8+ -**System capability**: SystemCapability.Multimedia.Audio.Device +write(buffer: ArrayBuffer): Promise\ -**Parameters** +Writes the buffer. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js -var audioManager = audio.getAudioManager(); -let outputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -var audioRoutingManager; - -async function getRoutingManager(){ - 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}`); - }); +let bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); +console.info(`BufferSize: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); } -``` +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf).then((writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); -### selectOutputDeviceByFilter9+ +``` -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### getAudioTime8+ -**System API**: This is a system API. +getAudioTime(callback: AsyncCallback\): void -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. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Renderer **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.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** + ```js -var audioManager = audio.getAudioManager(); -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; +audioRenderer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); +}); -async function getRoutingManager(){ - 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'); } - }); - }); -} ``` -### selectOutputDeviceByFilter9+ - -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<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 a promise to return the result. +### getAudioTime8+ -**System capability**: SystemCapability.Multimedia.Audio.Device +getAudioTime(): Promise\ -**Parameters** +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** ```js -var audioManager = audio.getAudioManager(); -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; +audioRenderer.getAudioTime().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); -async function getRoutingManager(){ - 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+ - -Describes the audio renderer change event. +### getBufferSize8+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getBufferSize(callback: AsyncCallback\): void -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. -## AudioRendererChangeInfoArray9+ +**System capability**: SystemCapability.Multimedia.Audio.Renderer -Describes the **AudioRenderChangeInfo** array, which is read-only. +**Parameters** -**System capability**: SystemCapability.Multimedia.Audio.Renderer +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** ```js -import audio from '@ohos.multimedia.audio'; - -var audioStreamManager; -var resultFlag = false; -var audioManager = audio.getAudioManager(); - -audioManager.getStreamManager((err, data) => { +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { if (err) { - console.error(`Get AudioStream Manager : ERROR : ${err}`); - } else { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); + console.error('getBufferSize error'); } }); -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - 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(`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(`ResultFlag for ${i} is: ${resultFlag}`); +``` + +### getBufferSize8+ + +getBufferSize(): Promise\ + +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Return value** + +| Type | Description | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | + +**Example** + +```js +let bufferSize; +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +}); + +``` + +### setRenderRate8+ + +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void + +Sets the render rate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { + if (err) { + console.error('Failed to set params'); + } else { + console.info('Callback invoked to indicate a successful render rate setting.'); + } +}); + +``` + +### setRenderRate8+ + +setRenderRate(rate: AudioRendererRate): Promise\ + +Sets the render rate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | + +**Example** + +```js +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { + console.info('setRenderRate SUCCESS'); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); + +``` + +### getRenderRate8+ + +getRenderRate(callback: AsyncCallback\): void + +Obtains the current render rate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | + +**Example** + +```js +audioRenderer.getRenderRate((err, renderrate) => { + console.info(`getRenderRate: ${renderrate}`); +}); + +``` + +### getRenderRate8+ + +getRenderRate(): Promise\ + +Obtains the current render rate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Return value** + +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | + +**Example** + +```js +audioRenderer.getRenderRate().then((renderRate) => { + console.info(`getRenderRate: ${renderRate}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); + +``` + +### setInterruptMode9+ + +setInterruptMode(mode: InterruptMode): Promise<void> + +Sets the audio interruption mode for the application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | + +**Example** + +```js +let mode = 0; +audioRenderer.setInterruptMode(mode).then(data=>{ + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); +}); + +``` + +### setInterruptMode9+ + +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void + +Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let mode = 1; +audioRenderer.setInterruptMode(mode, (err, data)=>{ + if(err){ + console.error(`setInterruptMode Fail: ${err}`); + } + console.info('setInterruptMode Success!'); +}); + +``` + +### setVolume9+ + +setVolume(volume: number): Promise<void> + +Sets the volume for the application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | -------------- | +| volume | number | Yes | Volume to set. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | + +**Example** + +```js +audioRenderer.setVolume(10).then(data=>{ + console.info('setVolume Success!'); +}).catch((err) => { + console.error(`setVolume Fail: ${err}`); +}); + +``` + +### setVolume9+ + +setVolume(volume: number, callback: AsyncCallback\): void + +Sets the volume for the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| volume | number | Yes | Volume to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +audioRenderer.setVolume(10, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); + } + console.info('setVolume Success!'); +}); + +``` + +### on('audioInterrupt')9+ + +on(type: 'audioInterrupt', callback: Callback\): void + +Subscribes to audio interruption events. This API uses a callback to get interrupt events. + +Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID | Error Message | +| ------- | ------------------------------- | +| 6800101 | if input parameter value error. | + +**Example** + +```js +let isPlay; +let started; +audioRenderer.on('audioInterrupt', async(interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + 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.info('Resume force paused renderer or ignore'); + await audioRenderer.start().then(async function () { + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + started = true; + }).catch((err) => { + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); + started = false; + }); + if (started) { + isPlay = true; + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); + } else { + console.error('AudioInterruptMusic Renderer start failed'); + } + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Choose to pause or ignore'); + if (isPlay == true) { + isPlay == false; + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + } else { + isPlay = true; + console.info('AudioInterruptMusic: Media PLAY : TRUE'); + } + break; + } + } +}); + +``` + +### on('markReach')8+ + +on(type: "markReach", frame: number, callback: Callback<number>): void + +Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| 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('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); + } +}); + +``` + + +### off('markReach') 8+ + +off(type: 'markReach'): void + +Unsubscribes from mark reached events. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | + +**Example** + +```js +audioRenderer.off('markReach'); + +``` + +### on('periodReach') 8+ + +on(type: "periodReach", frame: number, callback: Callback<number>): void + +Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| 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.info('ON Triggered successfully'); + } +}); + +``` + +### off('periodReach') 8+ + +off(type: 'periodReach'): void + +Unsubscribes from period reached events. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | + +**Example** + +```js +audioRenderer.off('periodReach') + +``` + +### on('stateChange')8+ + +on(type: 'stateChange', callback: Callback): void + +Subscribes to state change events. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | + +**Example** + +```js +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); } }); + ``` -## AudioCapturerChangeInfo9+ +## AudioCapturer8+ -Describes the audio capturer change event. +Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. + +### Attributes **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | + +**Example** + +```js +let state = audioCapturer.state; -## AudioCapturerChangeInfoArray9+ +``` -Describes the **AudioCapturerChangeInfo** array, which is read-only. +### getCapturerInfo8+ + +getCapturerInfo(callback: AsyncCallback): void + +Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Capturer +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | + **Example** ```js -import audio from '@ohos.multimedia.audio'; - -const audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { +audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error(`getStreamManager : Error: ${err}`); + console.error('Failed to get capture info'); } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); -var resultFlag = false; -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - 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(`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(`ResultFlag for element ${i} is: ${resultFlag}`); - } - } -}); ``` -## AudioDeviceDescriptor -Describes an audio device. +### getCapturerInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Device +getCapturerInfo(): Promise -| 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. | +Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. -## AudioDeviceDescriptors +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Return value** -Array of [AudioDeviceDescriptor](#audiodevicedescriptor), which is read-only. +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** ```js -import audio from '@ohos.multimedia.audio'; +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}`); + } else { + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); + } +}).catch((err) => { + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); +}); -function displayDeviceProp(value) { - deviceRoleValue = value.deviceRole; - deviceTypeValue = value.deviceType; -} +``` -var deviceRoleValue = null; -var deviceTypeValue = null; -const promise = audio.getAudioManager().getDevices(1); -promise.then(function (value) { - 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'); +### getStreamInfo8+ + +getStreamInfo(callback: AsyncCallback): void + +Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | + +**Example** + +```js +audioCapturer.getStreamInfo((err, streamInfo) => { + if (err) { + console.error('Failed to get stream info'); } else { - console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); + 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}`); } }); + ``` -## AudioRendererFilter9+ +### getStreamInfo8+ -Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. +getStreamInfo(): Promise -**System API**: This is a system API. +Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. -| 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 | +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Return value** + +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; +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}`); +}).catch((err) => { + console.error(`getStreamInfo :ERROR: ${err}`); +}); + +``` + +### getAudioStreamId9+ + +getAudioStreamId(callback: AsyncCallback): void + +Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | + +**Example** + +```js +audioCapturer.getAudioStreamId((err, streamid) => { + console.info(`audioCapturer GetStreamId: ${streamid}`); +}); + +``` + +### getAudioStreamId9+ + +getAudioStreamId(): Promise + +Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Return value** + +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | + +**Example** + +```js +audioCapturer.getAudioStreamId().then((streamid) => { + console.info(`audioCapturer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); + +``` + +### start8+ + +start(callback: AsyncCallback): void + +Starts capturing. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +audioCapturer.start((err) => { + if (err) { + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); + } +}); + ``` -## AudioRenderer8+ -Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. +### start8+ -### Attributes +start(): Promise -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Starts capturing. This API uses a promise to return the result. -| Name | Type | Readable | Writable | Description | -| ------------------ | -------------------------- | -------- | -------- | --------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -var state = audioRenderer.state; +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'); + if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); +}); + ``` -### getRendererInfo8+ +### stop8+ -getRendererInfo(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Stops capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getRendererInfo((err, rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +audioCapturer.stop((err) => { + if (err) { + console.error('Capturer stop failed'); + } else { + console.info('Capturer stopped.'); + } }); + ``` -### getRendererInfo8+ -getRendererInfo(): Promise +### stop8+ -Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. +stop(): Promise -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Stops capturing. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------------------------ | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioRenderer.getRendererInfo().then((rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +audioCapturer.stop().then(() => { + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped:'); + } }).catch((err) => { - console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); + ``` -### getStreamInfo8+ +### release8+ -getStreamInfo(callback: AsyncCallback): void +release(callback: AsyncCallback): void -Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getStreamInfo((err, streamInfo) => { - 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}`); +audioCapturer.release((err) => { + if (err) { + console.error('capturer release failed'); + } else { + console.info('capturer released.'); + } }); + ``` -### getStreamInfo8+ -getStreamInfo(): Promise +### release8+ -Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. +release(): Promise -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Releases this **AudioCapturer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioRenderer.getStreamInfo().then((streamInfo) => { - 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}`); +let 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}`); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### start8+ +### read8+ -start(callback: AsyncCallback): void +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -Starts the renderer. This API uses an asynchronous callback to return the result. +Reads the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** ```js -audioRenderer.start((err) => { - if (err) { - console.error('Renderer start failed.'); - } else { - console.info('Renderer start success.'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + }); +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.info('Success in reading the buffer data'); } }); ``` -### start8+ +### read8+ -start(): Promise +read(size: number, isBlockingRead: boolean): Promise -Starts the renderer. This API uses a promise to return the result. +Reads the buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** ```js -audioRenderer.start().then(() => { - console.info('Renderer started'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +audioCapturer.read(bufferSize, true).then((buffer) => { + console.info('buffer read successfully'); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`ERROR : ${err}`); }); ``` -### pause8+ +### getAudioTime8+ -pause(callback: AsyncCallback\): void +getAudioTime(callback: AsyncCallback): void -Pauses rendering. This API uses an asynchronous callback to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **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** ```js -audioRenderer.pause((err) => { - if (err) { - console.error('Renderer pause failed'); - } else { - console.info('Renderer paused.'); - } +audioCapturer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### pause8+ +### getAudioTime8+ -pause(): Promise\ +getAudioTime(): Promise -Pauses rendering. This API uses a promise to return the result. +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** ```js -audioRenderer.pause().then(() => { - console.info('Renderer paused'); +audioCapturer.getAudioTime().then((audioTime) => { + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` -### drain8+ +### getBufferSize8+ -drain(callback: AsyncCallback\): void +getBufferSize(callback: AsyncCallback): void -Drains the playback buffer. This API uses an asynchronous callback to return the result. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **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 buffer size. | **Example** ```js -audioRenderer.drain((err) => { - if (err) { - console.error('Renderer drain failed'); - } else { - console.info('Renderer drained.'); +audioCapturer.getBufferSize((err, bufferSize) => { + if (!err) { + console.info(`BufferSize : ${bufferSize}`); + audioCapturer.read(bufferSize, true).then((buffer) => { + console.info(`Buffer read is ${buffer}`); + }).catch((err) => { + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + }); } }); ``` -### drain8+ +### getBufferSize8+ -drain(): Promise\ +getBufferSize(): Promise -Drains the playback buffer. This API uses a promise to return the result. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** ```js -audioRenderer.drain().then(() => { - console.info('Renderer drained successfully'); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); + bufferSize = data; }).catch((err) => { - console.error(`ERROR: ${err}`); + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` -### stop8+ +### on('markReach')8+ -stop(callback: AsyncCallback\): void +on(type: "markReach", frame: number, callback: Callback<number>): void -Stops rendering. This API uses an asynchronous callback to return the result. +Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| 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.stop((err) => { - if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); +audioCapturer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### stop8+ +### off('markReach')8+ -stop(): Promise\ +off(type: 'markReach'): void -Stops rendering. This API uses a promise to return the result. +Unsubscribes from mark reached events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -audioRenderer.stop().then(() => { - console.info('Renderer stopped successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioCapturer.off('markReach'); ``` -### release8+ +### on('periodReach')8+ -release(callback: AsyncCallback\): void +on(type: "periodReach", frame: number, callback: Callback<number>): void -Releases the renderer. This API uses an asynchronous callback to return the result. +Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| 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.release((err) => { - if (err) { - console.error('Renderer release failed'); - } else { - console.info('Renderer released.'); +audioCapturer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### release8+ +### off('periodReach')8+ -release(): Promise\ +off(type: 'periodReach'): void -Releases the renderer. This API uses a promise to return the result. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** ```js -audioRenderer.release().then(() => { - console.info('Renderer released successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioCapturer.off('periodReach') ``` -### write8+ +### on('stateChange')8+ -write(buffer: ArrayBuffer, callback: AsyncCallback\): void +on(type: 'stateChange', callback: Callback): void -Writes the buffer. This API uses an asynchronous callback to return the result. +Subscribes to state change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** ```js -var bufferSize; -audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -var context = featureAbility.getContext(); -var path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf, (err, writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio capturer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio capturer state is: STATE_RUNNING'); } }); ``` -### write8+ - -write(buffer: ArrayBuffer): Promise\ +## ToneType9+ -Writes the buffer. This API uses a promise to return the result. +Enumerates the tone types of the player. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Tone -| Type | Description | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Default Value | Description | +| :----------------------------------------------- | :------------ | :-------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | -**Example** +## TonePlayer9+ -```js -var bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`BufferSize: ${bufferSize}`); -var context = featureAbility.getContext(); -var path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf).then((writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. -``` +**System API**: This is a system API. -### getAudioTime8+ +### load9+ -getAudioTime(callback: AsyncCallback\): void +load(type: ToneType, callback: AsyncCallback<void>): void -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { + if (err) { + console.error(`callback call load failed error: ${err.message}`); + return; + } else { + console.info('callback call load success'); + } }); ``` -### getAudioTime8+ +### load9+ -getAudioTime(): Promise\ +load(type: ToneType): Promise<void> -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. +Loads the DTMF tone configuration. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :--------------------- | :-------- | ----------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | **Return value** -| Type | Description | -| ---------------- | ------------------------------------- | -| Promise\ | Promise used to return the timestamp. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioRenderer.getAudioTime().then((timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); }); ``` -### getBufferSize8+ +### start9+ -getBufferSize(callback: AsyncCallback\): void +start(callback: AsyncCallback<void>): void -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { +tonePlayer.start((err) => { if (err) { - console.error('getBufferSize error'); + console.error(`callback call start failed error: ${err.message}`); + return; + } else { + console.info('callback call start success'); } }); ``` -### getBufferSize8+ +### start9+ -getBufferSize(): Promise\ +start(): Promise<void> -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. +Starts DTMF tone playing. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** -| Type | Description | -| ---------------- | --------------------------------------- | -| Promise\ | Promise used to return the buffer size. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -var bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); }); ``` -### setRenderRate8+ +### stop9+ -setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void +stop(callback: AsyncCallback<void>): void -Sets the render rate. This API uses an asynchronous callback to return the result. +Stops the tone that is being played. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ----------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { +tonePlayer.stop((err) => { if (err) { - console.error('Failed to set params'); + console.error(`callback call stop error: ${err.message}`); + return; } else { - console.info('Callback invoked to indicate a successful render rate setting.'); + console.error('callback call stop success '); } }); ``` -### setRenderRate8+ - -setRenderRate(rate: AudioRendererRate): Promise\ - -Sets the render rate. This API uses a promise to return the result. +### stop9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +stop(): Promise<void> -**Parameters** +Stops the tone that is being played. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | --------- | ------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** | Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.info('setRenderRate SUCCESS'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); }); ``` -### getRenderRate8+ +### release9+ -getRenderRate(callback: AsyncCallback\): void +release(callback: AsyncCallback<void>): void -Obtains the current render rate. This API uses an asynchronous callback to return the result. +Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getRenderRate((err, renderrate) => { - console.info(`getRenderRate: ${renderrate}`); +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } }); ``` -### getRenderRate8+ +### release9+ -getRenderRate(): Promise\ +release(): Promise<void> -Obtains the current render rate. This API uses a promise to return the result. +Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** -| Type | Description | -| ------------------------------------------------- | --------------------------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioRenderer.getRenderRate().then((renderRate) => { - console.info(`getRenderRate: ${renderRate}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); ``` -### setInterruptMode9+ - -setInterruptMode(mode: InterruptMode): Promise<void> +## ActiveDeviceType(deprecated) -Sets the audio interruption mode for the application. This API uses a promise to return the result. +Enumerates the active device types. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------ | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Default Value | Description | +| ------------- | ------------- | ------------------------------------------------------------ | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | -**Return value** +## InterruptActionType(deprecated) -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +Enumerates the returned event types for audio interruption events. -**Example** +> **NOTE** +> This API is supported since API version 7 and deprecated since API version 9. -```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((err) => { - console.error(`setInterruptMode Fail: ${err}`); -}); +**System capability**: SystemCapability.Multimedia.Audio.Renderer -``` +| Name | Default Value | Description | +| -------------- | ------------- | ------------------------- | +| TYPE_ACTIVATED | 0 | Focus gain event. | +| TYPE_INTERRUPT | 1 | Audio interruption event. | -### setInterruptMode9+ +## AudioInterrupt(deprecated) -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -Sets the audio interruption mode for the application. This API uses a callback to return the result. +Describes input parameters of audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | --------- | ----------------------------------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | - -**Example** - -```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); - } - console.info('setInterruptMode Success!'); -}); - -``` +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | -### on('interrupt')9+ +## InterruptAction(deprecated) -on(type: 'interrupt', callback: Callback\): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -Subscribes to audio interruption events. This API uses a callback to get interrupt events. +Describes the callback invoked for audio interruption or focus gain events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted. | -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | -**Example** +### setVolume(deprecated) -```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.info('Force paused. Stop writing'); - isPlay = false; - break; - case audio.InterruptHint.INTERRUPT_HINT_STOP: - 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.info('Resume force paused renderer or ignore'); - await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; - }).catch((err) => { - console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); - started = false; - }); - if (started) { - isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); - } else { - console.error('AudioInterruptMusic Renderer start failed'); - } - break; - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Choose to pause or ignore'); - if (isPlay == true) { - isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); - } else { - isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); - } - break; - } - } -}); +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. -### on('markReach')8+ +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. -on(type: "markReach", frame: number, callback: Callback<number>): void +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked. +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **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 | Callback | Yes | Callback invoked when the event is triggered. | +| 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 -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.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.'); }); ``` +### setVolume(deprecated) -### off('markReach') 8+ +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -off(type: 'markReach'): void +Sets the volume for a stream. This API uses a promise to return the result. -Unsubscribes from mark reached events. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setVolume](#setvolume9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**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**. | -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :----------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **markReach**. | +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<void> | Promise used to return the result. | **Example** ```js -audioRenderer.off('markReach'); +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); ``` -### on('periodReach') 8+ +### getVolume(deprecated) -on(type: "periodReach", frame: number, callback: Callback<number>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| 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 | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ----------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume. | **Example** ```js -audioRenderer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.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.'); }); ``` -### off('periodReach') 8+ +### getVolume(deprecated) -off(type: 'periodReach'): void +getVolume(volumeType: AudioVolumeType): Promise<number> -Unsubscribes from period reached events. +Obtains the volume of a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **periodReach**. | +| 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 -audioRenderer.off('periodReach') +audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +}); ``` -### on('stateChange')8+ +### getMinVolume(deprecated) -on(type: 'stateChange', callback: Callback): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Subscribes to state change events. +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume. | **Example** ```js -audioRenderer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio renderer state is: STATE_RUNNING'); +audioManager.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}`); }); ``` -## AudioCapturer8+ +### getMinVolume(deprecated) -Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. +getMinVolume(volumeType: AudioVolumeType): Promise<number> -### Attributes +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. -| Name | Type | Readable | Writable | Description | -| :----------------- | :------------------------- | :------- | :------- | :-------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | +**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 -var state = audioCapturer.state; +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +}); ``` -### getCapturerInfo8+ +### getMaxVolume(deprecated) -getCapturerInfo(callback: AsyncCallback): void +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume. | **Example** ```js -audioCapturer.getCapturerInfo((err, capturerInfo) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Failed to get capture info'); - } else { - console.info('Capturer getCapturerInfo:'); - console.info(`Capturer source: ${capturerInfo.source}`); - console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); + console.error(`Failed to obtain the maximum volume. ${err}`); + return; } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` +### getMaxVolume(deprecated) -### getCapturerInfo8+ +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -getCapturerInfo(): Promise +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | **Return value** -| Type | Description | -| :------------------------------------------------ | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| --------------------- | ------------------------------------------ | +| Promise<number> | Promise used to return the maximum volume. | **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}`); - } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); - } -}).catch((err) => { - console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### getStreamInfo8+ +### mute(deprecated) -getStreamInfo(callback: AsyncCallback): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. + +**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 | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| 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 -audioCapturer.getStreamInfo((err, streamInfo) => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { - console.error('Failed to get stream info'); - } else { - 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}`); + console.error(`Failed to mute the stream. ${err}`); + return; } + console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### getStreamInfo8+ +### mute(deprecated) -getStreamInfo(): Promise +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. +Mutes or unmutes a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. + +**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<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<void> | Promise used to return the result. | **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}`); -}).catch((err) => { - console.error(`getStreamInfo :ERROR: ${err}`); +audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### start8+ +### isMute(deprecated) -start(callback: AsyncCallback): void +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Starts capturing. This API uses an asynchronous callback to return the result. +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| 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 -audioCapturer.start((err) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Capturer start failed.'); - } else { - console.info('Capturer start success.'); + 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}`); }); ``` +### isMute(deprecated) -### start8+ +isMute(volumeType: AudioVolumeType): Promise<boolean> -start(): Promise +Checks whether a stream is muted. This API uses a promise to return the result. -Starts capturing. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| 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 -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'); - if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); - } -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); +audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### stop8+ +### isActive(deprecated) -stop(callback: AsyncCallback): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Stops capturing. This API uses an asynchronous callback to return the result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | **Example** ```js -audioCapturer.stop((err) => { +audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Capturer stop failed'); - } else { - console.info('Capturer stopped.'); + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` +### isActive(deprecated) -### stop8+ +isActive(volumeType: AudioVolumeType): Promise<boolean> -stop(): Promise +Checks whether a stream is active. This API uses a promise to return the result. -Stops capturing. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | **Example** ```js -audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped:'); - } -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); +audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### release8+ +### setRingerMode(deprecated) -release(callback: AsyncCallback): void +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | --------- | ----------------------------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.release((err) => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error('capturer release failed'); - } else { - console.info('capturer released.'); + console.error(`Failed to set the ringer mode.​ ${err}`); + return; } + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` +### setRingerMode(deprecated) -### release8+ +setRingerMode(mode: AudioRingMode): Promise<void> -release(): Promise +Sets the ringer mode. This API uses a promise to return the result. -Releases this **AudioCapturer** instance. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY + +This permission is required only for muting or unmuting the ringer. + +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------------------------------- | --------- | ------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<void> | Promise used to return the result. | **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}`); -}).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` +### getRingerMode(deprecated) -### read8+ +getRingerMode(callback: AsyncCallback<AudioRingMode>): void -read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void +Obtains the ringer mode. This API uses an asynchronous callback to return the result. -Reads the buffer. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. | **Example** ```js -var bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); - }); -audioCapturer.read(bufferSize, true, async(err, buffer) => { - if (!err) { - console.info('Success in reading the buffer data'); +audioManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` +### getRingerMode(deprecated) -### read8+ - -read(size: number, isBlockingRead: boolean): Promise - -Reads the buffer. This API uses a promise to return the result. +getRingerMode(): Promise<AudioRingMode> -**System capability**: SystemCapability.Multimedia.Audio.Capturer +Obtains the ringer mode. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. -| Name | Type | Mandatory | Description | -| :------------- | :------ | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | +**System capability**: SystemCapability.Multimedia.Audio.Communication **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | +| Type | Description | +| ---------------------------------------------- | --------------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. | **Example** ```js -var bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); -}).catch((err) => { - console.info(`ERROR : ${err}`); +audioManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` +### getDevices(deprecated) -### getAudioTime8+ +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -getAudioTime(callback: AsyncCallback): void +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | 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 -audioCapturer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); +audioManager.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.'); }); ``` +### getDevices(deprecated) -### getAudioTime8+ +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -getAudioTime(): Promise +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ------------------ | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| Type | Description | +| ------------------------------------------------------------ | --------------------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. | **Example** ```js -audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); -}).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` +### setDeviceActive(deprecated) -### getBufferSize8+ +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void -getBufferSize(callback: AsyncCallback): void +Sets a device to the active state. This API uses an asynchronous callback to return the result. -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getBufferSize((err, bufferSize) => { - if (!err) { - console.info(`BufferSize : ${bufferSize}`); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ${buffer}`); - }).catch((err) => { - console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); - }); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { + if (err) { + console.error(`Failed to set the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` +### setDeviceActive(deprecated) -### getBufferSize8+ +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> -getBufferSize(): Promise +Sets a device to the active state. This API uses a promise to return the result. -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** -| Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<void> | Promise used to return the result. | **Example** + ```js -var bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); ``` +### isDeviceActive(deprecated) -### on('markReach')8+ +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -on(type: "markReach", frame: number, callback: Callback<number>): void +Checks whether a device is active. This API uses an asynchronous callback to return the result. -Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device **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 | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------------- | --------- | ------------------------------------------------------- | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device. | **Example** ```js -audioCapturer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { + if (err) { + console.error(`Failed to obtain the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### off('markReach')8+ - -off(type: 'markReach'): void - -Unsubscribes from mark reached events. - -**System capability**: SystemCapability.Multimedia.Audio.Capturer - -**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. | - -**Example** - -```js -audioCapturer.off('markReach'); - -``` +### isDeviceActive(deprecated) -### on('periodReach')8+ +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -on(type: "periodReach", frame: number, callback: Callback<number>): void +Checks whether a device is active. This API uses a promise to return the result. -Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| 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 | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------------------- | --------- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the active state of the device. | **Example** ```js -audioCapturer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### off('periodReach')8+ +### setMicrophoneMute(deprecated) -off(type: 'periodReach'): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -Unsubscribes from period reached events. +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| 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. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.off('periodReach') +audioManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); +}); ``` -### on('stateChange')8+ +### setMicrophoneMute(deprecated) -on(type: 'stateChange', callback: Callback): void +setMicrophoneMute(mute: boolean): Promise<void> -Subscribes to state change events. +Mutes or unmutes the microphone. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| ---- | ------- | --------- | ------------------------------------------------------------ | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------- | +| Promise<void> | Promise used to return the result. | **Example** ```js -audioCapturer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio capturer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio capturer state is: STATE_RUNNING'); - } +audioManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -## ToneType 9+ - -Enumerates the tone types of the player. - -**System capability**: SystemCapability.Multimedia.Audio.Tone - -| Name | Default Value | Description | -| :----------------------------------------------- | :------------ | :------------------------------------------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | - -## TonePlayer9+ +### isMicrophoneMute(deprecated) -Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. +isMicrophoneMute(callback: AsyncCallback<boolean>): void -### load9+ +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -load(type: ToneType, callback: AsyncCallback<void>): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. -Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| type | ToneType(#tonetype9) | Yes | Tone type. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { +audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`callback call load failed error: ${err.message}`); + console.error(`Failed to obtain the mute status of the microphone. ${err}`); return; - } else { - console.info('callback call load success'); } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### load9+ +### isMicrophoneMute(deprecated) -load(type: ToneType): Promise<void> +isMicrophoneMute(): Promise<boolean> -Loads the DTMF tone configuration. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. -**Parameters** +**Required permissions**: ohos.permission.MICROPHONE -| Name | Type | Mandatory | Description | -| :--- | :------------------- | :-------- | ----------- | -| type | ToneType(#tonetype9) | Yes | Tone type. | +**System capability**: SystemCapability.Multimedia.Audio.Device **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { - console.info('promise call load '); -}).catch(() => { - console.error('promise call load fail'); +audioManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### start9+ +### on('volumeChange')(deprecated) -start(callback: AsyncCallback<void>): void +on(type: 'volumeChange', callback: Callback\): void -Starts DTMF tone playing. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. -**System capability**: SystemCapability.Multimedia.Audio.Tone +Subscribes to system volume change events. + +**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. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected. | +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.start((err) => { - if (err) { - console.error(`callback call start failed error: ${err.message}`); - return; - } else { - console.info('callback call start success'); - } +audioManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### start9+ +### on('ringerModeChange')(deprecated) -start(): Promise<void> +on(type: 'ringerModeChange', callback: Callback\): void -Starts DTMF tone playing. This API uses a promise to return the result. +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. -**Return value** +**System API**: This is a system API. -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| 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 result. | **Example** ```js -tonePlayer.start().then(() => { - console.info('promise call start'); -}).catch(() => { - console.error('promise call start fail'); +audioManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); }); ``` -### stop9+ +### on('deviceChange')(deprecated) -stop(callback: AsyncCallback<void>): void +on(type: 'deviceChange', callback: Callback): void -Stops the tone that is being played. This API uses an asynchronous callback to return the result. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Tone +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | 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. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | **Example** ```js -tonePlayer.stop((err) => { - if (err) { - console.error(`callback call stop error: ${err.message}`); - return; - } else { - console.error('callback call stop success '); - } +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} `); }); ``` -### stop9+ +### off('deviceChange')(deprecated) -stop(): Promise<void> +off(type: 'deviceChange', callback?: Callback): void -Stops the tone that is being played. This API uses a promise to return the result. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off](#off9) in **AudioRoutingManager**. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| 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. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js -tonePlayer.stop().then(() => { - console.info('promise call stop finish'); -}).catch(() => { - console.error('promise call stop fail'); +audioManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### release9+ +### on('interrupt')(deprecated) -release(callback: AsyncCallback<void>): void +on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -Releases the resources associated with the **TonePlay** instance. This API uses an asynchronous callback to return the result. +Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Tone +Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | **Example** ```js -tonePlayer.release((err) => { - if (err) { - console.error(`callback call release failed error: ${err.message}`); - return; - } else { - console.info('callback call release success '); +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); + } + if (InterruptAction.actionType === 1) { + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); + ``` -### release9+ +### off('interrupt')(deprecated) -release(): Promise<void> +off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -Releases the resources associated with the **TonePlay** instance. This API uses a promise to return the result. +Unsubscribes from audio interruption events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | **Example** ```js -tonePlayer.release().then(() => { - console.info('promise call release'); -}).catch(() => { - console.error('promise call release fail'); +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); + } }); ``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index f44ea5c33a652e87193e1a976c0031dccd049e07..ffde8d4356caee1dde9f47bdbb424d2dbdda57bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -6,7 +6,9 @@ The **RemoteAbilityInfo** module provides information about a remote ability. > > 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. -## RemoteAbilityInfo +## RemoteAbilityInfo(deprecated) + +> This API is deprecated since API version 9. You are advised to use [RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.DistributedBundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md new file mode 100644 index 0000000000000000000000000000000000000000..93b932d3c40ee9bf838f5d2caed848b2916b81cf --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -0,0 +1,22 @@ +# ElementName + +The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). + + +> **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. + +## ElementName + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| deviceId | string | Yes | Yes | Device ID. | +| bundleName | string | Yes | Yes | Bundle name of the application. | +| abilityName | string | Yes | Yes | Name of the ability. | +| uri | string | Yes | Yes | Resource ID. | +| shortName | string | Yes | Yes | Short name of the ability. | +| moduleName | string | Yes | Yes | Module name of the HAP file to which the ability belongs. | + diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..0281e4fc7785bd815c1b988a9f67fb74b5a514de --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md @@ -0,0 +1,19 @@ +# RemoteAbilityInfo + +The **RemoteAbilityInfo** module provides information about a remote ability, which can be obtained through [distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md). + +> **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. + +## RemoteAbilityInfo + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**System API**: This is a system API. + +| Name | Type | Readable| Writable| Description | +| ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | No | Element name information of the remote ability. | +| label | string | Yes | No | Label of the remote ability. | +| icon | string | Yes | No | Icon of the remote ability.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index ab561f552758ed5af3c79bc2c4406d84ceb56f2b..a04f49f6d46bd886af5b23c01e65ce7d0b689e85 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Example** ```js -call.formatPhoneNumber("138xxxxxxxx",{ +call.formatPhoneNumber("138xxxxxxxx", { countryCode: "CN" }, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -796,7 +796,7 @@ call.reject(rejectMessageOptions, (err, data) => { ## call.reject7+ -reject(callId: number, callback: AsyncCallback): +reject(callId: number, callback: AsyncCallback\): void Rejects a call based on the specified call ID. This API uses an asynchronous callback to return the result. @@ -811,16 +811,11 @@ This is a system API. | callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Return value** - -| Type | Description | -| ------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| **Example** ```js -call.reject(1, (error, data) => { +call.reject(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1621,8 +1616,8 @@ This is a system API. **Example** ```js -call.on('callDetailsChange', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.on('callDetailsChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1646,8 +1641,8 @@ This is a system API. **Example** ```js -call.on('callEventChange', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.on('callEventChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1671,8 +1666,8 @@ This is a system API. **Example** ```js -call.on('callDisconnectedCause', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.on('callDisconnectedCause', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1696,8 +1691,8 @@ This is a system API. **Example** ```js -call.on('mmiCodeResult', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.on('mmiCodeResult', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1721,8 +1716,8 @@ This is a system API. **Example** ```js -call.off('callDetailsChange', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.off('callDetailsChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1746,8 +1741,8 @@ This is a system API. **Example** ```js -call.off('callEventChange', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.off('callEventChange', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1771,8 +1766,8 @@ This is a system API. **Example** ```js -call.off('callDisconnectedCause', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.off('callDisconnectedCause', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1796,8 +1791,8 @@ This is a system API. **Example** ```js -call.off('mmiCodeResult', (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +call.off('mmiCodeResult', data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -2386,7 +2381,7 @@ This is a system API. let audioDeviceOptions={ bluetoothAddress: "IEEE 802-2014" } -call.setAudioDevice(1, audioDeviceOptions, (err, value) => { +call.setAudioDevice(1, audioDeviceOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 5d57d317cb2a4ae2fa0e7ba29e61a23d95c8dbd1..cc34ebefa765c63b14d0bf65e1d8d26ebe64e4e1 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](../../ability/context-userguide.md) | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -30,7 +30,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to ```js camera.getCameraManager(context, (err, cameraManager) => { if (err) { - console.error('Failed to get the CameraManager instance ${err.message}'); + console.error(`Failed to get the CameraManager instance ${err.message}`); return; } console.log('Callback returned with the CameraManager instance'); @@ -49,12 +49,12 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ------- | ---- | ------------ | -| context | Context | Yes | Application context.| +| context | [Context](../../ability/context-userguide.md) | Yes | Application context.| **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------------- | +| Type | Description | +| ----------------------------------------- | ----------------------------------- | | Promise<[CameraManager](#cameramanager)\> | Promise used to return the **CameraManager** instance.| **Example** @@ -78,876 +78,884 @@ Enumerates the camera statuses. | CAMERA_STATUS_AVAILABLE | 2 | The camera is available. | | CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable.| +## Profile -## CameraPosition - -Enumerates the camera positions. +Defines the camera profile. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------------- | ---- | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| -| CAMERA_POSITION_BACK | 1 | Rear camera. | -| CAMERA_POSITION_FRONT | 2 | Front camera. | +| Name | Type | Read Only| Description | +| -------- | ----------------------------- |---- | ------------- | +| format | [CameraFormat](#cameraformat) | Yes | Output format. | +| size | [Size](#size) | Yes | Resolution. | -## CameraType +## FrameRateRange -Enumerates the camera types. +Defines the frame rate range. **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. | -| CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information. | - +| Name | Type | Read Only| Description | +| -------- | ----------------------------- |---- | ------------- | +| min | number | Yes | Minimum frame rate. | +| max | number | Yes | Maximum frame rate. | -## ConnectionType +## VideoProfile -Enumerates the camera connection types. +Defines the video profile. **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.| -| CAMERA_CONNECTION_REMOTE | 2 | Remote camera. | +| Name | Type | Read Only| Description | +| ------------------------- | ----------------------------------------- | --- |----------- | +| frameRateRange | [FrameRateRange](#frameraterange) | Yes | Frame rate range. | -## Size +## CameraOutputCapability -Defines the image size that can be used in previewing, photographing, and video recording. +Defines the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | ------------ | -| height | string | Yes | Yes | Image height.| -| width | number | Yes | Yes | Image width.| +| 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 Implements camera management. Before calling any API in **CameraManager**, you must use **getCameraManager** to obtain a **CameraManager** instance. -### getCameras +### getSupportedCameras -getCameras(callback: AsyncCallback\>): void +getSupportedCameras(callback: AsyncCallback\>): void -Obtains all cameras supported by the device. This API uses an asynchronous callback to return the array of supported cameras. +Obtains supported cameras. 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 array of supported cameras.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| **Example** ```js -cameraManager.getCameras((err, cameras) => { +cameraManager.getSupportedCameras((err, cameras) => { if (err) { - console.error('Failed to get the cameras. ${err.message}'); + console.error(`Failed to get the cameras. ${err.message}`); return; } - console.log('Callback returned with an array of supported cameras: ' + cameras.length); + console.log(`Callback returned with an array of supported cameras: ${cameras.length}`); }) ``` -### getCameras +### getSupportedCameras -getCameras(): Promise\> +getSupportedCameras(): Promise\> -Obtains all cameras supported by the device. This API uses a promise to return the array of supported cameras. +Obtains supported cameras. 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 array of supported cameras.| +| Type | Description | +| ----------------------------------------------- | ------------------------- | +| Promise\> | Promise used to return the array of supported cameras.| **Example** ```js -cameraManager.getCameras().then((cameraArray) => { - console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); +cameraManager.getSupportedCameras().then((cameraArray) => { + console.log(`Promise returned with an array of supported cameras: ${cameraArray.length}`); }) ``` -### createCameraInput - -createCameraInput(cameraId: string, callback: AsyncCallback): void +### getSupportedOutputCapability -Creates a **CameraInput** instance with the specified camera ID. This API uses an asynchronous callback to return the result. +getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void -**Required permissions**: ohos.permission.CAMERA +Obtains the output capability supported by a camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| cameraId | string | Yes | ID of the target camera. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| +| Name | Type | Mandatory| Description | +| ------------ |--------------------------------------------------------------- | -- | -------------------------- | +| CameraDevice | [CameraDevice](#cameradevice) | Yes| Camera device. | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes| Callback used to return the output capability.| **Example** ```js -cameraManager.createCameraInput(cameraId, (err, cameraInput) => { +cameraManager.getSupportedOutputCapability(cameradevice, (err, cameras) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error(`Failed to get the cameras. ${err.message}`); return; } - console.log('Callback returned with the CameraInput instance.'); + console.log('Callback returned with an array of supported outputCapability'); }) ``` -### createCameraInput - -createCameraInput(cameraId: string): Promise +### getSupportedOutputCapability -Creates a **CameraInput** instance with the specified camera ID. This API uses a promise to return the result. +getSupportedOutputCapability(camera:CameraDevice): Promise -**Required permissions**: ohos.permission.CAMERA +Obtains the output capability supported by a camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | -| cameraId | string | Yes | ID of the target camera.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameradevice) | Yes | Camera device. | **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| -------------------------------------------------------------- | ----------------------------- | +| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.| **Example** ```js -cameraManager.createCameraInput(cameraId).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapability) => { + console.log('Promise returned with an array of supported outputCapability'); }) ``` -### createCameraInput +### isCameraMuted -createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void +isCameraMuted(): boolean -Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result. +Checks whether the camera is muted. -**Required permissions**: ohos.permission.CAMERA +Before calling the API, ensure that the camera can be muted. You can use [isCameraMuteSupported](#iscameramutesupported) to check whether the camera can be muted. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +**Return value** -| 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.| +| Type | Description | +| ---------- | -------------------------------------------- | +| boolean | Returns **true** if the camera is muted; returns **false** otherwise.| **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { - if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); - return; - } - console.log('Callback returned with the CameraInput instance'); -}) +let ismuted = await cameraManager.isCameraMuted(); ``` -### createCameraInput - -createCameraInput(position: CameraPosition, type: CameraType): Promise +### isCameraMuteSupported -Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result. +isCameraMuteSupported(): boolean -**Required permissions**: ohos.permission.CAMERA +Checks whether the camera can be muted. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ---------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position.| -| type | [CameraType](#cameratype) | Yes | Camera type.| - **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| ---------- | ----------------------------- | +| boolean | Returns **true** if the camera can be muted; returns **false** otherwise.| **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance.'); -}) +let ismutesuppotred = await cameraManager.isCameraMuteSupported(); ``` -### on('cameraStatus') +### muteCamera -on(type: 'cameraStatus', callback: AsyncCallback): void +muteCamera(mute: boolean): void -Listens for camera status changes. This API uses an asynchronous callback to return the result. +Mutes or unmutes the camera. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| 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** - -```js -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { - if (err) { - console.error('Failed to get cameraStatus callback. ${err.message}'); - return; - } - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); -}) -``` - -## Camera - -After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera instance is returned, with camera-related metadata such as **cameraId**, **cameraPosition**, **cameraType**, and **connectionType**. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Read only| Description | -| -------------- | --------------------------------- | ---- | -------------- | -| cameraId | string | Yes | Camera ID. | -| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | -| cameraType | [CameraType](#cameratype) | Yes | Camera type. | -| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| +| 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. | **Example** ```js -async function getCameraInfo("cameraId") { - var cameraManager = await camera.getCameraManager(context); - var cameras = await cameraManager.getCameras(); - var cameraObj = cameras[0]; - var cameraId = cameraObj.cameraId; - var cameraPosition = cameraObj.cameraPosition; - var cameraType = cameraObj.cameraType; - var connectionType = cameraObj.connectionType; -} +cameraManager.muteCamera(mute); ``` -## CameraStatusInfo - -Describes the camera status information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Description | -| ------ | ----------------------------- | ---------- | -| camera | [Camera](#camera) | Camera object.| -| status | [CameraStatus](#camerastatus) | Camera status.| - - -## CameraInput +### createCameraInput -Implements a **CameraInput** instance. Before calling any API in **CameraInput**, you must create a **CameraInput** instance. +createCameraInput(camera: CameraDevice, callback: AsyncCallback): void -### getCameraId +Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses an asynchronous callback to return the result. -getCameraId(callback: AsyncCallback\): void +This is a system API. -Obtains the camera ID based on which this **CameraInput** instance is created. This API uses an asynchronous callback to return the camera ID. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the camera ID.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | --------------------------------- | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | **Example** ```js -cameraInput.getCameraId((err, cameraId) => { +cameraManager.createCameraInput(camera, (err, cameraInput) => { if (err) { - console.error('Failed to get the camera ID. ${err.message}'); + console.error(`Failed to create the CameraInput instance. ${err.message}`); return; } - console.log('Callback returned with the camera ID: ' + cameraId); + console.log('Callback returned with the CameraInput instance.'); }) ``` -### getCameraId +### createCameraInput + +createCameraInput(camera: CameraDevice): Promise + +Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses a promise to return the result. -getCameraId(): Promise +This is a system API. -Obtains the camera ID based on which this **CameraInput** instance is created. This API uses a promise to return the camera ID. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------- | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| + **Return value** -| Type | Description | -| ---------------- | ----------------------------- | -| Promise | Promise used to return the camera ID.| +| Type | Description | +| ------------------------------------- | ------------------------------------ | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraInput.getCameraId().then((cameraId) => { - console.log('Promise returned with the camera ID:' + cameraId); +cameraManager.createCameraInput(camera).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` +### createCameraInput -### hasFlash +createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void -hasFlash(callback: AsyncCallback): void +Creates a **CameraInput** instance with the specified camera position and type. 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. +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the flash support status. The value **true** means that the device has flash.| +| 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. | **Example** ```js -cameraInput.hasFlash((err, status) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { - console.error('Failed to check whether the device has flash light. ${err.message}'); + console.error(`Failed to create the CameraInput instance. ${err.message}`); return; } - console.log('Callback returned with flash light support status: ' + status); + console.log('Callback returned with the CameraInput instance'); }) ``` -### hasFlash +### createCameraInput -hasFlash(): Promise +createCameraInput(position: CameraPosition, type:CameraType ): Promise -Checks whether the device has flash. This API uses a promise to return the result. +Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| position | [CameraPosition](#cameraposition) | Yes | Camera position. | +| type | [CameraType](#cameratype) | Yes | Camera type. | + **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------- | -| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.| +| Type | Description | +| ------------------------------------- | ------------------------------------ | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### isFlashModeSupported +### createPreviewOutput -isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void +createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. +Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| 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.| +| 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** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { if (err) { - console.error('Failed to check whether the flash mode is supported. ${err.message}'); + console.error(`Failed to gcreate previewOutput. ${err.message}`); return; } - console.log('Callback returned with the flash mode support status: ' + status); + console.log('Callback returned with previewOutput created.'); }) ``` -### isFlashModeSupported +### createPreviewOutput -isFlashModeSupported(flashMode: FlashMode): Promise +createPreviewOutput(profile: Profile, surfaceId: string): Promise -Checks whether a specified flash mode is supported. This API uses a promise to return the result. +Creates a **PreviewOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| +| 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 | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance. | **Example** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { - console.log('Promise returned with flash mode support status.' + status); +cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => { + console.log('Promise returned with previewOutput created.'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void - -Sets the flash mode. This API uses an asynchronous callback to return the result. +### createPhotoOutput -Before the setting, do the following checks: +createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -1. Use **[hasFlash](#hasflash)** to check whether the device has flash. -2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. +Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------------------ | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| 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** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { if (err) { - console.error('Failed to set the flash mode ${err.message}'); + console.error(`Failed to create photoOutput. ${err.message}`); return; } - console.log('Callback returned with the successful execution of setFlashMode.'); + console.log('Callback returned with photoOutput created.'); }) ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode): Promise - -Sets a flash mode. This API uses a promise to return the result. +### createPhotoOutput -Before the setting, do the following checks: +createPhotoOutput(profile: Profile, surfaceId: string): Promise -1. Use **[hasFlash](#hasflash)** to check whether the device has flash. -2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. +Creates a **PhotoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| +| 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| Promise used to return the result.| +| Type | Description | +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance. | **Example** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFlashMode.'); +cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { + console.log('Promise returned with photoOutput created.'); }) ``` -### getFlashMode +### createVideoOutput -getFlashMode(callback: AsyncCallback): void +createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void -Obtains the flash mode in use. This API uses an asynchronous callback to return the result. +Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| +| 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** ```js -cameraInput.getFlashMode((err, flashMode) => { +cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { if (err) { - console.error('Failed to get the flash mode ${err.message}'); + console.error(`Failed to create videoOutput. ${err.message}`); return; } - console.log('Callback returned with current flash mode: ' + flashMode); + console.log('Callback returned with an array of supported outputCapability' ); }) ``` -### getFlashMode +### createVideoOutput -getFlashMode(): Promise +createVideoOutput(profile: VideoProfile, surfaceId: string): Promise -Obtains the flash mode in use. This API uses a promise to return the result. +Creates a **VideoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| 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<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| +| Type | Description | +| ------------------------------------- | -------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance. | **Example** ```js -cameraInput.getFlashMode().then((flashMode) => { - console.log('Promise returned with current flash mode : ' + flashMode); +cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { + console.log('Promise returned with videoOutput created.'); }) ``` -### isFocusModeSupported +### createMetadataOutput -isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void +createMetadataOutput(metadataObjectTypes:Array, callback: AsyncCallback): void -Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. +Creates a **MetadataOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| 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.| +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | --- | ---------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types. | +| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance. | **Example** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { if (err) { - console.error('Failed to check whether the focus mode is supported. ${err.message}'); + console.error(`Failed to create metadataOutput. ${err.message}`); return; } - console.log('Callback returned with the focus mode support status: ' + status); + console.log('Callback returned with metadataOutput created.'); }) ``` -### isFocusModeSupported +### createMetadataOutput -isFocusModeSupported(afMode: FocusMode): Promise +createMetadataOutput(metadataObjectTypes:Array): Promise -Checks whether a specified focus mode is supported. This API uses a promise to return the result. +Creates a **MetadataOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | --- | -------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types. | **Return value** -| 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.| +| Type | Description | +| ------------------------------------------ | ----------------------------------------- | +| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.| **Example** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { - console.log('Promise returned with focus mode support status.' + status); +cameraManager.createMetadataOutput().then((metadataoutput) => { + console.log('Promise returned with metadataOutput created.'); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode, callback: AsyncCallback): void +### createCaptureSession -Sets a focus mode. This API uses an asynchronous callback to return the result. +createCaptureSession(callback: AsyncCallback): void -Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. +Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------ | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------------------- | ----------------------------------------- | ----------- | ---------------------------- | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| **Example** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { +cameraManager.createCaptureSession((err, capturesession) => { if (err) { - console.error('Failed to set the focus mode ${err.message}'); + console.error(`Failed to create captureSession. ${err.message}`); return; } - console.log('Callback returned with the successful execution of setFocusMode.'); + console.log('Callback returned with captureSession created.'); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode): Promise +### createCaptureSession -Sets a focus mode. This API uses a promise to return the result. +createCaptureSession(): Promise -Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. +Creates a **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| - **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| ------------------------------------------- | ---------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| **Example** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFocusMode.'); +cameraManager.createCaptureSession().then((capturesession) => { + console.log('Promise returned with captureSession created.'); }) ``` -### getFocusMode +### on('cameraStatus') -getFocusMode(callback: AsyncCallback): void +on(type: 'cameraStatus', callback: AsyncCallback): void -Obtains the focus mode in use. This API uses an asynchronous callback to return the result. +Listens for camera status changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| +| 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** ```js -cameraInput.getFocusMode((err, afMode) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { - console.error('Failed to get the focus mode ${err.message}'); + console.error(`Failed to get cameraStatus callback. ${err.message}`); return; } - console.log('Callback returned with current focus mode: ' + afMode); -}) -``` - -### getFocusMode - -getFocusMode(): Promise - -Obtains the focus mode in use. 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 mode.| - -**Example** - -```js -cameraInput.getFocusMode().then((afMode) => { - console.log('Promise returned with current focus mode : ' + afMode); + console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); + console.log(`status: ${cameraStatusInfo.status}`); }) ``` -### getZoomRatioRange +### on('cameraMute') -getZoomRatioRange\(callback: AsyncCallback\>\): void +on(type: 'cameraMute', callback: AsyncCallback): void -Obtains the zoom ratio range. This API uses an asynchronous callback to return the result. +Listens for camera mute status changes. 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 an array containing the minimum and maximum zoom ratios.| +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | --------- | +| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| +| callback | boolean | Yes | Callback used to return the camera mute status. | **Example** ```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { +cameraManager.on('cameraMute', (err, cameraStatusInfo) => { if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); + console.error(`Failed to get cameraMute callback. ${err.message}`); return; } - console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); }) ``` -### getZoomRatioRange - -getZoomRatioRange\(\): Promise\> +## CameraStatusInfo -Obtains the zoom ratio range. This API uses a promise to return the result. +Describes the camera status information. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** - -| Type | Description | -| ------------------------ | ------------------------------------------- | -| Promise\> | Promise used to return an array containing the minimum and maximum zoom ratios.| +| Name | Type | Description | +| ------ | ----------------------------- | ---------- | +| camera | [CameraDevice](#cameradevice) | Camera object.| +| status | [CameraStatus](#camerastatus) | Camera status.| + +## CameraPosition + +Enumerates the camera positions. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| --------------------------- | ---- | -------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position. | +| CAMERA_POSITION_BACK | 1 | Rear camera. | +| CAMERA_POSITION_FRONT | 2 | Front camera. | + +## CameraType + +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. | +| CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information.| + +## ConnectionType + +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.| +| CAMERA_CONNECTION_REMOTE | 2 | Remote camera.| + +## CameraDevice + +Defines the camera device information. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| 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.| **Example** ```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { - console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); -}) +async function getCameraInfo("cameraId") { + let cameraManager = await camera.getCameraManager(context); + let cameras = await cameraManager.getSupportedCameras(); + let cameraObj = cameras[0]; + let cameraId = cameraObj.cameraId; + let cameraPosition = cameraObj.cameraPosition; + let cameraType = cameraObj.cameraType; + let connectionType = cameraObj.connectionType; +} ``` -### setZoomRatio +## Size -setZoomRatio(zoomRatio: number, callback: AsyncCallback): void +Enumerates the camera output capability. -Sets a zoom ratio. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------ | +| height | number | Yes | Yes | Image height, in pixels.| +| width | number | Yes | Yes | Image width, in pixels.| + +## Point + +Enumerates the point coordinates, which are used for focus and exposure configuration. + +**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. | + +## CameraFormat + +Enumerates the camera output formats. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Default Value | Description | +| ----------------------- | --------- | ------------ | +| CAMERA_FORMAT_RGBA_8888 | 3 | RGB image. | +| CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP image. | +| CAMERA_FORMAT_JPEG | 2000 | JPEG image. | + +## CameraInput + +Provides camera information used in **[CaptureSession](#capturesession)**. + +### open + +open\(callback: AsyncCallback\): void + +Opens this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------ | -| zoomRatio | number | Yes | Zoom ratio. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.setZoomRatio(1, (err) => { +cameraInput.open((err) => { if (err) { - console.error('Failed to set the zoom ratio value ${err.message}'); + console.error(`Failed to open the camera. ${err.message}`); return; } - console.log('Callback returned with the successful execution of setZoomRatio.'); + console.log('Callback returned with camera opened.'); }) ``` -### setZoomRatio +### open -setZoomRatio(zoomRatio: number): Promise +open(): Promise -Sets a zoom ratio. This API uses a promise to return the result. +Opens this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------ | -| zoomRatio | number | Yes | Zoom ratio.| - **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** ```js -cameraInput.setZoomRatio(1).then(() => { - console.log('Promise returned with the successful execution of setZoomRatio.'); +cameraInput.open().then(() => { + console.log('Promise returned with camera opened.'); }) ``` -### getZoomRatio +### close -getZoomRatio(callback: AsyncCallback): void +close\(callback: AsyncCallback\): void -Obtains the zoom ratio in use. This API uses an asynchronous callback to return the result. +Closes 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 result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.getZoomRatio((err, zoomRatio) => { +cameraInput.close((err) => { if (err) { - console.error('Failed to get the zoom ratio ${err.message}'); + console.error(`Failed to close the cameras. ${err.message}`); return; } - console.log('Callback returned with current zoom ratio: ' + zoomRatio); + console.log('Callback returned with camera closed.'); }) ``` -### getZoomRatio +### close -getZoomRatio(): Promise +close(): Promise -Obtains the zoom ratio in use. This API uses a promise to return the result. +Closes 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 zoom ratio.| +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| **Example** ```js -cameraInput.getZoomRatio().then((zoomRatio) => { - console.log('Promise returned with current zoom ratio : ' + zoomRatio); +cameraInput.close().then(() => { + console.log('Promise returned with camera closed.'); }) ``` @@ -955,14 +963,14 @@ cameraInput.getZoomRatio().then((zoomRatio) => { release\(callback: AsyncCallback\): void -Releases this **CameraInput** instance. This API uses an asynchronous callback to return the result. +Releases this camera. This API uses an asynchronous callback to return the result. **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** @@ -970,7 +978,7 @@ Releases this **CameraInput** instance. This API uses an asynchronous callback t ```js cameraInput.release((err) => { if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); + console.error(`Failed to release the CameraInput instance ${err.message}`); return; } console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); @@ -981,14 +989,14 @@ cameraInput.release((err) => { release(): Promise -Releases this **CameraInput** instance. This API uses a promise to return the result. +Releases this camera. 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 the result.| **Example** @@ -999,32 +1007,9 @@ cameraInput.release().then(() => { }) ``` -### on('focusStateChange') - -on(type: 'focusStateChange', callback: AsyncCallback): void - -Listens for focus state changes. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**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. | - -**Example** - -```js -cameraInput.on('focusStateChange', (focusState) => { - console.log('Focus state : ' + focusState); -}) -``` - ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(type: 'error', camera:CameraDevice, callback: ErrorCallback): void Listens for **CameraInput** errors. This API uses a callback to return the result. @@ -1032,37 +1017,43 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :----------------------------------------------- | +| 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. | +| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | **Example** ```js -cameraInput.on('error', (cameraInputError) => { - console.log('Camera input error code: ' + cameraInputError.code); +cameraInput.on('error', camera, (cameraInputError) => { + console.log(`Camera input error code: ${cameraInputError.code}`); }) ``` -## CameraInputErrorCode +## CameraInputErrorCode -Enumerates the error codes used in a **CameraInput** instance. +Enumerates the error codes used for camera input. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| +| 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. | -## CameraInputError +## CameraInputError -Defines a **CameraInput** error. +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.| @@ -1072,25 +1063,37 @@ 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.| | FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| -## FocusMode +## ExposureMode + +Enumerates the exposure modes. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ----------- | +| EXPOSURE_MODE_LOCKED | 0 | Exposure locked.| +| EXPOSURE_MODE_AUTO | 1 | Auto exposure.| +| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.| + + ## FocusMode 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. | -| FOCUS_MODE_LOCKED | 3 | Focus locked. | +| FOCUS_MODE_LOCKED | 3 | Focus locked. | ## FocusState @@ -1098,70 +1101,29 @@ 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.| -## camera.createCaptureSession - -createCaptureSession\(context: Context, callback: AsyncCallback\): void - -Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------------------------- | -| context | Context | Yes | Application context. | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| - -**Example** - -```js -camera.createCaptureSession((context), (err, captureSession) => { - if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); - return; - } - console.log('Callback returned with the CaptureSession instance.' + captureSession); -}); -``` - -## camera.createCaptureSession +## VideoStabilizationMode -createCaptureSession(context: Context\): Promise; - -Creates a **CaptureSession** instance. This API uses a promise to return the result. +Enumerates the video stabilization modes. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------ | -| context | Context | Yes | Application context.| - -**Return value** - -| Type | Description | -| ------------------------------------------- | ----------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| - -**Example** - -```js -camera.createCaptureSession(context).then((captureSession) => { - console.log('Promise returned with the CaptureSession instance'); -}) -``` +| 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 -Implements a shooting session. +Implements a shooting session, which saves all **[CameraInput](#camerainput)** and **[CameraOutput](#cameraoutput)** instances required to run the camera and requests the camera to complete shooting or video recording. ### beginConfig @@ -1173,8 +1135,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** @@ -1182,7 +1144,7 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn ```js captureSession.beginConfig((err) => { if (err) { - console.error('Failed to start the configuration. ${err.message}'); + console.error(`Failed to start the configuration. ${err.message}`); return; } console.log('Callback invoked to indicate the begin config success.'); @@ -1199,8 +1161,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.| @@ -1222,8 +1184,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** @@ -1231,7 +1193,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an ```js captureSession.commitConfig((err) => { if (err) { - console.error('Failed to commit the configuration. ${err.message}'); + console.error(`Failed to commit the configuration. ${err.message}`); return; } console.log('Callback invoked to indicate the commit config success.'); @@ -1248,8 +1210,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** @@ -1264,14 +1226,14 @@ captureSession.commitConfig().then(() => { addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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. | @@ -1280,7 +1242,7 @@ Adds a **CameraInput** instance to this **CaptureSession** instance. This API us ```js captureSession.addInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); + console.error(`Failed to add the CameraInput instance. ${err.message}`); return; } console.log('Callback invoked to indicate that the CameraInput instance is added.'); @@ -1291,20 +1253,20 @@ captureSession.addInput(cameraInput, (err) => { addInput\(cameraInput: CameraInput\): Promise -Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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** @@ -1315,969 +1277,2262 @@ captureSession.addInput(cameraInput).then(() => { }) ``` -### addOutput +### removeInput -addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addOutput(previewOutput, (err) => { +captureSession.removeInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); + console.error(`Failed to remove the CameraInput instance. ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); + console.log('Callback invoked to indicate that the cameraInput instance is removed.'); }); ``` -### addOutput +### removeInput -addOutput\(previewOutput: PreviewOutput\): Promise +removeInput\(cameraInput: CameraInput\): Promise -Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------ | +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js -captureSession.addOutput(previewOutput).then(() => { - console.log('Promise used to indicate that the PreviewOutput instance is added.'); +captureSession.removeInput(cameraInput).then(() => { + console.log('Promise returned to indicate that the cameraInput instance is removed.'); }) ``` ### addOutput -addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void +addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** 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** ```js -captureSession.addOutput(photoOutput, (err) => { +captureSession.addOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); + console.error(`Failed to add output. ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); -}); + console.log('Callback returned with output added.'); +}) ``` ### addOutput -addOutput\(photoOutput: PhotoOutput\): Promise +addOutput\(cameraOutput: CameraOutput\): Promise -Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| **Example** ```js -captureSession.addOutput(photoOutput).then(() => { - console.log('Promise used to indicate that the PhotoOutput instance is added.'); +captureSession.addOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput added.'); }) ``` -### addOutput +### removeOutput -addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void +removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| -| 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** ```js -captureSession.addOutput(videoOutput, (err) => { +captureSession.removeOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); + console.error(`Failed to remove the CameraOutput instance. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); + console.log('Callback invoked to indicate that the CameraOutput instance is removed.'); }); ``` -### addOutput +### removeOutput -addOutput\(videoOutput: VideoOutput\): Promise +removeOutput(cameraOutput: CameraOutput): Promise -Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ------------------------- | +| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| + **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------ | +| Promise| Promise used to return the result.| + **Example** ```js -captureSession.addOutput(videoOutput).then(() => { - console.log('Promise used to indicate that the VideoOutput instance is added.'); +captureSession.removeOutput(cameraOutput).then(() => { + console.log('Promise returned to indicate that the CameraOutput instance is removed.'); }) ``` -### removeInput +### start -removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +start\(callback: AsyncCallback\): void -Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Starts this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.removeInput(cameraInput, (err) => { +captureSession.start((err) => { if (err) { - console.error('Failed to remove the CameraInput instance. ${err.message}'); + console.error(`Failed to start the session ${err.message}`); return; } - console.log('Callback invoked to indicate that the cameraInput instance is removed.'); + console.log('Callback invoked to indicate the session start success.'); }); ``` -### removeInput +### start -removeInput\(cameraInput: CameraInput\): Promise +start\(\): Promise -Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Starts this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| - **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------ | +| Promise| Promise used to return the result.| **Example** ```js -captureSession.removeInput(cameraInput).then(() => { - console.log('Promise returned to indicate that the cameraInput instance is removed.'); +captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); }) ``` -### removeOutput +### stop -removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +stop\(callback: AsyncCallback\): void -Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Stops this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.removeOutput(previewOutput, (err) => { +captureSession.stop((err) => { if (err) { - console.error('Failed to remove the PreviewOutput instance. ${err.message}'); + console.error(`Failed to stop the session ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is removed.'); + console.log('Callback invoked to indicate the session stop success.'); }); ``` -### removeOutput +### stop -removeOutput(previewOutput: PreviewOutput): Promise +stop(): Promise -Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Stops this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| - - **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| - **Example** ```js -captureSession.removeOutput(previewOutput).then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); +captureSession.stop().then(() => { + console.log('Promise returned to indicate the session stop success.'); }) ``` -### removeOutput +### release -removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void +release\(callback: AsyncCallback\): void -Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Releases this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.removeOutput(photoOutput, (err) => { +captureSession.release((err) => { if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); + console.error(`Failed to release the CaptureSession instance ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); + console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); }); ``` -### removeOutput +### release -removeOutput(photoOutput: PhotoOutput): Promise +release(): Promise -Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Releases this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| - - **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| - **Example** ```js -captureSession.removeOutput(photoOutput).then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); +captureSession.release().then(() => { + console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); }) ``` -### removeOutput +### hasFlash -removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void +hasFlash(callback: AsyncCallback): void -Removes a **VideoOutput** instance from this **CaptureSession** instance. 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 | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| 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** ```js -captureSession.removeOutput(videoOutput, (err) => { +captureSession.hasFlash((err, status) => { if (err) { - console.error('Failed to remove the VideoOutput instance. ${err.message}'); + console.error(`Failed to check whether the device has flash light. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is removed.'); -}); + console.log(`Callback returned with flash light support status: ${status}`); +}) ``` -### removeOutput +### hasFlash -removeOutput(videoOutput: VideoOutput): Promise +hasFlash(): Promise -Removes a **VideoOutput** instance from this **CaptureSession** instance. 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 -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.| +**Example** + +```js +captureSession.hasFlash().then((status) => { + console.log(`Promise returned with the flash light support status: ${status}`); +}) +``` + +### isFlashModeSupported + +isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void + +Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| 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** + +```js +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { + if (err) { + console.error(`Failed to check whether the flash mode is supported. ${err.message}`); + return; + } + console.log(`Callback returned with the flash mode support status: ${status}`); +}) +``` + +### isFlashModeSupported + +isFlashModeSupported(flashMode: FlashMode): Promise + +Checks whether a specified flash mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| + +**Return value** + +| 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** + +```js +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { + console.log(`Promise returned with flash mode support status.${status}`); +}) +``` + +### setFlashMode + +setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void + +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. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | --------------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { + if (err) { + console.error(`Failed to set the flash mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setFlashMode.'); +}) +``` + +### setFlashMode + +setFlashMode(flashMode: FlashMode): Promise + +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. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------ | +| Promise| Promise used to return the result.| + +**Example** + +```js +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFlashMode.'); +}) +``` + +### getFlashMode + +getFlashMode(callback: AsyncCallback): void + +Obtains the flash mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | --------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| + +**Example** + +```js +captureSession.getFlashMode((err, flashMode) => { + if (err) { + console.error(`Failed to get the flash mode ${err.message}`); + return; + } + console.log(`Callback returned with current flash mode: ${flashMode}`); +}) +``` + +### getFlashMode + +getFlashMode(): Promise + +Obtains the flash mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| --------------------------------- | --------------------------------- | +| Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| + +**Example** + +```js +captureSession.getFlashMode().then((flashMode) => { + console.log(`Promise returned with current flash mode : ${flashMode}`); +}) +``` + +### isExposureModeSupported + +isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; + +Checks whether a specified exposure mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**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.| + +**Example** + +```js +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => { + if (err) { + console.log(`Failed to check exposure mode supported ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of isExposureModeSupported'); +}) +``` + +### isExposureModeSupported + +isExposureModeSupported(aeMode: ExposureMode): Promise + +Checks whether a specified exposure mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------| ---- | ----------------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | + +**Return value** + +| 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** + +```js +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log(`Promise returned with exposure mode supported : ${isSupported}`); +}) +``` + +### getExposureMode + +getExposureMode(callback: AsyncCallback): void + +Obtains the exposure mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ---------------------------------------- | +| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.| + +**Example** + +```js +captureSession.getExposureMode((err, exposureMode) => { + if (err) { + console.log(`Failed to get the exposure mode ${err.message}`); + return ; + } + console.log(`Callback returned with current exposure mode: ${exposureMode}`); +}) +``` + +### getExposureMode + +getExposureMode(): Promise + +Obtains the exposure mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| --------------------------------------- |------------------------------- | +| Promise<[ExposureMode](#exposuremode)\> | Promise used to return the exposure mode.| + +**Example** + +```js +captureSession.getExposureMode().then((exposureMode) => { + console.log(`Promise returned with current exposure mode : ${exposureMode}`); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void + +Sets an exposure mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ----------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => { + if (err) { + console.log(`Failed to set the exposure mode ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of setExposureMode'); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode): Promise + +Sets an exposure mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ----------------- |---------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { + console.log('Promise returned with the successful execution of setExposureMode.'); +}) +``` + +### getMeteringPoint + +getMeteringPoint(callback: AsyncCallback): void + +Obtains the center of the metering area. 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 center of the metering area.| + +**Example** + +```js +captureSession.getMeteringPoint((err, exposurePoint) => { + if (err) { + console.log(`Failed to get the current exposure point ${err.message}`); + return ; + } + console.log(`Callback returned with current exposure point: ${exposurePoint}`); +}) +``` + +### getMeteringPoint + +getMeteringPoint(): Promise + +Obtains the center of the metering area. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ------------------------- |----------------------------- | +| Promise<[Point](#point)\> | Promise used to return the center of the metering area.| + +**Example** + +```js +captureSession.getMeteringPoint().then((exposurePoint) => { + console.log(`Promise returned with current exposure point : ${exposurePoint}`); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point, callback: AsyncCallback): void + +Sets the center of the metering area. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------| ---- | ------------------- | +| exposurePoint | [Point](#point) | Yes | Exposure point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +const Point1 = {x: 1, y: 1}; + +captureSession.setMeteringPoint(Point1,(err) => { + if (err) { + console.log(`Failed to set the exposure point ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of setMeteringPoint'); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point): Promise + +Sets the center of the metering area. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| 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.| + +**Example** + +```js +const Point2 = {x: 2, y: 2}; + +captureSession.setMeteringPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setMeteringPoint'); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(callback: AsyncCallback\>): void + +Obtains the exposure compensation values. 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 array of compensation values.| + +**Example** + +```js +captureSession.getExposureBiasRange((err, biasRangeArray) => { + if (err) { + console.log(`Failed to get the array of compenstation range ${err.message}`); + return ; + } + console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(): Promise\> + +Obtains the exposure compensation values. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ----------------- |-------------------------------------- | +| Promise\> | Promise used to return the array of compensation values.| + +**Example** + +```js +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log(`Promise returned with exposure mode supported : ${isSupported}`); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number, callback: AsyncCallback): void + +Sets an exposure compensation value. This API uses an asynchronous callback to return the result. + +Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------| ---- | ------------------- | +| exposureBias | number | Yes | Compensation value. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.setExposureBias(-4,(err) => { + if (err) { + console.log(`Failed to set the exposure bias ${err.message}`); + return ; + } + console.log('Callback returned with the successful execution of setExposureBias'); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number): Promise + +Sets an exposure compensation value. This API uses a promise to return the result. + +Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | --------- | ---- | --------- | +| exposureBias | number | Yes | Compensation value. | + +**Return value** + +| Name | Description | +| ----------------- |------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +captureSession.setExposureBias(-4).then(() => { + console.log('Promise returned with the successful execution of setExposureBias.'); +}) +``` + +### getExposureValue + +getExposureValue(callback: AsyncCallback): void + +Obtains the exposure value in use. 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 the exposure value.| + +**Example** + +```js +captureSession.getExposureValue((err, exposureValue) => { + if (err) { + console.log(`Failed to get the exposure value ${err.message}`); + return ; + } + console.log(`Callback returned with the exposure value: ${exposureValue}`); +}) +``` + +### getExposureValue + +getExposureValue(): Promise + +Obtains the exposure value in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ----------------- |-------------------------- | +| Promise | Promise used to the exposure value.| + +**Example** + +```js +captureSession.getExposureValue().then((exposureValue) => { + console.log(`Promise returned with exposure value: ${exposureValude}`); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void + +Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| 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** + +```js +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { + if (err) { + console.error(`Failed to check whether the focus mode is supported. ${err.message}`); + return; + } + console.log(`Callback returned with the focus mode support status: ${status}`); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode): Promise + +Checks whether a specified focus mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| + +**Return value** + +| 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** + +```js +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { + console.log(`Promise returned with focus mode support status ${status}.`); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode, callback: AsyncCallback): void + +Sets a focus mode. This API uses an asynchronous callback to return the result. + +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { + if (err) { + console.error(`Failed to set the focus mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setFocusMode.'); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode): Promise + +Sets a focus mode. This API uses a promise to return the result. + +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------ | +| Promise| Promise used to return the result.| + +**Example** + +```js +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFocusMode.'); +}) +``` + +### getFocusMode + +getFocusMode(callback: AsyncCallback): void + +Obtains the focus mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| + +**Example** + +```js +captureSession.getFocusMode((err, afMode) => { + if (err) { + console.error(`Failed to get the focus mode ${err.message}`); + return; + } + console.log(`Callback returned with current focus mode: ${afMode}`); +}) +``` + +### getFocusMode + +getFocusMode(): Promise + +Obtains the focus mode in use. 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 mode.| + +**Example** + +```js +captureSession.getFocusMode().then((afMode) => { + console.log(`Promise returned with current focus mode : ${afMode}`); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point, callback: AsyncCallback): void + +Sets a focus point. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------- | +| point | [Point](#point) | Yes | Focal point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +const Point1 = {x: 1, y: 1}; + +captureSession.setFocusPoint(Point1, (err) => { + if (err) { + console.error(`Failed to set the focus point ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setFocusPoint.'); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point): Promise + +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 | Focal point. | + +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +const Point2 = {x: 2, y: 2}; + +captureSession.setFocusPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setFocusPoint.'); +}) +``` + +### getFocusPoint + +getFocusPoint(callback: AsyncCallback): void + +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 focal point.| + +**Example** + +```js +captureSession.getFocusPoint((err, point) => { + if (err) { + console.error(`Failed to get the current focus point ${err.message}`); + return; + } + console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocusPoint + +getFocusPoint(): Promise + +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 focal point.| + +**Example** + +```js +captureSession.getFocusPoint().then((point) => { + console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocalLength + +getFocalLength(callback: AsyncCallback): void + +Obtains the focal length. 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 focal length.| + +**Example** + +```js +captureSession.getFocalLength((err, focalLength) => { + if (err) { + console.error(`Failed to get the current focal length ${err.message}`); + return; + } + console.log(`Callback returned with the current focal length: ${focalLength}`); +}) +``` + +### getFocalLength + +getFocalLength(): Promise + +Obtains the focal length. 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 focal length.| + +**Example** + +```js +captureSession.getFocalLength().then((focalLength) => { + console.log(`Promise returned with the current focal length: ${focalLength}`); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(callback: AsyncCallback\>\): void + +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 an array containing the minimum and maximum zoom ratios.| + +**Example** + +```js +captureSession.getZoomRatioRange((err, zoomRatioRange) => { + if (err) { + console.error(`Failed to get the zoom ratio range. ${err.message}`); + return; + } + console.log(`Callback returned with zoom ratio range: ${zoomRatioRange.length}`); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(\): Promise\> + +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 an array containing the minimum and maximum zoom ratios.| + +**Example** + +```js +captureSession.getZoomRatioRange().then((zoomRatioRange) => { + console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number, callback: AsyncCallback): void + +Sets a zoom ratio. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------- | +| zoomRatio | number | Yes | Zoom ratio. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.setZoomRatio(1, (err) => { + if (err) { + console.error(`Failed to set the zoom ratio value ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setZoomRatio.'); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number): Promise + +Sets a zoom ratio. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------- | +| zoomRatio | number | Yes | Zoom ratio.| + +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +captureSession.setZoomRatio(1).then(() => { + console.log('Promise returned with the successful execution of setZoomRatio.'); +}) +``` + +### getZoomRatio + +getZoomRatio(callback: AsyncCallback): void + +Obtains the zoom ratio in use. 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 result.| + +**Example** + +```js +captureSession.getZoomRatio((err, zoomRatio) => { + if (err) { + console.error(`Failed to get the zoom ratio ${err.message}`); + return; + } + console.log(`Callback returned with current zoom ratio: ${zoomRatio}`); +}) +``` + +### getZoomRatio + +getZoomRatio(): Promise + +Obtains the zoom ratio in use. 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 ratio.| + +**Example** + +```js +captureSession.getZoomRatio().then((zoomRatio) => { + console.log(`Promise returned with current zoom ratio : ${zoomRatio}`); +}) +``` + +### isVideoStabilizationModeSupported + +isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void + +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. | + +**Example** + +```js +captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => { + if (err) { + console.error(`Failed to check whether video stabilization mode supported. ${err.message}`); + return; + } + console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported`); +}) +``` + +### isVideoStabilizationModeSupported + +isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise + +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 | +| ----------------- | --------------------------------------------- | +| 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** + +```js +captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => { + console.log(`Promise returned with video stabilization mode supported: ${isSupported}`); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(callback: AsyncCallback): void + +Obtains the video stabilization mode in use. 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 video stabilization mode. | + +**Example** + +```js +captureSession.getActiveVideoStabilizationMode((err, vsMode) => { + if (err) { + console.error(`Failed to get active video stabilization mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(): Promise + +Obtains the video stabilization mode in use. 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 video stabilization mode. | + +**Example** + +```js +captureSession.getActiveVideoStabilizationMode().then((vsMode) => { + console.log(`Promise returned with the current video stabilization mode: ${vsMode}`); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void + +Sets a video stabilization mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { + if (err) { + console.error(`Failed to set the video stabilization mode ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode): Promise + +Sets a video stabilization mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | --------------------- | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------------- | +| Promise| Promise used to return the result. | + +**Example** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { + console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### on('focusStateChange') + +on(type: 'focusStateChange', callback: AsyncCallback): void + +Listens for focus state changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**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. | + +**Example** + +```js +captureSession.on('focusStateChange', (focusState) => { + console.log(`Focus state : ${focusState}`); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for **CaptureSession** errors. This API uses a callback to return the errors. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**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. | + +**Example** + +```js +captureSession.on('error', (captureSessionError) => { + console.log(`Capture session error code: ${captureSessionError.code}`); +}) +``` + +## CaptureSessionErrorCode + +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.| + +## CaptureSessionError + +Defines a **CaptureSession** error. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| + +## CameraOutput + +Implements output information used in a **[CaptureSession](#capturesession)**. It is the base class of **output**. + +### release + +release(callback: AsyncCallback): void + +Releases output resources. 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 result.| + +**Example** + +```js +cameraOutput.release((err) => { + if (err) { + console.error(`Failed to release the PreviewOutput instance ${err.message}`); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +Releases output resources. 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 the result.| - **Example** ```js -captureSession.removeOutput(videoOutput).then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is removed.'); +cameraOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); }) ``` +## PreviewOutput + +Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. + ### start -start\(callback: AsyncCallback\): void +start(callback: AsyncCallback): void -Starts this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Starts to output preview streams. This API uses an asynchronous callback to return the result. **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** ```js -captureSession.start((err) => { +previewOutput.start((err) => { if (err) { - console.error('Failed to start the session ${err.message}'); + console.error(`Failed to start the previewOutput. ${err.message}`); return; } - console.log('Callback invoked to indicate the session start success.'); -}); + console.log('Callback returned with previewOutput started.'); +}) ``` ### start -start\(\): Promise +start(): Promise -Starts this **CaptureSession** instance. This API uses a promise to return the result. +Starts to output preview streams. 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 the result.| **Example** ```js -captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); +previewOutput.start().then(() => { + console.log('Promise returned with previewOutput started.'); }) ``` ### stop -stop\(callback: AsyncCallback\): void +stop(callback: AsyncCallback): void -Stops this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Stops outputting preview streams. This API uses an asynchronous callback to return the result. **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** ```js -captureSession.stop((err) => { +previewOutput.stop((err) => { if (err) { - console.error('Failed to stop the session ${err.message}'); + console.error(`Failed to stop the previewOutput. ${err.message}`); return; } - console.log('Callback invoked to indicate the session stop success.'); -}); + console.log('Callback returned with previewOutput stopped.'); +}) ``` ### stop stop(): Promise -Stops this **CaptureSession** instance. This API uses a promise to return the result. +Stops outputting preview streams. 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 the result.| **Example** ```js -captureSession.stop().then(() => { - console.log('Promise returned to indicate the session stop success.'); +previewOutput.stop().then(() => { + console.log('Callback returned with previewOutput stopped.'); }) ``` -### release +### on('frameStart') -release\(callback: AsyncCallback\): void +on(type: 'frameStart', callback: AsyncCallback): void -Releases this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Listens for preview frame start events. 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 result.| +| 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** ```js -captureSession.release((err) => { - if (err) { - console.error('Failed to release the CaptureSession instance ${err.message}'); - return; - } - console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); -}); +previewOutput.on('frameStart', () => { + console.log('Preview frame started'); +}) ``` -### release +### on('frameEnd') -release(): Promise +on(type: 'frameEnd', callback: AsyncCallback): void -Releases this **CaptureSession** instance. This API uses a promise to return the result. +Listens for preview frame end events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +**Parameters** -| Type | Description | -| -------------- | --------------------------- | -| Promise| Promise 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** ```js -captureSession.release().then(() => { - console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); +previewOutput.on('frameEnd', () => { + console.log('Preview frame ended'); }) ``` ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(type: 'error', callback: ErrorCallback): void -Listens for **CaptureSession** errors. This API uses a callback to return the errors. +Listens for **PreviewOutput** errors. This API uses a callback to return the errors. **System capability**: SystemCapability.Multimedia.Camera.Core **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 preview output error event.| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | **Example** ```js -captureSession.on('error', (captureSessionError) => { - console.log('Capture session error code: ' + captureSessionError.code); +previewOutput.on('error', (previewOutputError) => { + console.log(`Preview output error code: ${previewOutputError.code}`); }) ``` -## CaptureSessionErrorCode +## PreviewOutputErrorCode -Enumerates the error codes used in a **CaptureSession** instance. +Enumerates the error codes used for preview output. **System capability**: SystemCapability.Multimedia.Camera.Core | Name | Value | Description | -| ------------- | ---- | ---------- | +| ------------- | ---- | -------- | | ERROR_UNKNOWN | -1 | Unknown error.| -## CaptureSessionError +## PreviewOutputError -Defines a **CaptureSession** error. +Defines the preview output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| +| Name| Type | Description | +| ---- | ------------------------------------------------- | ---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| -## camera.createPreviewOutput +## ImageRotation -createPreviewOutput(surfaceId: string, callback: AsyncCallback): void +Enumerates the image rotation angles. -Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Multimedia.Camera.Core + +| 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.| +| ROTATION_270 | 270 | The image rotates 270 degrees.| + +## Location + +Defines geolocation information. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +| Name | Type | Mandatory|Description | +| ------------ | ------ | --- |------------ | +| latitude | number | Yes |Latitude, in degrees. | +| longitude | number | Yes |Longitude, in degrees. | +| altitude | number | Yes |Altitude, in meters. | -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | ------------------------------------- | -| surfaceId | string | Yes | Surface ID, which is obtained from **XComponent**. | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| +## QualityLevel -**Example** +Enumerates the image quality levels. -```js -camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { - if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with previewOutput instance'); -}); -``` +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| QUALITY_LEVEL_HIGH | 0 | High image quality. | +| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| +| QUALITY_LEVEL_LOW | 2 | Low image quality. | -## camera.createPreviewOutput -createPreviewOutput(surfaceId: string): Promise\ +## PhotoCaptureSetting -Creates a **PreviewOutput** instance. This API uses a promise to return the result. +Defines the settings for photo capture. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +| 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 -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------------------------------- | -| surfaceId | string | Yes | Surface ID, which is obtained from **XComponent**.| +Implements output information used in a **CaptureSession**. -**Return value** +### capture + +capture(callback: AsyncCallback): void + +Captures a photo with the default shooting parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core -| Type | Description | -| ----------------------------------------- | --------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -camera.createPreviewOutput("surfaceId").then((previewOutput) => { - console.log('Promise returned with the PreviewOutput instance'); -}) +photoOutput.capture((err) => { + if (err) { + console.error(`Failed to capture the photo ${err.message}`); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); ``` -## PreviewOutput - -Implements preview output. - -### release +### capture -release(callback: AsyncCallback): void +capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void -Releases this **PreviewOutput** instance. This API uses an asynchronous callback to return the result. +Captures a photo with the specified shooting parameters. 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 result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -previewOutput.release((err) => { +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} +photoOutput.capture(settings, (err) => { if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); + console.error(`Failed to capture the photo ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); + console.log('Callback invoked to indicate the photo capture request success.'); }); ``` -### release +### capture -release(): Promise +capture(setting?: PhotoCaptureSetting): Promise -Releases this **PreviewOutput** instance. This API uses a promise to return the result. +Captures a photo with the specified shooting parameters. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | -------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| + **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** ```js -previewOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +photoOutput.capture().then(() => { + console.log('Promise returned to indicate that photo capture request success.'); }) ``` -### on('frameStart') +### isMirrorSupported -on(type: 'frameStart', callback: AsyncCallback): void +isMirrorSupported(callback: AsyncCallback): void -Listens for preview frame start events. This API uses an asynchronous callback to return the result. +Checks whether mirroring is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| 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. | +| 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** ```js -previewOutput.on('frameStart', () => { - console.log('Preview frame started'); +photoOutput.isMirrorSupported((err, isSupported) => { + if (err) { + console.error(`Failed to check mirror is supported ${err.message}`); + return; + } + console.log('Callback returned with the successful execution of isMirrorSupported.'); }) ``` -### on('frameEnd') +### isMirrorSupported -on(type: 'frameEnd', callback: AsyncCallback): void +isMirrorSupported(): Promise -Listens for preview frame end events. This API uses an asynchronous callback to return the result. +Checks whether mirroring is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +**Return value** -| 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. | +| 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** ```js -previewOutput.on('frameEnd', () => { - console.log('Preview frame ended'); +photoOutput.isMirrorSupported().then((isSupported) => { + console.log(`Promise returned with mirror supported: ${isSupported}`); }) ``` -### on('error') +### on('captureStart') -on(type: 'error', callback: ErrorCallback): void +on(type: 'captureStart', callback: AsyncCallback): void -Listens for **PreviewOutput** errors. This API uses a callback to return the errors. +Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. **System capability**: SystemCapability.Multimedia.Camera.Core **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 **'captureStart'**, indicating the shooting start event.| +| callback | AsyncCallback | Yes | Callback used to return the capture ID. | **Example** ```js -previewOutput.on('error', (previewOutputError) => { - console.log('Preview output error code: ' + previewOutputError.code); +photoOutput.on('captureStart', (err, captureId) => { + console.log(`photo capture stated, captureId : ${captureId}`); }) ``` -## PreviewOutputErrorCode +### on('frameShutter') -Enumerates the error codes used in a **PreviewOutput** instance. +on(type: 'frameShutter', callback: AsyncCallback): void -**System capability**: SystemCapability.Multimedia.Camera.Core +Listens for frame shutter events. This API uses an asynchronous callback to return the event information. -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| +**System capability**: SystemCapability.Multimedia.Camera.Core -## PreviewOutputError +**Parameters** -Defines a **PreviewOutput** error. +| 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. | -**System capability**: SystemCapability.Multimedia.Camera.Core +**Example** -| Name| Type | Description | -| ---- | ------------------------------------------------- | ---------------------- | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| +```js +photoOutput.on('frameShutter', (err, frameShutterInfo) => { + console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`); + console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`); +}) +``` -## camera.createPhotoOutput +### on('captureEnd') -createPhotoOutput(surfaceId: string, callback: AsyncCallback): void +on(type: 'captureEnd', callback: AsyncCallback): void -Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result. +Listens for shooting end events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| 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 | +| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | +| 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** ```js -camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { - if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); - return; - } - console.log('Callback returned with the PhotoOutput instance.'); -}); +photoOutput.on('captureEnd', (err, captureEndInfo) => { + console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`); + console.log(`frameCount : ${captureEndInfo.frameCount}`); +}) ``` -## camera.createPhotoOutput +### on('error') -createPhotoOutput(surfaceId: string): Promise +on(type: 'error', callback: ErrorCallback): void -Creates a **PhotoOutput** instance. This API uses a promise to return the result. +Listens for **PhotoOutput** errors. This API uses a callback to return the errors. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------------------------------- | -| 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.| - +| 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** ```js -camera.createPhotoOutput("surfaceId").then((photoOutput) => { - console.log('Promise returned with PhotoOutput instance'); +photoOutput.on('error', (err, photoOutputError) => { + console.log(`Photo output error code: ${photoOutputError.code}`); }) ``` -## ImageRotation - -Enumerates the image rotation angles. - -**System capability**: SystemCapability.Multimedia.Camera.Core -| 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.| -| ROTATION_270 | 270 | The image rotates 270 degrees.| - -## QualityLevel +## FrameShutterInfo -Enumerates the image quality levels. +Defines the frame shutter information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------- | ---- | -------------- | -| QUALITY_LEVEL_HIGH | 0 | High image quality. | -| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| -| QUALITY_LEVEL_LOW | 2 | Low image quality. | - +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------- | +| captureId | number | Yes | ID of this capture action. | +| timestamp | number | Yes | Timestamp when the frame shutter event is triggered.| -## PhotoCaptureSetting +## CaptureEndInfo -Defines the settings for photo capture. +Defines the capture end information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | -------------- | -| quality | [QualityLevel](#qualitylevel) | No | Photo quality. | -| rotation | [ImageRotation](#imagerotation) | No | Rotation angle of the photo.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------| +| captureId | number | Yes | ID of this capture action.| +| frameCount | number | Yes | Number of frames captured. | +## PhotoOutputErrorCode -## PhotoOutput +Enumerates the error codes used for photo output. -Implements photo output. +**System capability**: SystemCapability.Multimedia.Camera.Core -### capture +| 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. | -capture(callback: AsyncCallback): void +## PhotoOutputError -Captures a photo with the default shooting settings. This API uses an asynchronous callback to return the result. +Defines a photo output error. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | **PhotoOutput** error code.| -**Example** +## VideoOutput -```js -photoOutput.capture((err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` +Implements output information used in a video recording session. -### capture +### start -capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void +start(callback: AsyncCallback): void -Captures a photo with the specified shooting settings. This API uses an asynchronous callback to return the result. +Starts video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------ | -| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 -} -photoOutput.capture(settings, (err) => { +videoOutput.start((err) => { if (err) { - console.error('Failed to capture the photo ${err.message}'); + console.error(`Failed to start the video output ${err.message}`); return; } - console.log('Callback invoked to indicate the photo capture request success.'); + console.log('Callback invoked to indicate the video output start success.'); }); ``` -### capture +### start -capture(setting?: PhotoCaptureSetting): Promise +start(): Promise -Captures a photo with the specified shooting settings. This API uses a promise to return the result. +Starts video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------- | ---- | ---------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| - **Return value** -| Type | Description | -| -------------- | --------------------------- | +| Type | Description | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** ```js -photoOutput.capture().then(() => { - console.log('Promise returned to indicate that photo capture request success.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that start method execution success.'); }) ``` -### release +### stop -release(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Releases this **PhotoOutput** instance. This API uses an asynchronous callback to return the result. +Stops video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2290,465 +3545,465 @@ Releases this **PhotoOutput** instance. This API uses an asynchronous callback t **Example** ```js -photoOutput.release((err) => { +videoOutput.stop((err) => { if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); + console.error(`Failed to stop the video output ${err.message}`); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); + console.log('Callback invoked to indicate the video output stop success.'); }); ``` -### release +### stop -release(): Promise +stop(): Promise -Releases this **PhotoOutput** instance. This API uses a promise to return the result. +Stops video recording. 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 the result.| - **Example** ```js -photoOutput.release().then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); +videoOutput.stop().then(() => { + console.log('Promise returned to indicate that stop method execution success.'); }) -``` +``` -### on('captureStart') +### on('frameStart') -on(type: 'captureStart', callback: AsyncCallback): void +on(type: 'frameStart', callback: AsyncCallback): void -Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. +Listens for video recording start events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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 **`frameStart`**, indicating the video recording start event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -photoOutput.on('captureStart', (err, captureId) => { - console.log('photo capture stated, captureId : ' + captureId); +videoOutput.on('frameStart', () => { + console.log('Video frame started'); }) ``` -### on('frameShutter') +### on('frameEnd') -on(type: 'frameShutter', callback: AsyncCallback): void +on(type: 'frameEnd', callback: AsyncCallback): void -Listens for frame shutter events. This API uses an asynchronous callback to return the event information. +Listens for video recording stop events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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 **'frameEnd'**, indicating the video recording stop event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -photoOutput.on('frameShutter', (err, frameShutterInfo) => { - console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); - console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +videoOutput.on('frameEnd', () => { + console.log('Video frame ended'); }) ``` -### on('captureEnd') +### on('error') -on(type: 'captureEnd', callback: AsyncCallback): void +on(type: 'error', callback: ErrorCallback): void -Listens for shooting end events. This API uses an asynchronous callback to return the event information. +Listens for errors that occur during video recording. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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 **'error'**, indicating the video output error event.| +| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | **Example** ```js -photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.log('photo capture end, captureId : ' + captureEndInfo.captureId); - console.log('frameCount : ' + captureEndInfo.frameCount); +videoOutput.on('error', (VideoOutputError) => { + console.log(`Video output error code: ${VideoOutputError.code}`); }) ``` -### on('error') - -on(type: 'error', callback: ErrorCallback): void +## VideoOutputErrorCode -Listens for **PhotoOutput** errors. This API uses a callback to return the errors. +Enumerates the error codes used for video recording. **System capability**: SystemCapability.Multimedia.Camera.Core -**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. | - -**Example** - -```js -photoOutput.on('error', (err, photoOutputError) => { - console.log('Photo output error code: ' + photoOutputError.code); -}) -``` +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| -## FrameShutterInfo +## VideoOutputError -Defines the frame shutter information. +Defines a video output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ----------------------------- | -| captureId | number | Yes | ID of this capture action.| -| timestamp | number | Yes | Timestamp when the frame shutter event is triggered. | +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | **VideoOutput** error code.| -## CaptureEndInfo +## MetadataObjectType -Defines the capture end information. +Enumerates metadata streams. **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. | +| Name | Value | Description | +| ------------------------- | ---- | ----------------- | +| FACE_DETECTION | 0 | Metadata object type.| -## PhotoOutputErrorCode +## Rect -Enumerates the error codes used in a **PhotoOutput** instance. +Defines a rectangle. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| - -## PhotoOutputError - -Defines a **PhotoOutput** error. +| 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. | -**System capability**: SystemCapability.Multimedia.Camera.Core +## MetadataObject -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| +Implements camera metadata, which is the data source of **[CameraInput](#camerainput)**. -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string, callback: AsyncCallback): void +getType(callback: AsyncCallback): void -Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result. +Obtains the metadata object type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | Yes | Surface ID, which is obtained from **VideoRecorder**. | -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | --- | -------------------- | +| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.| **Example** ```js -camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { +metadataObject.getType((err, metadataObjectType) => { if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); + console.error(`Failed to get type. ${err.message}`); return; } - console.log('Callback returned with the VideoOutput instance'); -}); + console.log('Callback returned with an array of metadataObjectType.'); +}) ``` -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string): Promise +getType(): Promise -Creates a **VideoOutput** instance. This API uses a promise to return the result. +Obtains the metadata object type. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | Yes | Surface ID, which is obtained from **VideoRecorder**.| - **Return value** -| Type | Description | -| ------------------------------------- | -------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance.| +| Type | Description | +| --------------------------------------------------- | --------------------------- | +| Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.| **Example** ```js -camera.createVideoOutput("surfaceId" -).then((videoOutput) => { - console.log('Promise returned with the VideoOutput instance'); +metadataObject.getType().then((metadataObjectType) => { + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -## VideoOutput - -Implements output information used in a video recording session. - -### start +### getTimestamp -start(callback: AsyncCallback): void +getTimestamp(callback: AsyncCallback): void -Starts video recording. This API uses an asynchronous callback to return the result. +Obtains the metadata timestamp. 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 result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.start((err) => { +metadataObject.getTimestamp((err,timestamp) => { if (err) { - console.error('Failed to start the video output ${err.message}'); + console.error(`Failed to get timestamp. ${err.message}`); return; } - console.log('Callback invoked to indicate the video output start success.'); -}); + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); +}) ``` -### start +### getTimestamp -start(): Promise +getTimestamp(): Promise -Starts video recording. This API uses a promise to return the result. +Obtains the metadata timestamp. 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 result.| - +| Type | Description | +| ---------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that start method execution success.'); +metadataObject.getTimestamp().then((timestamp) => { + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); }) ``` -### stop +### getBoundingBox -stop(callback: AsyncCallback): void +getBoundingBox(callback: AsyncCallback): void -Stops video recording. This API uses an asynchronous callback to return the result. +Obtains the bounding box of metadata. 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 result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| **Example** ```js -videoOutput.stop((err) => { +metadataObject.getBoundingBox((err, rect) => { if (err) { - console.error('Failed to stop the video output ${err.message}'); + console.error(`Failed to get boundingBox. ${err.message}`); return; } - console.log('Callback invoked to indicate the video output stop success.'); -}); + console.log('Callback returned with boundingBox getted.'); +}) ``` -### stop +### getBoundingBox -stop(): Promise +getBoundingBox(): Promise -Stops video recording. This API uses a promise to return the result. +Obtains the bounding box of metadata. 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 result.| +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<[Rect](#rect)\> | Promise used to return the result.| **Example** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that stop method execution success.'); +metadataObject.getBoundingBox().then((rect) => { + console.log('Callback returned with boundingBox getted.'); }) ``` -### release +## MetadataFaceObject -release(callback: AsyncCallback): void +Implements the face object of metadata. It inherits [MetadataObject](#metadataobject). + +## MetadataOutput + +Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. + +### start + +start(callback: AsyncCallback): void -Releases this **VideoOutput** instance. This API uses an asynchronous callback to return the result. +Starts to output metadata. 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 result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.release((err) => { +metadataOutput.start((err) => { if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); + console.error(`Failed to start metadataOutput. ${err.message}`); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); + console.log('Callback returned with metadataOutput started.'); +}) ``` -### release +### start -release(): Promise +start(): Promise -Releases this **VideoOutput** instance. This API uses a promise to return the result. +Starts to output metadata. 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 result.| - +| Type | Description | +| ---------------------- | ------------------------ | +| Promise | Promise used to return the result.| **Example** ```js -videoOutput.release().then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); +metadataOutput.start().then(() => { + console.log('Callback returned with metadataOutput started.'); }) ``` -### on('frameStart') +### stop -on(type: 'frameStart', callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Listens for video recording start events. This API uses an asynchronous callback to return the result. +Stops outputting metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| 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. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.on('frameStart', () => { - console.log('Video frame started'); +metadataOutput.stop((err) => { + if (err) { + console.error(`Failed to stop the metadataOutput. ${err.message}`); + return; + } + console.log('Callback returned with metadataOutput stopped.'); }) ``` -### on('frameEnd') +### stop -on(type: 'frameEnd', callback: AsyncCallback): void +stop(): Promise + +Stops outputting metadata. 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 result.| + +**Example** + +```js +metadataOutput.stop().then(() => { + console.log('Callback returned with metadataOutput stopped.'); +}) +``` + +### on('metadataObjectsAvailable') -Listens for video recording end events. This API uses an asynchronous callback to return the result. +on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void + +Listens for metadata objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :--------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **`frameEnd`**, indicating the video 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 **'metadataObjectsAvailable'**, that is, the metadata object.| +| callback | Callback\> | Yes | Callback used to return the error information. | **Example** ```js -videoOutput.on('frameEnd', () => { - console.log('Video frame ended'); +metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { + console.log(`metadata output error code: ${metadataObject.code}`); }) ``` ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(type: 'error', callback: ErrorCallback): void -Listens for **VideoOutput** errors. This API uses a callback to return the result. +Listens for metadata errors. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **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'**, that is, the metadata error.| +| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | **Example** ```js -videoOutput.on('error', (VideoOutputError) => { - console.log('Video output error code: ' + VideoOutputError.code); +metadataOutput.on('error', (metadataOutputError) => { + console.log(`Metadata output error code: ${metadataOutputError.code}`); }) ``` -## VideoOutputErrorCode +## MetadataOutputErrorCode -Enumerates the error codes used in a **VideoOutput** instance. +Enumerates the codes used for metadata output errors. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ------------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| -## VideoOutputError +## MetadataOutputError -Defines a **VideoOutput** error. +Defines a metadata output error. **System capability**: SystemCapability.Multimedia.Camera.Core | Name| Type | Description | | ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| +| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | **MetadataOutput** error code.| diff --git a/en/application-dev/reference/apis/js-apis-config-policy.md b/en/application-dev/reference/apis/js-apis-config-policy.md index 3c8f4d0050107f7e0b50e0d8f6c2a44d0a87e664..4e541cbfe0022219d9ebf57b0502e82984c84384 100644 --- a/en/application-dev/reference/apis/js-apis-config-policy.md +++ b/en/application-dev/reference/apis/js-apis-config-policy.md @@ -1,12 +1,12 @@ # Configuration Policy -The configuration policy provides the capability of obtaining the custom configuration directory and file path based on the predefined custom configuration level. +The **configPolicy** module provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level. > **NOTE** > > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs of this module are system APIs and cannot be called by third-party applications. +> The APIs provided by this module are system APIs. ## Modules to Import @@ -32,7 +32,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **Example** ```js configPolicy.getOneCfgFile('etc/config.xml', (error, value) => { - if (error == undefined) { + if (error == null) { console.log("value is " + value); } else { console.log("error occurs "+ error); @@ -73,7 +73,8 @@ Obtains the path of a configuration file with the specified name and highest pri getCfgFiles(relPath: string, callback: AsyncCallback<Array<string>>) -Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml**, then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned. +Obtains a list of configuration files with the specified name, sorted in ascending order of priority. This API uses an asynchronous callback to return the result. +For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml** (in ascending order of priority), then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -86,7 +87,7 @@ Obtains all configuration files with the specified name and lists them in ascend **Example** ```js configPolicy.getCfgFiles('etc/config.xml', (error, value) => { - if (error == undefined) { + if (error == null) { console.log("value is " + value); } else { console.log("error occurs "+ error); @@ -99,7 +100,7 @@ Obtains all configuration files with the specified name and lists them in ascend getCfgFiles(relPath: string): Promise<Array<string>> -Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses a promise to return the result. +Obtains a list of configuration files with the specified name, sorted in ascending order of priority. This API uses a promise to return the result. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -127,7 +128,7 @@ Obtains all configuration files with the specified name and lists them in ascend getCfgDirList(callback: AsyncCallback<Array<string>>) -Obtains the configuration level directory list. This API uses an asynchronous callback to return the result. +Obtains the list of configuration level directories. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Customization.ConfigPolicy @@ -139,7 +140,7 @@ Obtains the configuration level directory list. This API uses an asynchronous ca **Example** ```js configPolicy.getCfgDirList((error, value) => { - if (error == undefined) { + if (error == null) { console.log("value is " + value); } else { console.log("error occurs "+ error); @@ -152,7 +153,7 @@ Obtains the configuration level directory list. This API uses an asynchronous ca getCfgDirList(): Promise<Array<string>> -Obtains the configuration level directory list. This API uses a promise to return the result. +Obtains the list of configuration level directories. This API uses a promise to return the result. **System capability**: SystemCapability.Customization.ConfigPolicy 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 4c04dd7a835c647889d70dff754d6baf14730efb..3b3a18170e3cdfb1c301174c940ff9e14b6fa7f0 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -10,16 +10,18 @@ Currently, this module provides incomplete functions, and its APIs are mainly us ## Modules to Import -```js +```ts import continuationManager from '@ohos.continuation.continuationManager' ``` -## continuationManager.register +## continuationManager.register(deprecated) 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. +> This API is deprecated since API version 9. You are advised to use [registerContinuation](#continuationmanagerregistercontinuation9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -28,9 +30,19 @@ Registers the continuation management service and obtains a token. This API does | -------- | -------- | -------- | -------- | | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | + **Example** - ```js + ```ts let token = -1; continuationManager.register((err, data) => { if (err.code != 0) { @@ -42,12 +54,14 @@ Registers the continuation management service and obtains a token. This API does }); ``` -## continuationManager.register +## continuationManager.register(deprecated) 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. +> This API is deprecated since API version 9. You are advised to use [registerContinuation](#continuationmanagerregistercontinuation9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -57,9 +71,20 @@ Registers the continuation management service and obtains a token. This API uses | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.| | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | +| 29360216 | Invalid continuation mode. | + **Example** - ```js + ```ts let token = -1; let continuationExtraParams = { deviceType: ["00E"] @@ -74,12 +99,14 @@ Registers the continuation management service and obtains a token. This API uses }); ``` -## continuationManager.register +## continuationManager.register(deprecated) register(options?: ContinuationExtraParams): Promise\; Registers the continuation management service and obtains a token. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [registerContinuation](#continuationmanagerregistercontinuation9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -94,9 +121,20 @@ Registers the continuation management service and obtains a token. This API uses | ------------------------- | ------------------ | | Promise\ | Promise used to return the token generated after the continuation management service is connected.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | +| 29360216 | Invalid continuation mode. | + **Example** - ```js + ```ts let token = -1; let continuationExtraParams = { deviceType: ["00E"] @@ -111,13 +149,159 @@ Registers the continuation management service and obtains a token. This API uses }); ``` +## continuationManager.registerContinuation9+ + +registerContinuation(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. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + +**Example** + + ```ts + let token = -1; + try { + continuationManager.registerContinuation((err, data) => { + if (err.code != 0) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('registerContinuation finished, ' + JSON.stringify(data)); + token = data; + }); + } catch (err) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.registerContinuation9+ + +registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\): void; + +Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.| + | callback | AsyncCallback\ | Yes| Callback used to return the token generated after the continuation management service is connected.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + +**Example** + + ```ts + let token = -1; + let continuationExtraParams = { + deviceType: ["00E"] + }; + try { + continuationManager.registerContinuation(continuationExtraParams, (err, data) => { + if (err.code != 0) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('registerContinuation finished, ' + JSON.stringify(data)); + token = data; + }); + } catch (err) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.registerContinuation9+ + +registerContinuation(options?: ContinuationExtraParams): Promise\; + +Registers the continuation management service and obtains a token. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the token generated after the continuation management service is connected.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + +**Example** + + ```ts + let token = -1; + let continuationExtraParams = { + deviceType: ["00E"] + }; + try { + continuationManager.register(continuationExtraParams) + .then((data) => { + console.info('registerContinuation finished, ' + JSON.stringify(data)); + token = data; + }) + .catch((err) => { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('registerContinuation failed, cause: ' + JSON.stringify(err)); + } + ``` + + ## continuationManager.on("deviceConnect")(deprecated) 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. +> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceselected9) instead. **System capability**: SystemCapability.Ability.DistributedAbilityManager @@ -128,9 +312,21 @@ Subscribes to device connection events. This API uses an asynchronous callback t | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null | 7 | +| 29360208 | The token has not registered. | +| 29360209 | Callback has been registered. | +| 29360214 | The type of callback is not supported. | + **Example** - ```js + ```ts continuationManager.on("deviceConnect", (data) => { console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); @@ -144,7 +340,7 @@ 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. +> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceunselected9) instead. **System capability**: SystemCapability.Ability.DistributedAbilityManager @@ -153,11 +349,23 @@ Subscribes to device disconnection events. This API uses an asynchronous callbac | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| - | callback | Callback\ | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + | callback | Callback\ | Yes| Callback invoked when a device is unselected from the device list provided by the device selection module. This callback returns the device ID.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360209 | Callback has been registered. | +| 29360214 | The type of callback is not supported. | **Example** - ```js + ```ts continuationManager.on("deviceDisconnect", (data) => { console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); }); @@ -169,7 +377,7 @@ 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. +> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceselected9) instead. **System capability**: SystemCapability.Ability.DistributedAbilityManager @@ -180,9 +388,21 @@ Unsubscribes from device connection events. This API uses an asynchronous callba | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | No| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360214 | The type of callback is not supported. | + **Example** - ```js + ```ts continuationManager.off("deviceConnect", (data) => { console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); @@ -196,7 +416,7 @@ 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. +> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceunselected9) instead. **System capability**: SystemCapability.Ability.DistributedAbilityManager @@ -205,125 +425,209 @@ Unsubscribes from device disconnection events. This API uses an asynchronous cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| - | callback | Callback\ | No| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + | callback | Callback\ | No| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360214 | The type of callback is not supported. | **Example** - ```js + ```ts continuationManager.off("deviceDisconnect", (data) => { console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); }); ``` -## continuationManager.on("deviceConnect")9+ +## continuationManager.on("deviceSelected")9+ -on(type: "deviceConnect", token: number, callback: Callback\>): void; +on(type: "deviceSelected", token: number, callback: Callback\>): void; Subscribes to device connection events. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | type | string | Yes| Event type. The value is fixed at **deviceSelected**.| | token | number | Yes| Token obtained after the registration of the continuation management service.| | callback | Callback\> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **Example** - ```js + ```ts let token = 1; - continuationManager.on("deviceConnect", token, (data) => { - console.info('onDeviceConnect len: ' + data.length); - for (let i = 0; i < data.length; i++) { - console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id)); - console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type)); - console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name)); - } - }); + try { + continuationManager.on("deviceSelected", token, (data) => { + console.info('onDeviceSelected len: ' + data.length); + for (let i = 0; i < data.length; i++) { + console.info('onDeviceSelected deviceId: ' + JSON.stringify(data[i].id)); + console.info('onDeviceSelected deviceType: ' + JSON.stringify(data[i].type)); + console.info('onDeviceSelected deviceName: ' + JSON.stringify(data[i].name)); + } + }); + } catch (err) { + console.error('on failed, cause: ' + JSON.stringify(err)); + } ``` -## continuationManager.on("deviceDisconnect")9+ +## continuationManager.on("deviceUnselected")9+ -on(type: "deviceDisconnect", token: number, callback: Callback\>): void; +on(type: "deviceUnselected", token: number, callback: Callback\>): void; Subscribes to device disconnection events. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | type | string | Yes| Event type. The value is fixed at **deviceUnselected**.| | token | number | Yes| Token obtained after the registration of the continuation management service.| - | callback | Callback\> | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + | callback | Callback\> | Yes| Callback invoked when a device is unselected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | **Example** - ```js + ```ts let token = 1; - continuationManager.on("deviceDisconnect", token, (data) => { - console.info('onDeviceDisconnect len: ' + data.length); - for (let i = 0; i < data.length; i++) { - console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i])); - } - console.info('onDeviceDisconnect finished.'); - }); + try { + continuationManager.on("deviceUnselected", token, (data) => { + console.info('onDeviceUnselected len: ' + data.length); + for (let i = 0; i < data.length; i++) { + console.info('onDeviceUnselected deviceId: ' + JSON.stringify(data[i].id)); + console.info('onDeviceUnselected deviceType: ' + JSON.stringify(data[i].type)); + console.info('onDeviceUnselected deviceName: ' + JSON.stringify(data[i].name)); + } + console.info('onDeviceUnselected finished.'); + }); + } catch (err) { + console.error('on failed, cause: ' + JSON.stringify(err)); + } ``` -## continuationManager.off("deviceConnect")9+ +## continuationManager.off("deviceSelected")9+ -off(type: "deviceConnect", token: number): void; +off(type: "deviceSelected", token: number): void; Unsubscribes from device connection events. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | type | string | Yes| Event type. The value is fixed at **deviceSelected**.| | token | number | Yes| Token obtained after the registration of the continuation management service.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **Example** - ```js + ```ts let token = 1; - continuationManager.off("deviceConnect", token); + try { + continuationManager.off("deviceSelected", token); + } catch (err) { + console.error('off failed, cause: ' + JSON.stringify(err)); + } ``` -## continuationManager.off("deviceDisconnect")9+ +## continuationManager.off("deviceUnselected")9+ -off(type: "deviceDisconnect", token: number): void; +off(type: "deviceUnselected", token: number): void; Unsubscribes from device disconnection events. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | type | string | Yes| Event type. The value is fixed at **deviceUnselected**.| | token | number | Yes| Token obtained after the registration of the continuation management service.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **Example** - ```js + ```ts let token = 1; - continuationManager.off("deviceDisconnect", token); + try { + continuationManager.off("deviceUnselected", token); + } catch (err) { + console.error('off failed, cause: ' + JSON.stringify(err)); + } ``` -## continuationManager.startDeviceManager +## continuationManager.startDeviceManager(deprecated) startDeviceManager(token: number, callback: AsyncCallback\): void; Starts the device selection module to show the list of available devices on the network. This API does not involve any filter parameters and uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -333,9 +637,22 @@ Starts the device selection module to show the list of available devices on the | token | number | Yes| Token obtained after the registration of the continuation management service.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360211 | Failed to connect ability. | +| 29360216 | Invalid continuation mode. | + **Example** - ```js + ```ts let token = 1; continuationManager.startDeviceManager(token, (err, data) => { if (err.code != 0) { @@ -346,12 +663,14 @@ Starts the device selection module to show the list of available devices on the }); ``` -## continuationManager.startDeviceManager +## continuationManager.startDeviceManager(deprecated) startDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void; Starts the device selection module to show the list of available devices on the network. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -362,9 +681,22 @@ Starts the device selection module to show the list of available devices on the | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360211 | Failed to connect ability. | +| 29360216 | Invalid continuation mode. | + **Example** - ```js + ```ts let token = 1; let continuationExtraParams = { deviceType: ["00E"] @@ -378,12 +710,14 @@ Starts the device selection module to show the list of available devices on the }); ``` -## continuationManager.startDeviceManager +## continuationManager.startDeviceManager(deprecated) startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\; Starts the device selection module to show the list of available devices on the network. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -399,9 +733,22 @@ Starts the device selection module to show the list of available devices on the | ------------------------- | ------------------ | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360211 | Failed to connect ability. | +| 29360216 | Invalid continuation mode. | + **Example** - ```js + ```ts let token = 1; let continuationExtraParams = { deviceType: ["00E"] @@ -415,12 +762,159 @@ Starts the device selection module to show the list of available devices on the }); ``` -## continuationManager.updateConnectStatus +## continuationManager.startContinuationDeviceManager9+ + +startContinuationDeviceManager(token: number, callback: AsyncCallback\): void; + +Starts the device selection module to show the list of available devices on the network. This API does not involve any filter parameters and uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + try { + continuationManager.startContinuationDeviceManager(token, (err, data) => { + if (err.code != 0) { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data)); + }); + } catch (err) { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.startContinuationDeviceManager9+ + +startContinuationDeviceManager(token: number, options: ContinuationExtraParams, callback: AsyncCallback\): void; + +Starts the device selection module to show the list of available devices on the network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Yes| Extra parameters used to filter the list of available devices.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + let continuationExtraParams = { + deviceType: ["00E"] + }; + try { + continuationManager.startContinuationDeviceManager(token, continuationExtraParams, (err, data) => { + if (err.code != 0) { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data)); + }); + } catch (err) { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.startContinuationDeviceManager9+ + +startContinuationDeviceManager(token: number, options?: ContinuationExtraParams): Promise\; + +Starts the device selection module to show the list of available devices on the network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + let continuationExtraParams = { + deviceType: ["00E"] + }; + try { + continuationManager.startContinuationDeviceManager(token, continuationExtraParams) + .then((data) => { + console.info('startContinuationDeviceManager finished, ' + JSON.stringify(data)); + }) + .catch((err) => { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('startContinuationDeviceManager failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.updateConnectStatus(deprecated) 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. +> This API is deprecated since API version 9. You are advised to use [updateContinuationState](#continuationmanagerupdatecontinuationstate9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -432,9 +926,22 @@ Instructs the device selection module to update the device connection state. Thi | status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360211 | Failed to connect ability. | +| 29360215 | Invalid connect state. | + **Example** - ```js + ```ts let token = 1; let deviceId: string = "test deviceId"; continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED, (err, data) => { @@ -446,12 +953,14 @@ Instructs the device selection module to update the device connection state. Thi }); ``` -## continuationManager.updateConnectStatus +## continuationManager.updateConnectStatus(deprecated) 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. +> This API is deprecated since API version 9. You are advised to use [updateContinuationState](#continuationmanagerupdatecontinuationstate9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -468,9 +977,22 @@ Instructs the device selection module to update the device connection state. Thi | ------------------------- | ------------------ | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360211 | Failed to connect ability. | +| 29360215 | Invalid connect state. | + **Example** - ```js + ```ts let token = 1; let deviceId: string = "test deviceId"; continuationManager.updateConnectStatus(token, deviceId, continuationManager.DeviceConnectState.CONNECTED) @@ -482,12 +1004,114 @@ Instructs the device selection module to update the device connection state. Thi }); ``` -## continuationManager.unregister +## continuationManager.updateContinuationState9+ + +updateContinuationState(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. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | deviceId | string | Yes| Device ID.| + | status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + let deviceId: string = "test deviceId"; + try { + continuationManager.updateContinuationState(token, deviceId, continuationManager.DeviceConnectState.CONNECTED, (err, data) => { + if (err.code != 0) { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('updateContinuationState finished, ' + JSON.stringify(data)); + }); + } catch (err) { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.updateContinuationState9+ + +updateContinuationState(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. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | deviceId | string | Yes| Device ID.| + | status | [DeviceConnectState](#deviceconnectstate) | Yes| Device connection state.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + let deviceId: string = "test deviceId"; + try { + continuationManager.updateContinuationState(token, deviceId, continuationManager.DeviceConnectState.CONNECTED) + .then((data) => { + console.info('updateContinuationState finished, ' + JSON.stringify(data)); + }) + .catch((err) => { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('updateContinuationState failed, cause: ' + JSON.stringify(err)); + } + ``` + + +## continuationManager.unregister(deprecated) unregister(token: number, callback: AsyncCallback\): void; Deregisters the continuation management service. This API uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [unregisterContinuation](#continuationmanagerunregistercontinuation9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -497,9 +1121,19 @@ Deregisters the continuation management service. This API uses an asynchronous c | token | number | Yes| Token obtained after the registration of the continuation management service.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | + **Example** - ```js + ```ts let token = 1; continuationManager.unregister(token, (err, data) => { if (err.code != 0) { @@ -510,12 +1144,14 @@ Deregisters the continuation management service. This API uses an asynchronous c }); ``` -## continuationManager.unregister +## continuationManager.unregister(deprecated) unregister(token: number): Promise\; Deregisters the continuation management service. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [unregisterContinuation](#continuationmanagerunregistercontinuation9) instead. + **System capability**: SystemCapability.Ability.DistributedAbilityManager **Parameters** @@ -530,9 +1166,19 @@ Deregisters the continuation management service. This API uses a promise to retu | ------------------------- | ------------------ | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | + **Example** - ```js + ```ts let token = 1; continuationManager.unregister(token) .then((data) => { @@ -543,6 +1189,100 @@ Deregisters the continuation management service. This API uses a promise to retu }); ``` +## continuationManager.unregisterContinuation9+ + +unregisterContinuation(token: number, callback: AsyncCallback\): void; + +Deregisters the continuation management service. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + try { + continuationManager.unregisterContinuation(token, (err, data) => { + if (err.code != 0) { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('unregisterContinuation finished, ' + JSON.stringify(data)); + }); + } catch (err) { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + } + ``` + +## continuationManager.unregisterContinuation9+ + +unregisterContinuation(token: number): Promise\; + +Deregisters the continuation management service. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | number | Yes| Token obtained after the registration of the continuation management service.| + +**Return value** + +| Type | Description | +| ------------------------- | ------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + +**Example** + + ```ts + let token = 1; + try { + continuationManager.unregisterContinuation(token) + .then((data) => { + console.info('unregisterContinuation finished, ' + JSON.stringify(data)); + }) + .catch((err) => { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('unregisterContinuation failed, cause: ' + JSON.stringify(err)); + } + ``` + + ## DeviceConnectState Enumerates the device connection states. diff --git a/en/application-dev/reference/apis/js-apis-cooperate.md b/en/application-dev/reference/apis/js-apis-cooperate.md new file mode 100644 index 0000000000000000000000000000000000000000..96fa3ebc9ff8fadf13097fd6042339ad202f186c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cooperate.md @@ -0,0 +1,390 @@ +# Screen Hopping + +The Screen Hopping module enables two or more networked devices to share the keyboard and mouse for collaborative operations. + +> **Description** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import inputDeviceCooperate from '@ohos.multimodalInput.inputDeviceCooperate' +``` + +## inputDeviceCooperate.enable + +enable(enable: boolean, callback: AsyncCallback<void>): void + +Specifies whether to enable screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------------------- | +| enable | boolean | Yes | Whether to enable screen hopping.| +| callback | AsyncCallback<void> | Yes |Callback used to return the result. | + + + +**Example** + +```js +try { + inputDeviceCooperate.enable(true, (error) => { + if (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Keyboard mouse crossing enable success.`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.enable + +enable(enable: boolean): Promise<void> + +Specifies whether to enable screen hopping. This API uses a promise to return the result. + + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------- | ---- | ------------------------------------------------------------------- | +| enable | boolean | Yes | Whether to enable screen hopping. | + + + +**Return value** + +| Name | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result. | + + + +**Example** + +```js +try { + inputDeviceCooperate.enable(true).then(() => { + console.log(`Keyboard mouse crossing enable success.`); + }, (error) => { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.start + +start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback\): void + +Starts screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| sinkDeviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. | +| srcInputDeviceId | number | Yes | ID of the target device for screen hopping. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcodes-multimodalinput.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 4400001 | This error code is reported if an invalid device descriptor is passed to the screen hopping API. | +| 4400002 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | + +**Example** + +```js +try { + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => { + if (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Start Keyboard mouse crossing success.`); + }); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.start + +start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ + +Starts screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| sinkDeviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. | +| srcInputDeviceId | number | Yes | ID of the target device for screen hopping. | + + + +**Return value** + +| Name | Description | +| ---------------------- | ------------------------------- | +| Promise\ | Promise used to return the result. | + +**Error codes** + +For details about the error codes, see [Screen Hopping Error Codes](../errorcodes/errorcodes-multimodalinput.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 4400001 | This error code is reported if an invalid device descriptor is passed to the screen hopping API. | +| 4400002 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. | + +**Example** + +```js +try { + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => { + console.log(`Start Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.stop + +stop(callback: AsyncCallback\): void + +Stops screen hopping. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + + + +**Example** + +```js +try { + inputDeviceCooperate.stop((error) => { + if (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Stop Keyboard mouse crossing success.`); + }); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.stop + +stop(): Promise\ + +Stops screen hopping. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Description | +| -------- | ---------------------------- | +| Promise\ | Promise used to return the result. | + +**Example** + +```js +try { + inputDeviceCooperate.stop().then(() => { + console.log(`Stop Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.getState + +getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): void + +Checks whether screen hopping is enabled. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| deviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. | +| callback | AsyncCallback<{ state: boolean }> | Yes | Callback used to return the result. | + +**Example** + +```js +try { + inputDeviceCooperate.getState(deviceDescriptor, (error, data) => { + if (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## inputDeviceCooperate.getState + +getState(deviceDescriptor: string): Promise<{ state: boolean }> + +Checks whether screen hopping is enabled. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------- | ---- | ---------------------------- | +| deviceDescriptor | string | Yes | Descriptor of the target device for screen hopping. | + + + +**Return value** + +| Name | Description | +| ------------------- | ------------------------------- | +| Promise<{ state: boolean }>| Promise used to return the result. | + + + +**Example** + +```js +try { + inputDeviceCooperate.getState(deviceDescriptor).then((data) => { + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }, (error) => { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + }); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## on('cooperation') + +on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, eventMsg: EventMsg }>): void + +Enables listening for screen hopping events. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| type | string | Yes | Event type. The value is **cooperation**. | +| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | Yes | Callback used to return the result. | + + + +**Example** + +```js +try { + inputDeviceCooperate.on('cooperation', (data) => { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); + }); +} catch (err) { + console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## off('cooperation') + +off(type: 'cooperation', callback?: AsyncCallback\): void + +Disables listening for screen hopping events. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------------- | +| type | string | Yes | Event type. The value is **cooperation**. | +| callback | AsyncCallback | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.| + + + +**Example** + +```js +// Unregister a single callback. +callback: function(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +}, +try { + inputDeviceCooperate.on('cooperation', this.callback); + inputDeviceCooperate.off("cooperation", this.callback); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` +```js +// Unregister all callbacks. +callback: function(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +}, +try { + inputDeviceCooperate.on('cooperation', this.callback); + inputDeviceCooperate.off("cooperation"); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## EventMsg + +Enumerates screen hopping event. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate + +| Name | Value | Description | +| -------- | --------- | ----------------- | +| MSG_COOPERATE_INFO_START | 200 | Screen hopping starts. | +| MSG_COOPERATE_INFO_SUCCESS | 201 | Screen hopping succeeds. | +| MSG_COOPERATE_INFO_FAIL | 202 | Screen hopping fails. | +| MSG_COOPERATE_STATE_ON | 500 | Screen hopping is enabled. | +| MSG_COOPERATE_STATE_OFF | 501 | Screen hopping is disabled. | diff --git a/en/application-dev/reference/apis/js-apis-distributedBundle.md b/en/application-dev/reference/apis/js-apis-distributedBundle.md new file mode 100644 index 0000000000000000000000000000000000000000..4df752e4c6b97ba160a40f9c14c6a729f629a1b0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributedBundle.md @@ -0,0 +1,503 @@ +# distributedBundle + +The **distributedBundle** module provides APIs for managing distributed bundles. + +> **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 provided by this module are system APIs. + +## Modules to Import + +``` +import distributedBundle from '@ohos.bundle.distributedBundle'; +``` + +## System Capability + +SystemCapability.BundleManager.DistributedBundleFramework + +## Required Permissions + +| Permission | Permission Level | Description | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.| + +For details, see "Permission Levels" in [Access Control Overview](../../security/accesstoken-overview.md). + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback\): void; + +Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName): Promise\; + +Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\>): void; + +Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application1', + abilityName: 'MainAbility1' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\): Promise\>; + +Obtains information about remote abilities that match the given element names. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ]).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, locale: string, callback: AsyncCallback\): void; + +Obtains information about the remote ability that matches the given element name and locale. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | +| locale | string |Yes| Target locale.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, 'zh-Hans-CN', (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, locale: string): Promise\; + +Obtains information about the remote ability that matches the given element name and locale. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.| +| locale | string |Yes| Target locale.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise used to return the **RemoteAbilityInfo** object obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, 'zh-Hans-CN').then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, locale: string, callback: AsyncCallback\>): void; + +Obtains information about remote abilities that match the given element names and locales. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| locale | string |Yes| Target locale.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application1', + abilityName: 'MainAbility1' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], 'zh-Hans-CN', (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise\>; + +Obtains information about remote abilities that match the given element names and locales. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| +| locale | string |Yes| Target locale.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise used to return the array of **RemoteAbilityInfo** objects obtained.| + +**Error codes** + +For details about the error codes, see [Bundle Error Codes](../errorcodes/errcode-bundle.md). + +| ID | Error Message | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**Example** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], 'zh-Hans-CN').then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index 3d5a11c39a470fd730ae359619d7ee0c29dc9eb6..aa49db0f38c911850ec73e2fdb00fa98399ff1fc 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,6 +1,6 @@ # Distributed Mission Management -The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, and start or stop synchronizing the remote mission list. +The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. > **NOTE** > @@ -48,16 +48,23 @@ Registers a mission status listener. This API uses an asynchronous callback to r console.log('NotifyNetDisconnect state ' + JSON.stringify(state)); } var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; var options = { notifyMissionsChanged: NotifyMissionsChanged, notifySnapshot: NotifySnapshot, notifyNetDisconnect: NotifyNetDisconnect } - distributedMissionManager.registerMissionListener(parameter, options, (error) => { - console.log("error.code = " + error.code) - }) + try { + distributedMissionManager.registerMissionListener(parameter, options, (error) => { + if (error.code != 0) { + console.error('registerMissionListener failed, cause: ' + JSON.stringify(error)) + } + console.info('registerMissionListener finished') + }) + } catch (error) { + console.error('registerMissionListener failed, cause: ' + JSON.stringify(error)) + } ``` ## distributedMissionManager.registerMissionListener @@ -97,19 +104,23 @@ Registers a mission status listener. This API uses a promise to return the resul console.log('NotifyNetDisconnect state ' + JSON.stringify(state)); } var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; var options = { notifyMissionsChanged: NotifyMissionsChanged, notifySnapshot: NotifySnapshot, notifyNetDisconnect: NotifyNetDisconnect } - distributedMissionManager.registerMissionListener(parameter, options) - .then(data => { - console.info('success data is ' + data); - }).catch(error => { - console.info('error error is ' + error); - }) + try { + distributedMissionManager.registerMissionListener(parameter, options) + .then(data => { + console.info('registerMissionListener finished, ' + JSON.stringify(data)); + }).catch(error => { + console.error('registerMissionListener failed, cause: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error('registerMissionListener failed, cause: ' + JSON.stringify(error)) + } ``` @@ -134,11 +145,18 @@ Deregisters a mission status listener. This API uses an asynchronous callback to ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; - distributedMissionManager.unRegisterMissionListener(parameter, (error) => { - console.log("error.code = " + error.code) - }) + try { + distributedMissionManager.unRegisterMissionListener(parameter, (error) => { + if (error.code != 0) { + console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error)) + } + console.info('unRegisterMissionListener finished') + }) + } catch (error) { + console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error)) + } ``` @@ -168,14 +186,18 @@ Deregisters a mission status listener. This API uses a promise to return the res ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; - distributedMissionManager.unRegisterMissionListener(parameter) - .then(data => { - console.info('success data is ' + data); - }).catch(error => { - console.info('error error is ' + error); - }) + try { + distributedMissionManager.unRegisterMissionListener(parameter) + .then(data => { + console.info('unRegisterMissionListener finished, ' + JSON.stringify(data)); + }).catch(error => { + console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error('unRegisterMissionListener failed, cause: ' + JSON.stringify(error)) + } ``` ## distributedMissionManager.startSyncRemoteMissions @@ -199,13 +221,20 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal ```ts var parameter = { - deviceId: remoteDeviceId, + deviceId: "", fixConflict: false, tag: 0 }; - distributedMissionManager.startSyncRemoteMissions(parameter, (error) => { - console.log("error.code = " + error.code) - }) + try { + distributedMissionManager.startSyncRemoteMissions(parameter, (error) => { + if (error.code != 0) { + console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } + console.info('startSyncRemoteMissions finished') + }) + } catch (error) { + console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } ``` ## distributedMissionManager.startSyncRemoteMissions @@ -234,16 +263,20 @@ Starts to synchronize the remote mission list. This API uses a promise to return ```ts var parameter = { - deviceId: remoteDeviceId, + deviceId: "", fixConflict: false, tag: 0 }; - distributedMissionManager.startSyncRemoteMissions(parameter) - .then(data => { - console.info('success data is ' + data); - }).catch(error => { - console.info('error error is ' + error); - }) + try { + distributedMissionManager.startSyncRemoteMissions(parameter) + .then(data => { + console.info('startSyncRemoteMissions finished, ' + JSON.stringify(data)); + }).catch(error => { + console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error('startSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } ``` ## distributedMissionManager.stopSyncRemoteMissions @@ -267,11 +300,18 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; - distributedMissionManager.stopSyncRemoteMissions(parameter, (error) => { - console.log("error.code = " + error.code) - }) + try { + distributedMissionManager.stopSyncRemoteMissions(parameter, (error) => { + if (error.code != 0) { + console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } + console.info('stopSyncRemoteMissions finished') + }) + } catch (error) { + console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } ``` ## distributedMissionManager.stopSyncRemoteMissions @@ -300,14 +340,113 @@ Stops synchronizing the remote mission list. This API uses a promise to return t ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" + }; + try { + distributedMissionManager.stopSyncRemoteMissions(parameter) + .then(data => { + console.info('stopSyncRemoteMissions finished, ' + JSON.stringify(data)); + }).catch(error => { + console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error('stopSyncRemoteMissions failed, cause: ' + JSON.stringify(error)) + } + ``` + +## distributedMissionManager.continueMission + +continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback<void>): void; + +Continues a mission on a remote device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------------------------------------- | ---- | ----- | +| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.| +| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + + ```ts + var parameter = { + srcDeviceId: "", + dstDeviceId: "", + missionId: 1, + wantParam: {"key": "value"} + }; + function OnContinueDone(resultCode) { + console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + }; + var options = { + OnContinueDone: OnContinueDone + }; + try { + distributedMissionManager.continueMission(parameter, options, (error) => { + if (error.code != 0) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + console.info('continueMission finished') + }) + } catch (error) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } + ``` + +## distributedMissionManager.continueMission + +continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise<void> + +Continues a mission on a remote device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | --------------------------------------- | ---- | ----- | +| parameter | [ContinueDeviceInfo](#continuedeviceinfo) | Yes | Parameters required for mission continuation.| +| options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + var parameter = { + srcDeviceId: "", + dstDeviceId: "", + missionId: 1, + wantParam: {"key": "value"} + }; + function OnContinueDone(resultCode) { + console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + }; + var options = { + OnContinueDone: OnContinueDone }; - distributedMissionManager.stopSyncRemoteMissions(parameter) - .then(data => { - console.info('success data is ' + data); - }).catch(error => { - console.info('error error is ' + error); - }) + try { + distributedMissionManager.continueMission(parameter, options) + .then(data => { + console.info('continueMission finished, ' + JSON.stringify(data)); + }).catch(error => { + console.error('continueMission failed, cause: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error('continueMission failed, cause: ' + JSON.stringify(error)) + } ``` ## MissionCallback @@ -349,3 +488,30 @@ Defines the parameters required for registering a listener. | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | | deviceId | string | Yes | Yes | Device ID.| + +## ContinueDeviceInfo + +Defines the parameters required for mission continuation. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| srcDeviceId | string | Yes | Yes | ID of the source device.| +| dstDeviceId | string | Yes | Yes | ID of the target device.| +| missionId | number | Yes | Yes | Mission ID.| +| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.| + +## ContinueCallback + +Defines the callback invoked when the mission continuation is complete. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| --------------------- | -------- | ---- | ---- | ------------------ | +| onContinueDone | function | Yes | No | Callback used to notify the user that the mission continuation is complete and return the continuation result. | diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md new file mode 100644 index 0000000000000000000000000000000000000000..743e17c77f8dd2c4baa48f90de3ff9ac47fedfc0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -0,0 +1,735 @@ +# User File Access and Management + +The **fileAccess** module is a framework for accessing and operating user files based on the extension mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of unified file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. + +>**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 provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by FilePicker and the file manager app. + +## Modules to Import + +```js +import fileAccess from '@ohos.data.fileAccess'; +``` + +## fileAccess.getFileAccessAbilityInfo + +getFileAccessAbilityInfo( ) : Promise<Array<Want>> + +Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +None + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<Array<Want>> | Promise used to return the want information obtained.| + +**Example** + + ```js + async getFileAccessAbilityInfo() { + let wantInfos = []; + try { + wantInfos = await fileAccess.getFileAccessAbilityInfo(); + console.log("getFileAccessAbilityInfo data " + JSON.stringify(wantInfos)); + } catch (error) { + console.error("getFileAccessAbilityInfo failed, error " + error); + } + } + ``` + +## fileAccess.createFileAccessHelper + +createFileAccessHelper(context: Context, wants: Array<Want>) : FileAccessHelper + +Synchronously creates a **Helper** object to connect to the specified wants. The **Helper** object provides file access and management capabilities. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| context | Context | Yes| Context of the ability.| +| wants | Array<Want> | Yes| Wants to connect.| + +**Return value** + +| Type| Description| +| --- | -- | +| FileAccessHelper | **Helper** object created.| + +**Example** + + ```js + createFileAccessHelper() { + let fileAccesssHelper = null; + // Obtain want information by using getFileAccessAbilityInfo(). + // Create a Helper object to interact with the media library service only. + let wantInfos = [ + { + "bundleName": "com.ohos.medialibrary.medialibrarydata", + "abilityName": "FileExtensionAbility", + }, + ] + try { + fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); + if (!fileAccesssHelper) + console.error("createFileAccessHelper interface returns an undefined object"); + } catch (error) { + console.error("createFileAccessHelper failed, error " + error); + } + } + ``` + +## fileAccess.createFileAccessHelper + +createFileAccessHelper(context: Context) : FileAccessHelper + +Synchronously creates a **Helper** object that connects to all file management services in the current system. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| context | Context | Yes| Context of the ability.| + +**Return value** + +| Type| Description| +| --- | -- | +| FileAccessHelper | **Helper** object created.| + +**Example** + + ```js + createFileAccessHelper() { + let fileAccesssHelperAllServer = null; + // Create a Helper object to interact with all file management services configured with fileAccess in the system. + try { + fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context); + if (!fileAccesssHelperAllServer) + console.error("createFileAccessHelper interface returns an undefined object"); + } catch (error) { + console.error("createFileAccessHelper failed, error " + error); + } + } + ``` + +## FileAccessHelper.getRoots + +getRoots( ) : Promise<RootIterator> + +Obtains information about the root nodes for the devices of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which +returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +None + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<RootIterator> | **RootIterator** object obtained.| + +**Example** + + ```js + async getRoots() { + let rootIterator = null; + let rootinfos = []; + let isDone = false; + try { + rootIterator = await fileAccesssHelper.getRoots(); + if (!rootIterator) { + console.error("getRoots interface returns an undefined object"); + return; + } + while (!isDone) { + let result = rootIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + rootinfos.push(result.value); + } + } catch (error) { + console.error("getRoots failed, error " + error); + } + } + ``` + +## RootInfo.listfile + +listFile(filter?: Filter) : FileIterator + +Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the root node of a device. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | + + +**Return value** + +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| + +**Example** + + ```js + / / Obtain root information by using getRoots(). + // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; + let rootInfo = rootinfos[0]; + let fileInfos = []; + let isDone = false; + try { + let fileIterator = rootInfo.listFile(); + // ListFile that contains the filter implementation. + // let fileIterator = rootInfo.listFile(filter); + if (!fileIterator) { + console.error("listFile interface returns an undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + fileInfos.push(result.value); + } + } catch (error) { + console.log("listFile failed, error " + error); + } + ``` + +## RootInfo.scanFile + +scanFile(filter?: Filter) : FileIterator + +Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the root node of a device synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using the [next()](#fileiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | + +**Return value** + +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| + +**Example** + + ```js + / / Obtain root information by using getRoots(). + // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; + let rootInfo = rootinfos[0]; + let fileInfos = []; + let isDone = false; + try { + let fileIterator = rootInfo.scanFile(); + // ScanFile that contains the filter implementation + // let fileIterator = rootInfo.scanFile(filter); + if (!fileIterator) { + console.error("scanFile interface returns undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + fileInfos.push(result.value); + } + } catch (error) { + console.error("scanFile failed, error " + error); + } + ``` + +## FileInfo.listfile + +listFile(filter?: Filter) : FileIterator + +Synchronously obtains the **FileIterator** object of the next-level files (file folders) matching the conditions of the filter from a directory. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | + +**Return value** + +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| + +**Example** + + ```js + // fileInfoDir specifies the target directory. + // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; + let fileInfoDir = fileInfos[0]; + let subfileInfos = []; + let isDone = false; + try { + let fileIterator = fileInfoDir.listFile(); + // ListFile that contains the filter implementation. + // let fileIterator = rootInfo.listFile(filter); + if (!fileIterator) { + console.error("listFile interface returns an undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + subfileInfos.push(result.value); + } + } catch (error) { + console.error("listFile failed, error " + error); + } + ``` + +## FileInfo.scanfile + +scanFile(filter?: Filter) : FileIterator; + +Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from a directory synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | -- | -- | +| filter | Filter | No| **Filter** object. | + + +**Return value** + +| Type| Description| +| --- | -- | +| FileIterator | **FileIterator** object obtained.| + +**Example** + + ```js + // fileInfoDir specifies the target directory. + // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; + let fileInfoDir = fileInfos[0]; + let subfileInfos = []; + let isDone = false; + try { + let fileIterator = fileInfoDir.scanFile(); + // ScanFile that contains the filter implementation + // let fileIterator = rootInfo.scanFile(filter); + if (!fileIterator) { + console.error("scanFile interface returns an undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.error("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + subfileInfos.push(result.value); + } + } catch (error) { + console.error("scanFile-filter failed, error " + error); + } + ``` + +## FileAccessHelper.createFile + +createFile(uri: string, displayName: string) : Promise<string> + +Creates a file in a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the parent directory for the file to create.| +| displayName | string | Yes| Name of the file to create. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<string> | URI of the file created.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + let displayName = "file1" + let fileUri = null; + try { + fileUri = await fileAccessHelper.createFile(sourceUri, displayName) + if (!fileUri) { + console.error("createFile return undefined object"); + return; + } + console.log("File created successfully. fileUri: " + JSON.stringify(fileUri)); + } catch (error) { + console.error("createFile failed, error " + error); + }; + ``` + +## FileAccessHelper.mkDir + +mkDir(parentUri: string, displayName: string) : Promise<string> + +Creates a folder in a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| parentUri | string | Yes| URI of the parent directory for the folder to create.| +| displayName | string | Yes| Name of the folder to create.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<string> | URI of the folder created.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + let dirName = "dirTest" + let dirUri = null; + try { + dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) + if (!dirUri) { + console.error("mkDir return undefined object"); + return; + } + console.log("Folder created successfully. dirUri: " + JSON.stringify(dirUri)); + } catch (error) { + console.error("mkDir failed, error " + error); + }; + ``` + +## FileAccessHelper.openFile + +openFile(uri: string, flags: [OPENFLAGS](#openflags)) : Promise<number> + +Opens a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file to open.| +| flags | OPENFLAGS | |File open mode.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<number> | Handle of the file opened.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + try { + let fd = await fileAccessHelper.openFile(targetUri, OPENFLAGS.READ); + } cache (error) { + console.error("openFile failed, error " + error); + }; + ``` + +## FileAccessHelper.delete + +delete(uri: string) : Promise<number> + +Deletes a file or folder. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or folder to delete.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<number> | Promise used to return the result.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + try { + let code = await fileAccessHelper.delete(targetUri); + if (code != 0) + console.error("delete failed, code " + code); + } cache (error) { + console.error("delete failed, error " + error); + }; + ``` + +## FileAccessHelper.move + +move(sourceFile: string, destFile: string) : Promise<string> + +Moves a file or folder. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFile | string | Yes| URI of the file or folder to move.| +| destFile | string | Yes| URI of the folder to which the file or folder is moved.| + +**Return value** + +| Type| Description| +| ----- | ------ | +| Promise<string> | URI of the file or folder in the destination directory.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let sourceFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + let destFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + try { + let fileUri = await fileAccessHelper.move(sourceFile, destFile); + console.log("Operation successful. fileUri: " + JSON.stringify(fileUri)); + } cache (error) { + console.error("move failed, error " + error); + }; + ``` + +## FileAccessHelper.rename + +rename(uri: string, displayName: string) : Promise<string> + +Renames a file or folder. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| uri | string | Yes| URI of the file or folder to rename.| +| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<string> | URI of the renamed file or folder.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + try { + let DestDir = await fileAccessHelper.rename(sourceDir, "testDir"); + console.log("Operation successful. DestDir: " + JSON.stringify(DestDir)); + } cache (error) { + console.error("rename failed, error " + error); + }; + ``` + +## FileAccessHelper.access + +access(sourceFileUri: string) : Promise<boolean> + +Checks whether a file or folder exists. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +| Name| Type| Mandatory| Description| +| --- | --- | --- | -- | +| sourceFileUri | string | Yes| URI of the file or folder.| + +**Return value** + +| Type| Description| +| --- | -- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + + ```js + // The URI of a shared disk is used as an example. + let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + try { + let existJudgment = await fileAccessHelper.access(sourceDir); + if (existJudgment) + console.log("sourceDir exists"); + else + console.log("sourceDir does not exist"); + } cache (error) { + console.error("rename failed, error " + error); + }; + ``` + +## RootIterator.next + +next( ) : { value: RootInfo, done: boolean } + +Obtains the next-level device root directory. **RootIterator** is an iterator object of the device root directory. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +None + +**Return value** + +| Type| Description| +| --- | -- | +| {value: RootInfo, done: boolean} | Root directory information obtained. This API traverses the folder until **done** returns **true**. The **value** field contains the root directory information.| + +## FileIterator.next + +next( ) : { value: FileInfo, done: boolean } + +Obtains the information about the next-level file or folder. **FileIterator** is an iterator object of a folder. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +**Parameters** + +None + +**Return value** + +| Type| Description| +| --- | -- | +| {value: FileInfo, done: boolean} | File or folder information obtained. This API traverses the specified folder until **done** returns **true**. The **value** field contains the file or folder information obtained.| + +## RootInfo + +Represents the root attribute information and interface capabilities of a device. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +### Attributes + +| Name| Type | Readable| Writable| Description | +| ------ | ------ | -------- | ------ | -------- | +| deviceType | number | Yes| No|Device type.| +| uri | string | Yes| No| Root directory URI of the device.| +| displayName | string | Yes| No| Device name.| +| deviceFlags | number | Yes| No| Capabilities supported by the device.| + +## FileInfo + +Represents the file or folder attribute information and interface capabilities. + +**System capability**: SystemCapability.FileManagement.UserFileService + +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER + +### Attributes + +| Name| Type | Readable| Writable| Description | +| ------ | ------ | -------- | ------ | -------- | +| uri | string | Yes| No| URI of the file or folder.| +| fileName | string | Yes| No| Name of a file or folder.| +| mode | number | Yes| No| Permissions on the file or folder.| +| size | number | Yes| No| Size of the file or folder.| +| mtime | number | Yes| No| Time when the file or folder was last modified.| +| mimeType | string | Yes| No| Media resource type of the file or folder.| + +## OPENFLAGS + +Enumerates the modes for opening a file. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name| Value| Description| +| ----- | ------ | ------ | +| READ | 0o0 | Read mode.| +| WRITE | 0o1 | Write mode.| +| WRITE_READ | 0o2 | Read/Write mode.| diff --git a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..fce0a93c72553be6306910412404e2fe09bc2290 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -0,0 +1,58 @@ +# User File Extension Info + +The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileInfo** of the user file access and management module. + +>**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 provided by this module are system APIs. + +## Modules to Import + +```js +import fileExtensionInfo from '@ohos.fileExtensionInfo'; +``` + +## fileExtensionInfo.DeviceType + +Defines the values of **deviceType** used in **RootInfo**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +| Name| Value| Description| +| ----- | ------ | ------ | +| DEVICE_LOCAL_DISK | 1 | Local disk.| +| DEVICE_SHARED_DISK | 2 | Shared disk.| +| DEVICE_SHARED_TERMINAL | 3 | Distributed network device.| +| DEVICE_NETWORK_NEIGHBORHOODS | 4 | Network neighbor device.| +| DEVICE_EXTERNAL_MTP | 5 | MTP device.| +| DEVICE_EXTERNAL_USB | 6 | USB device.| +| DEVICE_EXTERNAL_CLOUD | 7 | Cloud disk.| + +## fileExtensionInfo.DeviceFlag + +Defines the values of **deviceFlags** used in **RootInfo**. **deviceFlags** is used to determine whether a capability is available through the AND operation. + +**System capability**: SystemCapability.FileManagement.UserFileService + +### Attributes + + | Name| Type | Value| Readable| Writable| Description | + | ------ | ------ | ---- | ---- | ---- | -------- | + | SUPPORTS_READ | number | 0b1 | Yes | No | Read support.| + | SUPPORTS_WRITE | number | 0b10 | Yes | No | Write support.| + +## fileExtensionInfo.DocumentFlag + +Defines the values of **mode** used in **FileInfo**. + +**System capability**: SystemCapability.FileManagement.UserFileService + +### Attributes + + | Name| Type | Value| Readable| Writable| Description | + | ------ | ------ | ---- | ---- | ---- | -------- | + | REPRESENTS_FILE | number | 0b1 | Yes | No | File.| + | REPRESENTS_DIR | number | 0b10 | Yes | No | Directory.| + | SUPPORTS_READ | number | 0b100 | Yes | No | Read support.| + | SUPPORTS_WRITE | number | 0b1000 | Yes | No | Write support.| diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 8c85faa1eee7abbbc888e11cd5c12f2a308905c7..373fbf8faee9549ab17b5fbe462997f8cb3eaa30 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -38,12 +38,16 @@ This is a system API. **Example** ``` -let keyOptions = {preKeys: [], finalKey: 3, isFinalKeyDown: true, finalKeyDownDuration: 0} -let callback = function(keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 } +let callback = function (keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +} +try { + inputConsumer.on(inputConsumer.SubscribeType.KEY, keyOptions, callback); +} catch (error) { + console.info(`inputConsumer.on, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); } -inputConsumer.on('key', keyOptions, callback); ``` @@ -68,12 +72,16 @@ This is a system API. **Example** ``` -let keyOptions = {preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0} -let callback = function(keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 } +let callback = function (keyOptions) { + console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, + "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) +} +try { + inputConsumer.off(inputConsumer.SubscribeType.KEY, keyOptions, callback); +} catch (error) { + console.info(`inputConsumer.off, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); } -inputConsumer.off('key', keyOptions, callback); ``` diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 2f4986f90f431852a7b2e76d8f58e24ba8469ed9..f5cf9b1af9502462bd906302bee23fcff28780b4 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -15,6 +15,130 @@ The Input Device module implements listening for connection, disconnection, and ```js import inputDevice from '@ohos.multimodalInput.inputDevice'; ``` +## inputDevice.getDeviceList9+ + +getDeviceList(callback: AsyncCallback<Array<number>>): void + +Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | ---------- | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + inputDevice.getDeviceList((error, ids) => { + if (error) { + console.log(`Failed to get device list. + error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + return; + } + this.data = ids; + console.log("The device ID list is: " + ids); + }); +} catch (error) { + console.info("getDeviceList " + error.code + " " + error.message); +} +``` + +## inputDevice.getDeviceList9+ + +getDeviceList(): Promise<Array<number>> + +Obtains the IDs of all input devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Return value** + +| Name | Description | +| ---------------------------------- | ------------------------------- | +| Promise<Array<number>> | Promise used to return the result.| + +**Example** + +```js +try { + inputDevice.getDeviceList().then((ids) => { + console.log("The device ID list is: " + ids); + }); +} catch (error) { + console.info("getDeviceList " + error.code + " " + error.message); +} +``` + +## inputDevice.getDeviceInfo9+ + +getDeviceInfo(deviceId: number, callback: AsyncCallback<InputDeviceData>): void + +Obtains information about an input device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------------- | ---- | --------------------------------------- | +| deviceId | number | Yes | ID of the input device. | +| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | Yes | Callback used to return the result, which is an **InputDeviceData** object.| + +**Example** + +```js +// Obtain the name of the device whose ID is 1. +try { + inputDevice.getDeviceInfo(1, (error, inputDevice) => { + if (error) { + console.log(`Failed to get device information. + error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + return; + } + console.log("The device name is: " + inputDevice.name); + }); +} catch (error) { + console.info("getDeviceInfo " + error.code + " " + error.message); +} +``` + +## inputDevice.getDeviceInfo9+ + +getDeviceInfo(deviceId: number): Promise<InputDeviceData> + +Obtains information about an input device. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| deviceId | number | Yes | ID of the input device.| + +**Return value** + +| Name | Description | +| -------------------------------------------------- | ------------------------------- | +| Promise<[InputDeviceData](#inputdevicedata)> | Promise used to return the result.| + +**Example** + +```js +// Obtain the name of the device whose ID is 1. +try { + inputDevice.getDeviceInfo(id).then((inputDevice) => { + console.log("The device name is: " + inputDevice.name); + }); +} catch (error) { + console.info("getDeviceInfo " + error.code + " " + error.message); +} +``` + ## inputDevice.on9+ @@ -35,20 +159,24 @@ Enables listening for hot swap events of an input device. ```js let isPhysicalKeyboardExist = true; -inputDevice.on("change", (data) => { +try { + inputDevice.on("change", (data) => { console.log("type: " + data.type + ", deviceId: " + data.deviceId); inputDevice.getKeyboardType(data.deviceId, (err, ret) => { - console.log("The keyboard type of the device is: " + ret); - if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { - // The physical keyboard is connected. - isPhysicalKeyboardExist = true; - } else if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { - // The physical keyboard is disconnected. - isPhysicalKeyboardExist = false; - } + console.log("The keyboard type of the device is: " + ret); + if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { + // The physical keyboard is connected. + isPhysicalKeyboardExist = true; + } else if (ret == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { + // The physical keyboard is disconnected. + isPhysicalKeyboardExist = false; + } }); -}); -// Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist. + }); + // Check whether the soft keyboard is open based on the value of isPhysicalKeyboardExist. +} catch (error) { + console.info("oninputdevcie " + error.code + " " + error.message); +} ``` ## inputDevice.off9+ @@ -69,24 +197,43 @@ Disables listening for hot swap events of an input device. **Example** ```js -function listener(data) { - console.log("type: " + data.type + ", deviceId: " + data.deviceId); +callback: function(data) { + console.log("type: " + data.type + ", deviceId: " + data.deviceId); } +try { + inputDevice.on("change", this.callback); +} catch (error) { + console.info("oninputdevcie " + error.code + " " + error.message) +} + +// Enable listening for hot swap events of an input device. +inputDevice.on("change", listener); + // Disable this listener. -inputDevice.off("change", listener); +try { + inputDevice.off("change", this.callback); +} catch (error) { + console.info("offinputdevcie " + error.code + " " + error.message) +} // Disable all listeners. -inputDevice.off("change"); +try { + inputDevice.off("change"); +} catch (error) { + console.info("offinputdevcie " + error.code + " " + error.message); +} // By default, the soft keyboard is closed when listening is disabled. ``` -## inputDevice.getDeviceIds +## inputDevice.getDeviceIds(deprecated) getDeviceIds(callback: AsyncCallback<Array<number>>): void Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result. +This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceList](#inputdevicegetdevicelist9) instead. + **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Parameters** @@ -103,12 +250,14 @@ inputDevice.getDeviceIds((ids)=>{ }); ``` -## inputDevice.getDeviceIds +## inputDevice.getDeviceIds(deprecated) getDeviceIds(): Promise<Array<number>> Obtains the IDs of all input devices. This API uses a promise to return the result. +This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceList](#inputdevicegetdevicelist9) instead. + **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Return value** @@ -125,12 +274,14 @@ inputDevice.getDeviceIds().then((ids)=>{ }); ``` -## inputDevice.getDevice +## inputDevice.getDevice(deprecated) getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void Obtains information about an input device. This API uses an asynchronous callback to return the result. +This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9) instead. + **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Parameters** @@ -149,12 +300,14 @@ inputDevice.getDevice(1, (inputDevice)=>{ }); ``` -## inputDevice.getDevice +## inputDevice.getDevice(deprecated) getDevice(deviceId: number): Promise<InputDeviceData> Obtains information about an input device. This API uses a promise to return the result. +This API is deprecated since API version 9. You are advised to use [inputDevice.getDeviceInfo](#inputdevicegetdeviceinfo9) instead. + **System capability**: SystemCapability.MultimodalInput.Input.InputDevice **Parameters** @@ -198,9 +351,13 @@ Obtains the key codes supported by the input device. This API uses an asynchrono ```js // Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055. -inputDevice.supportKeys(1, [17, 22, 2055], (ret)=>{ +try { + inputDevice.supportKeys(1, [17, 22, 2055], (error, ret) => { console.log("The query result is as follows: " + ret); -}); + }); +} catch (error) { + console.info("supportKeys " + error.code + " " + error.message); +} ``` ## inputDevice.supportKeys9+ @@ -228,9 +385,13 @@ Obtains the key codes supported by the input device. This API uses a promise to ```js // Check whether the input device whose ID is 1 supports key codes 17, 22, and 2055. -inputDevice.supportKeys(1, [17, 22, 2055]).then((ret)=>{ +try { + inputDevice.supportKeys(1, [17, 22, 2055]).then((ret) => { console.log("The query result is as follows: " + ret); -}) + }); +} catch (error) { + console.info("supportKeys " + error.code + " " + error.message); +} ``` ## inputDevice.getKeyboardType9+ @@ -252,9 +413,18 @@ Obtains the keyboard type of an input device. This API uses an asynchronous call ```js // Query the keyboard type of the input device whose ID is 1. -inputDevice.getKeyboardType(1, (ret)=>{ - console.log("The keyboard type of the device is: " + ret); -}); +try { + inputDevice.getKeyboardType(1, (error, number) => { + if (error) { + console.log(`Failed to get keyboardtype. + error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + return; + } + console.log("The keyboard type of the device is: " + number); + }); +} catch (error) { + console.info("getKeyboardType " + error.code + " " + error.message); +} ``` ## inputDevice.getKeyboardType9+ @@ -275,14 +445,18 @@ Obtains the keyboard type of an input device. This API uses a promise to return ```js // Query the keyboard type of the input device whose ID is 1. -inputDevice.getKeyboardType(1).then((ret)=>{ - console.log("The keyboard type of the device is: " + ret); -}) +try { + inputDevice.getKeyboardType(1).then((number) => { + console.log("The keyboard type of the device is: " + number); + }); +} catch (error) { + console.info("getKeyboardType " + error.code + " " + error.message); +} ``` ## DeviceListener9+ -Defines the information about an input device. +Defines the listener for hot swap events of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index c38734f143bed4fd8288df7672d721caf4696025..695a7a5bf4b611270ff32acb8aab17cc6f802aa3 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -36,13 +36,24 @@ This is a system API. **Example** ```js -let keyEvent = { +try { + var keyEvent = { isPressed: true, keyCode: 2, keyDownDuration: 0, isIntercepted: false + } + inputEventClient.injectKeyEvent({ KeyEvent: keyEvent }); + var keyEvent1 = { + isPressed: false, + keyCode: 2, + keyDownDuration: 0, + isIntercepted: false + }; + inputEventClient.injectKeyEvent({ KeyEvent: keyEvent1 }); +} catch (error) { + console.info("injectKeyEvent " + error.code + " " + error.message); } -let res = inputEventClient.injectEvent({KeyEvent: keyEvent}); ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 9fdcb88e96a336e19a87efab9c9856af746df558..315e2d81f718bff6f6f1bc9b0ce813df11850da5 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -43,10 +43,14 @@ This is a system API. **Example** ```js -inputMonitor.off("touch", (event) => { - // A touch event is consumed. - return false; -}); +try { + inputMonitor.on("touch", (data)=> { + console.info(`monitorOnTouchEvent success ${JSON.stringify(data)}`); + return false; + }); +} catch (error) { + console.info("onMonitor " + error.code + " " + error.message) +} ``` on(type: "mouse", receiver: Callback<MouseEvent>): void @@ -69,13 +73,16 @@ This is a system API. **Example** ```js -inputMonitor.off("mouse", (event) => { - // A mouse event is consumed. -}); +try { + inputMonitor.on("mouse", (data)=> { + console.info(`monitorOnMouseEvent success ${JSON.stringify(data)}`); + return false; + }); +} catch (error) { + console.info("onMonitor " + error.code + " " + error.message) +} ``` - - ## inputMonitor.off off(type: "touch", receiver?: TouchEventReceiver): void @@ -98,7 +105,26 @@ This is a system API. **Example** ```js -inputMonitor.off("touch"); +// Disable listening globally. +try { + inputMonitor.off("touch"); +} catch (error) { + console.info("offMonitor " + error.code + " " + error.message) +} +// Disable listening for this receiver. +callback:function(data) { + console.info(`call success ${JSON.stringify(data)}`); +}, +try { + inputMonitor.on("touch", this.callback); +} catch (error) { + console.info("onTouchMonitor " + error.code + " " + error.message) +}, +try { + inputMonitor.off("touch",this.callback); +} catch (error) { + console.info("offTouchMonitor " + error.code + " " + error.message) +} ``` off(type: "mouse", receiver?:Callback\):void @@ -121,7 +147,26 @@ This is a system API. **Example** ```js -inputMonitor.off("mouse"); +// Disable listening globally. +try { + inputMonitor.off("mouse"); +} catch (error) { + console.info("offMonitor " + error.code + " " + error.message) +} +// Disable listening for this receiver. +callback:function(data) { + console.info(`call success ${JSON.stringify(data)}`); +}, +try { + inputMonitor.on("mouse", this.callback); +} catch (error) { + console.info("onMouseMonitor " + error.code + " " + error.message) +}, +try { + inputMonitor.off("mouse", this.callback); +} catch (error) { + console.info("offMouseMonitor " + error.code + " " + error.message) +} ``` @@ -149,9 +194,13 @@ This is a system API. **Example** ```js -inputMonitor.on("touch", (event) => { - // A touch event is consumed. - return false; -}); -inputMonitor.off("touch"); +try { + inputMonitor.on("touch", (event) => { + // If true is returned, all subsequent events of this operation will be consumed by the listener, instead of being distributed to the window. + return false; + }); + inputMonitor.off("touch"); +} catch (error) { + console.info("offMonitor " + error.code + " " + error.message) +} ``` diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index b29a380a5b1b2e8afb4d41687a659dc29db4344c..8c4dd734fbdbe5d2a3d2bbd621f04f54ed20d883 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,7 +1,6 @@ # Media > **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 multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. @@ -53,7 +52,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance, which can be used to manage and play video media.| +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| **Example** @@ -80,9 +79,9 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result **Return value** -| Type | Description | -| ------------------------------------- | ----------------------------------- | -| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance, which can be used to manage and play video media.| +| Type | Description | +| ------------------------------------- | ------------------------------------------------------------ | +| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| **Example** @@ -112,9 +111,9 @@ Only one **AudioRecorder** instance can be created per device. **Return value** -| Type | Description | -| ------------------------------- | ----------------------------------------- | -| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio media.| **Example** @@ -135,7 +134,7 @@ Only one **AudioRecorder** instance can be created per device. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance, which can be used to record video media.| +| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| **Example** @@ -163,9 +162,9 @@ Only one **AudioRecorder** instance can be created per device. **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------- | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance, which can be used to record video media.| +| Type | Description | +| ----------------------------------------- | ------------------------------------------------------------ | +| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| **Example** @@ -263,7 +262,7 @@ Enumerates the buffering event types. | BUFFERING_START | 1 | Buffering starts. | | BUFFERING_END | 2 | Buffering ends. | | BUFFERING_PERCENT | 3 | Buffering progress, in percent. | -| CACHED_DURATION | 4 | Cache duration, in milliseconds.| +| CACHED_DURATION | 4 | Cache duration, in ms.| ## AudioPlayer @@ -362,9 +361,9 @@ Seeks to the specified playback position. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------ | -| timeMs | number | Yes | Position to seek to, in milliseconds.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------------- | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| **Example** @@ -427,9 +426,9 @@ Obtains the audio track information. This API uses an asynchronous callback to r **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the audio track information obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return a **MediaDescription** array, which records the audio track information.| **Example** @@ -463,9 +462,9 @@ Obtains the audio track information. This API uses a promise to return the resul **Return value** -| Type | Description | -| ------------------------------------------------------ | ------------------------------- | -| Promise> | Promise used to return the audio track information obtained.| +| Type | Description | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | Promise used to return a **MediaDescription** array, which records the audio track information.| **Example** @@ -497,7 +496,7 @@ for (let i = 0; i < arrayDescription.length; i++) { on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -Subscribes to the audio buffering update event. +Subscribes to the audio buffering update event. Only network playback supports this subscription. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -594,7 +593,7 @@ audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' e on(type: 'timeUpdate', callback: Callback\): void -Subscribes to the **'timeUpdate'** event. +Subscribes to the **'timeUpdate'** event. This event is reported every second when the audio playback is in progress. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -1014,10 +1013,10 @@ Seeks to the specified playback position. The next key frame at the specified po **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------ | -| timeMs | number | Yes | Position to seek to, in milliseconds.| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| callback | function | Yes | Callback used to return the result. | **Example** @@ -1042,11 +1041,11 @@ Seeks to the specified playback position. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------ | -| timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | +| callback | function | Yes | Callback used to return the result. | **Example** @@ -1072,16 +1071,16 @@ Seeks to the specified playback position. If **mode** is not specified, the next **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------- | ---- | ------------------------------------ | -| timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | No | Seek mode. | +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| mode | [SeekMode](#seekmode8) | No | Seek mode. | **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------------------------------------- | +| Promise\ | Promise used to return the playback position, in ms.| **Example** @@ -1220,9 +1219,9 @@ Obtains the video track information. This API uses an asynchronous callback to r **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the video track information obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return a **MediaDescription** array, which records the video track information.| **Example** @@ -1256,9 +1255,9 @@ Obtains the video track information. This API uses a promise to return the resul **Return value** -| Type | Description | -| ------------------------------------------------------ | ------------------------------- | -| Promise> | Promise used to return the video track information obtained.| +| Type | Description | +| ------------------------------------------------------ | ----------------------------------------------- | +| Promise> | Promise used to return a **MediaDescription** array, which records the video track information.| **Example** @@ -1332,9 +1331,9 @@ Sets the video playback speed. 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 playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| **Example** @@ -1389,13 +1388,13 @@ Selects a bit rate from available ones, which can be obtained by calling [availa | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------------------- | -| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s.| +| bitrate | number | Yes | Bit rate, which is used in the HLS multi-bit rate scenario. The unit is bit/s.| **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ---------------- | --------------------------- | +| Promise\ | Promise used to return the bit rate.| **Example** @@ -1435,7 +1434,7 @@ videoPlayer.on('playbackCompleted', () => { on(type: 'bufferingUpdate', callback: (infoType: BufferingInfoType, value: number) => void): void -Subscribes to the video buffering update event. +Subscribes to the video buffering update event. Only network playback supports this subscription. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index da2443a7c87c363ae79085a9b0dfeda4f7f5af99..31414ab325572d7ed25a31b1b3a78a725dce39e6 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -16,7 +16,7 @@ import connection from '@ohos.net.connection' getDefaultNet(callback: AsyncCallback\): void -Obtains the default active data network. This API uses an asynchronous callback to return the result. +Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -41,7 +41,7 @@ connection.getDefaultNet(function (error, netHandle) { getDefaultNet(): Promise\ -Obtains the default active data network. This API uses a promise to return the result. +Obtains the default active data network. This API uses a promise to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -65,7 +65,7 @@ connection.getDefaultNet().then(function (netHandle) { getDefaultNetSync(): NetHandle; -Obtains the default active data network in synchronous mode. +Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -88,8 +88,7 @@ let netHandle = connection.getDefaultNetSync(); hasDefaultNet(callback: AsyncCallback\): void -Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. -The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. +Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -114,8 +113,7 @@ connection.hasDefaultNet(function (error, has) { hasDefaultNet(): Promise\ -Checks whether the default data network is activated. This API uses a promise to return the result. -The default network priority is as follows: Ethernet > Wi-Fi > cellular. When only one network is connected, it is treated as the default data network. +Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -311,6 +309,8 @@ reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): v Reports connection of the data network. This API uses an asynchronous callback to return the result. +If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. + **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetManager.Core @@ -339,6 +339,8 @@ reportNetConnected(netHandle: NetHandle): Promise<void> Reports connection of the data network. This API uses a promise to return the result. +If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. + **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetManager.Core @@ -353,7 +355,7 @@ Reports connection of the data network. This API uses a promise to return the re | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -372,6 +374,8 @@ reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>) Reports disconnection of the data network. This API uses an asynchronous callback to return the result. +If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. + **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetManager.Core @@ -400,6 +404,8 @@ reportNetDisconnected(netHandle: NetHandle): Promise<void> Reports disconnection of the data network. This API uses a promise to return the result. +If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. + **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetManager.Core @@ -414,7 +420,7 @@ Reports disconnection of the data network. This API uses a promise to return the | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -523,7 +529,7 @@ This is a system API. | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -572,7 +578,7 @@ This is a system API. | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -890,7 +896,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses | Type | Description | | -------------- | ---------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 97429f0dee1df4f12487cce5d361182ba660fe87..ea2d452000bb542e55232a29456d3811fd24526c 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -12,7 +12,7 @@ The mouse pointer module provides APIs related to pointer attribute management. import pointer from '@ohos.multimodalInput.pointer'; ``` -## pointer.setPointerVisibele +## pointer.setPointerVisible9+ setPointerVisible(visible: boolean, callback: AsyncCallback<void>): void @@ -22,24 +22,28 @@ Sets the visible status of the mouse pointer. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------------- | -| visible | boolean | Yes | Whether the mouse pointer is visible. The value **true** indicates that the mouse pointer is visible, and the value **false** indicates the opposite.| -| callback | AysncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------------------------------- | +| visible | boolean | Yes | Whether the mouse pointer is visible.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -pointer.setPointerVisible(true, (err, data) => { - if (err) { - console.log(`set pointer visible failed. err=${JSON.stringify(err)}`); - return; +try { + pointer.setPointerVisible(true, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; } - console.log(`set pointer visible success.`); -); + console.log(`Set pointer visible success`); + }); +} catch (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` -## pointer.setPointerVisible +## pointer.setPointerVisible9+ setPointerVisible(visible: boolean): Promise<void> @@ -49,66 +53,400 @@ Sets the visible status of the mouse pointer. This API uses a promise to return **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------------------------------------------------------------- | -| visible | boolean | Yes | Whether the mouse pointer is visible. The value **true** indicates that the mouse pointer is visible, and the value **false** indicates the opposite.| +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ---------------------------------------- | +| visible | boolean | Yes | Whether the mouse pointer is visible.| **Return value** -| Parameter | Description | -| ------------------- | ------------------------------- | +| Name | Description | +| ------------------- | ------------------- | | Promise<void> | Promise used to return the result.| **Example** ```js -pointer.setPointerVisible(false).then( data => { - console.log(`set mouse pointer visible success`); - }, data => { - console.log(`set mouse pointer visible failed err=${JSON.stringify(data)}`); -}); +try { + pointer.setPointerVisible(false).then(() => { + console.log(`Set pointer visible success`); + }); +} catch (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` -## pointer.isPointerVisible +## pointer.isPointerVisible9+ isPointerVisible(callback: AsyncCallback<boolean>): void -Checks the visible status of the mouse pointer. This API uses an asynchronous callback to return the result. +Checks the visible status of the mouse pointer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.Pointer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | -------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| **Example** ```js -pointer.isPointerVisible((visible)=>{ - console.log("The mouse pointer visible attributes is " + visible); -}); +try { + pointer.isPointerVisible((error, visible) => { + if (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); + }); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` -## pointer.isPointerVisible +## pointer.isPointerVisible9+ isPointerVisible(): Promise<boolean> -Checks the visible status of the mouse pointer. This API uses a promise to return the result. +Checks the visible status of the mouse pointer. This API uses a promise to return the result. **System capability**: SystemCapability.MultimodalInput.Input.Pointer **Return value** -| Parameter | Description | -| ---------------------- | ------------------------------- | +| Name | Description | +| ---------------------- | ------------------- | | Promise<boolean> | Promise used to return the result.| **Example** ```js -pointer.isPointerVisible().then( data => { - console.log(`isPointerThen success data=${JSON.stringify(data)}`); +pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); }); ``` + +## pointer.setPointerSpeed9+ + +setPointerSpeed(speed: number, callback: AsyncCallback<void>): void + +Sets the mouse movement speed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------------------- | +| speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**. | +| callback | AysncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.setPointerSpeed(5, (error) => { + if (error) { + console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer speed success`); + }); +} catch (error) { + console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.setPointerSpeed9+ + +setPointerSpeed(speed: number): Promise<void> + +Sets the mouse movement speed. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------------------------- | +| speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**.| + +**Return value** + +| Name | Description | +| ------------------- | ---------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.setPointerSpeed(5).then(() => { + console.log(`Set pointer speed success`); + }); +} catch (error) { + console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerSpeed9+ + +getPointerSpeed(callback: AsyncCallback<number>): void + +Obtains the mouse movement speed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + pointer.getPointerSpeed((error, speed) => { + if (error) { + console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Get pointer speed success, speed: ${JSON.stringify(speed)}`); + }); +} catch (error) { + console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerSpeed9+ + +getPointerSpeed(): Promise<number> + +Obtains the mouse movement speed. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Return value** + +| Name | Description | +| --------------------- | ------------------- | +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +try { + pointer.getPointerSpeed().then(speed => { + console.log(`Get pointer speed success, speed: ${JSON.stringify(speed)}`); + }); +} catch (error) { + console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## pointer.getPointerStyle9+ + +getPointerStyle(windowId: number, callback: AsyncCallback<PointerStyle>): void + +Obtains the mouse pointer style. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------- | +| windowId | number | Yes | Window ID. | +| callback | AsyncCallback<[PointerStyle](#pointerstyle9)> | Yes | Callback used to return the result.| + +**Example** + +```js +import window from '@ohos.window'; + +window.getTopWindow((error, win) => { + win.getProperties((error, properties) => { + var windowId = properties.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId, (error, style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); + }); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } + }); +}); +``` + +## pointer.getPointerStyle9+ + +getPointerStyle(windowId: number): Promise<PointerStyle> + +Obtains the mouse pointer style. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------- | +| windowId | number | Yes | Window ID.| + +**Return value** + +| Name | Description | +| ---------------------------------------- | ------------------- | +| Promise<[PointerStyle](#pointerstyle9)> | Promise used to return the result.| + +**Example** + +```js +import window from '@ohos.window'; + +window.getTopWindow((error, win) => { + win.getProperties((error, properties) => { + var windowId = properties.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.getPointerStyle(windowId).then((style) => { + console.log(`Get pointer style success, style: ${JSON.stringify(style)}`); + }); + } catch (error) { + console.log(`Get pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } + }); +}); +``` + +## pointer.setPointerStyle9+ + +setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback<void>): void + +Sets the mouse pointer style. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------------------------------ | ---- | ----------------------------------- | +| windowId | number | Yes | Window ID. | +| pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. | +| callback | AysncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +import window from '@ohos.window'; + +window.getTopWindow((error, win) => { + win.getProperties((error, properties) => { + var windowId = properties.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS, error => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } + }); +}); +``` +## pointer.setPointerStyle9+ + +setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise<void> + +Sets the mouse pointer style. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------------- | ------------------------------ | ---- | ---------------- | +| windowId | number | Yes | Window ID. | +| pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. | +| Promise<void> | void | Yes | Promise used to return the result.| + +**Example** + +```js +import window from '@ohos.window'; + +window.getTopWindow((error, win) => { + win.getProperties((error, properties) => { + var windowId = properties.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + pointer.setPointerStyle(windowId, pointer.PointerStyle.CROSS).then(() => { + console.log(`Set pointer style success`); + }); + } catch (error) { + console.log(`Set pointer style failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + } + }); +}); +``` +## PointerStyle9+ + +Enumerates mouse pointer styles. + +**System capability**: SystemCapability.MultimodalInput.Input.Pointer + +| Name | Value | Description | +| -------------------------------- | ---- | ------ | +| DEFAULT | 0 | Default | +| EAST | 1 | East arrow | +| WEST | 2 | West arrow | +| SOUTH | 3 | South arrow | +| NORTH | 4 | North arrow | +| WEST_EAST | 5 | West-east arrow | +| NORTH_SOUTH | 6 | North-south arrow | +| NORTH_EAST | 7 | North-east arrow | +| NORTH_WEST | 8 | North-west arrow | +| SOUTH_EAST | 9 | South-east arrow | +| SOUTH_WEST | 10 | South-west arrow | +| NORTH_EAST_SOUTH_WEST | 11 | North-east and south-west adjustment| +| NORTH_WEST_SOUTH_EAST | 12 | North-west and south-east adjustment| +| CROSS | 13 | Cross (accurate selection) | +| CURSOR_COPY | 14 | Copy cursor | +| CURSOR_FORBID | 15 | Forbid cursor | +| COLOR_SUCKER | 16 | Sucker | +| HAND_GRABBING | 17 | Grabbing hand | +| HAND_OPEN | 18 | Opening hand | +| HAND_POINTING | 19 | Hand-shaped pointer | +| HELP | 20 | Help | +| MOVE | 21 | Move | +| RESIZE_LEFT_RIGHT | 22 | Left and right resizing| +| RESIZE_UP_DOWN | 23 | Up and down resizing| +| SCREENSHOT_CHOOSE | 24 | Screenshot crosshair| +| SCREENSHOT_CURSOR | 25 | Screenshot cursor | +| TEXT_CURSOR | 26 | Text cursor | +| ZOOM_IN | 27 | Zoom in | +| ZOOM_OUT | 28 | Zoom out | +| MIDDLE_BTN_EAST | 29 | Scrolling east | +| MIDDLE_BTN_WEST | 30 | Scrolling west | +| MIDDLE_BTN_SOUTH | 31 | Scrolling south | +| MIDDLE_BTN_NORTH | 32 | Scrolling north | +| MIDDLE_BTN_NORTH_SOUTH | 33 | Scrolling north-south | +| MIDDLE_BTN_NORTH_EAST | 34 | Scrolling north-east | +| MIDDLE_BTN_NORTH_WEST | 35 | Scrolling north-west | +| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east | +| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west | +| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions| diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index e88c899e36745869e6009616b1c8581c3fa37b49..1fd0357783d6cf3ead6913cfc07a0e4b4e1c3c82 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -4,6 +4,8 @@ The **Prompt** module provides APIs for creating and showing toasts, dialog boxe > **NOTE** > +> The APIs of this module are deprecated since API Version 9. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead. +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -35,6 +37,8 @@ prompt.showToast({ }); ``` +![en-us_image_0001](figures/en-us_image_0001.gif) + ## ShowToastOptions Describes the options for showing the toast. @@ -43,9 +47,9 @@ Describes the options for showing the toast. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. | ## prompt.showDialog @@ -92,6 +96,8 @@ prompt.showDialog({ }) ``` +![en-us_image_0002](figures/en-us_image_0002.gif) + ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void @@ -132,6 +138,8 @@ prompt.showDialog({ }); ``` +![en-us_image_0004](figures/en-us_image_0004.gif) + ## ShowDialogOptions Describes the options for showing the dialog box. @@ -140,8 +148,8 @@ Describes the options for showing the dialog box. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Text body. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | | buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -170,7 +178,6 @@ Shows an action menu. This API uses a callback to return the result asynchronous | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | | callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| - **Example** ```js @@ -195,6 +202,8 @@ prompt.showActionMenu({ }) ``` +![en-us_image_0005](figures/en-us_image_0005.gif) + ## prompt.showActionMenu showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> @@ -238,6 +247,8 @@ prompt.showActionMenu({ console.info('showActionMenu error: ' + err); }) ``` +![en-us_image_0006](figures/en-us_image_0006.gif) + ## ActionMenuOptions Describes the options for showing the action menu. @@ -246,7 +257,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | | buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -267,5 +278,5 @@ Describes the menu item button in the action menu. | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Button text.| -| color | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md new file mode 100644 index 0000000000000000000000000000000000000000..268673b046bbb5f775dfffe3986105718319d009 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -0,0 +1,341 @@ +# Prompt + +The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import promptAction from '@ohos.promptAction' +``` + +## promptAction.showToast + +showToast(options: ShowToastOptions): void + +Shows a toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000, + }); +} catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); +}; + +``` + +![en-us_image_0001](figures/en-us_image_0001.gif) + +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ], + }) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void + +Shows a dialog box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ] + }, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }); +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| + +## ShowDialogSuccessResponse + +Describes the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Description | +| ----- | ------ | ------------------- | +| index | number | Index of the selected button in the **buttons** array.| + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## ActionMenuOptions + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| + +## ActionMenuSuccessResponse + +Describes the action menu response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------------------ | +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index ec920f58cab6825ce1dd286f42d1eb24e759f10b..ad01b50bc77d167a58eff666777c2d383cec8922 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1840,10 +1840,10 @@ Defines the network status. | Name | Value | Description | | ----------------------------- | ---- | -------------------------- | -| REG_STATE_NO_SERVICE | 0 | The device cannot use any service. | -| REG_STATE_IN_SERVICE | 1 | The device can use services normally. | -| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service.| -| REG_STATE_POWER_OFF | 3 | The cellular radio service is disabled. | +| REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. | +| REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. | +| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service. | +| REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. | ## NsaState diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2609d848a83392c8b0630015b2f135894fde0a61..27e794f1f636971f637b4cfe3bda4eff9fbb0852 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -14,108 +14,404 @@ The **Router** module provides APIs to access pages through URLs. You can use th import router from '@ohos.router' ``` -## router.push +## router.pushUrl9+ -push(options: RouterOptions): void +pushUrl(options: RouterOptions): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -}); + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.push9+ -push(options: RouterOptions, mode: RouterMode): void +## router.pushUrl9+ + +pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` +## router.pushUrl9+ + +pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -},router.RouterMode.Standard); + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.replace +## router.pushUrl9+ -replace(options: RouterOptions): void +pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void -Replaces the current page with another one in the application and destroys the current page. +Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail', - params: { - data1: 'message', - }, -}); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` - ## router.replace9+ +## router.replaceUrl9+ -replace(options: RouterOptions, mode: RouterMode): void +replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail/detail', - params: { - data1: 'message', - }, -}, router.RouterMode.Standard); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` ## router.back @@ -127,6 +423,7 @@ Returns to the previous page or a specified page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------------------------------------------------ | | options | [RouterOptions](#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.| @@ -160,11 +457,13 @@ Obtains the number of pages in the current stack. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Return value** + | Type | Description | | ------ | ------------------ | | string | Number of pages in the stack. The maximum value is **32**.| **Example** + ```js var size = router.getLength(); console.log('pages stack size = ' + size); @@ -205,25 +504,38 @@ Describes the page routing state. | name | string | Name of the current page, that is, the file name. | | path | string | Path of the current page. | -## router.enableAlertBeforeBackPage +## router.enableBackPageAlert9+ -enableAlertBeforeBackPage(options: EnableAlertOptions): void +enableBackPageAlert(options: EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | --------- | | options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + **Example** - ```js - router.enableAlertBeforeBackPage({ + ```js +try { + router.enableBackPageAlert({ message: 'Message Info' - }); + }); +} catch(error) { + console.error(`enableBackPageAlert failed, code is ${error.code}, message is ${error.message}`); +} ``` ## EnableAlertOptions @@ -244,6 +556,7 @@ Disables the display of a confirm dialog box before returning to the previous pa **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** + ```js router.disableAlertBeforeBackPage(); ``` @@ -274,10 +587,10 @@ Describes the page routing options. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| url | string | Yes | URI of the destination page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.| +| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| > **NOTE** @@ -291,7 +604,7 @@ Enumerates the routing modes. | Name | Description | | -------- | ---------------------------------------- | -| Standard | Standard mode. | +| Standard | Standard mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. | | Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.
If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.| ## Examples @@ -401,3 +714,144 @@ struct Second { } } ``` + +## router.push(deprecated) + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +}); +``` +## router.push(deprecated) + +push(options: RouterOptions, mode: RouterMode): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +},router.RouterMode.Standard); +``` + +## router.replace(deprecated) + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| + +**Example** + +```js +router.replace({ + url: 'pages/detail', + params: { + data1: 'message', + }, +}); +``` + + ## router.replace(deprecated) + +replace(options: RouterOptions, mode: RouterMode): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Example** + +```js +router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, +}, router.RouterMode.Standard); +``` + +## router.enableAlertBeforeBackPage(deprecated) + +enableAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +This API is deprecated since API version 9. You are advised to use [enableBackPageAlert9+](#routerenablebackpagealert9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------- | +| options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| + +**Example** + + ```js + router.enableAlertBeforeBackPage({ + message: 'Message Info' + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 6622b4b719e95f2c87af19653fbf8a89905239f2..a5515dadfbd141dc16bfa44b2edffea5013109f4 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -689,7 +689,7 @@ promise.then(data => { ## sim.**setShowName**8+ -setShowName\(slotId: number, name: string,callback: AsyncCallback\): void +setShowName\(slotId: number, name: string, callback: AsyncCallback\): void Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy **Example** ```js -let name = 'China Mobile'; +let name = "ShowName"; sim.setShowName(0, name, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom **Example** ```js -let name = 'China Mobile'; +let name = "ShowName"; let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); @@ -818,7 +818,7 @@ promise.then(data => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number, number: string,callback: AsyncCallback\): void +setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): void Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -848,7 +848,7 @@ sim.setShowNumber(0, number, (err, data) => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number,number: string\): Promise\ +setShowNumber\(slotId: number, number: string\): Promise\ Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result. @@ -885,7 +885,7 @@ promise.then(data => { ## sim.**getShowNumber**8+ -getShowNumber(slotId: number,callback: AsyncCallback): void +getShowNumber(slotId: number, callback: AsyncCallback): void Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1097,7 +1097,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; sim.setLockState(0, lockInfo, (err, data) => { @@ -1136,7 +1136,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; let promise = sim.setLockState(0, lockInfo); @@ -1344,7 +1344,7 @@ promise.then(data => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void +unlockPin(slotId: number, pin: string, callback: AsyncCallback): void Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1374,7 +1374,7 @@ sim.unlockPin(0, pin, (err, data) => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string): Promise<LockStatusResponse\> +unlockPin(slotId: number, pin: string): Promise<LockStatusResponse\> Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1411,7 +1411,7 @@ promise.then(data => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback): void +unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback): void Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1443,7 +1443,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string): Promise<LockStatusResponse\> +unlockPuk(slotId: number, newPin: string, puk: string): Promise<LockStatusResponse\> Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1482,7 +1482,7 @@ promise.then(data => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string ,callback: AsyncCallback): void +unlockPin2(slotId: number, pin2: string, callback: AsyncCallback): void Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1512,7 +1512,7 @@ sim.unlockPin2(0, pin2, (err, data) => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string): Promise<LockStatusResponse\> +unlockPin2(slotId: number, pin2: string): Promise<LockStatusResponse\> Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1539,7 +1539,7 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to ```js let pin2='1234'; -let promise = sim.unlockPin2(0,pin2); +let promise = sim.unlockPin2(0, pin2); promise.then(data => { console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1851,7 +1851,7 @@ Sets voice mailbox information for the SIM card in the specified slot. This API **Example** ```js -sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => { +sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2602,8 +2602,8 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; sim.unlockSimLock(0, persoLockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2640,8 +2640,8 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; let promise = sim.unlockSimLock(0, persoLockInfo); promise.then(data => { diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 6920c9dbf3aea204efb78c292e949a7ec0e4a053..7d372978202503f6ed0a0517fa69f85ae5dfcf44 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -160,7 +160,7 @@ promise.then(data => { ## sms.setDefaultSmsSlotId7+ -setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback<void>\): void +setDefaultSmsSlotId\(slotId: number, callback: AsyncCallback<void>\): void Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. @@ -180,7 +180,7 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a **Example** ```js -sms.setDefaultSmsSlotId(0,(err, data) => { +sms.setDefaultSmsSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -610,8 +610,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; sms.updateSimMessage(updateSimMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -650,8 +650,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; let promise = sms.updateSimMessage(updateSimMessageOptions); promise.then(data => { @@ -1054,13 +1054,13 @@ Encodes MMS messages. This API uses an asynchronous callback to return the resul ```js let mmsAcknowledgeInd = { - transactionId = "100", - version = 0x10, - reportAllowed = 128 + transactionId: "100", + version: sms.MmsVersionType.MMS_VERSION_1_0, + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType = 133, - mmsType = mmsAcknowledgeInd + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + mmsType: mmsAcknowledgeInd }; sms.encodeMms(mmsInformation, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -1096,10 +1096,10 @@ Encodes MMS messages. This API uses a promise to return the result. let mmsAcknowledgeInd = { transactionId: "100", version: sms.MmsVersionType.MMS_VERSION_1_0, - reportAllowed = sms.ReportType.MMS_YES + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, mmsType: mmsAcknowledgeInd }; let promise = sms.encodeMms(mmsInformation); diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index f3a29a9cc683fecc38b4c935af7607bd2a5415b8..a8ea022b24881bd1def701d3c59433270b0da762 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -88,7 +88,7 @@ console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) ## data.setDefaultCellularDataSlotId -setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void +setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): void Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. @@ -108,7 +108,7 @@ This is a system API. **Example** ```js -data.setDefaultCellularDataSlotId(0,(err, data) => { +data.setDefaultCellularDataSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -313,7 +313,7 @@ Checks whether the cellular data roaming service is enabled. This API uses an as **Example** ```js -data.isCellularDataRoamingEnabled(0,(err, data) => { +data.isCellularDataRoamingEnabled(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index e88c24874ded38ec76625957039617147d5664b6..24176d5c9727d1905d229aca43521462d6ebdd29 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -2334,7 +2334,7 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -2380,7 +2380,7 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -6199,7 +6199,7 @@ Loads content from a page associated with a local storage to the main window in | Name | Type | Mandatory | Description | | -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | +| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -6251,7 +6251,7 @@ Loads content from a page associated with a local storage to the main window in | Name | Type | Mandatory | Description | | ------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | +| storage | LocalStorage | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | **Return value** diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 322a8000a525eef6e32174a2a099f04573570edc..945c5219bedb22f5efdd6f53b5d55d4cdd97f260 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -59,7 +59,9 @@ Sets an attribute. let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setAttributes("importance", "high"); +thatSer.startElement("note"); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 75ac7f144e75fd9ed1068f161854fb185c0d6210..967def0ecbdfda71fe88bc55ac02e6d395046a00 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,31 +1,32 @@ -# Zip +# zlib + +The **zlib** module provides APIs for file compression and decompression. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Constraints - -None ## Modules to Import ```javascript import zlib from '@ohos.zlib'; ``` -## zlib.zipFile -zipFile(inFile:string, outFile:string, options: Options): Promise<void> +## zlib.zipFile(deprecated) +zipFile(inFile: string, outFile: string, options: Options): Promise<void> Zips a file. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [zlib.compressFile](#zlibcompressfile9) instead. + **System capability**: SystemCapability.BundleManager.Zlib **Parameters** | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) and [Stage Model](js-apis-application-context.md).| -| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | +| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | | options | [Options](#options) | No | Optional parameters for the zip operation. | **Return value** @@ -36,59 +37,59 @@ Zips a file. This API uses a promise to return the result. **Example 1** -```javascript - +```typescript // Zip a file. -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile, outFile, options).then((data) => { - console.log("zipFile result: " + data); -}).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('zipFile result is ' + JSON.Stringify(data)); +}).catch((err) => { + console.log('error is ' + JSON.Stringify(err)); }); - ``` **Example 2** -``` +```typescript // Zip a folder. -import zlib from '@ohos.zlib' -var inFile = "/xxx/xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile , outFile, options).then((data) => { - console.log("zipFile result: " + data); + console.log('zipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }); ``` -## zlib.unzipFile +## zlib.unzipFile(deprecated) unzipFile(inFile:string, outFile:string, options: Options): Promise<void> Unzips a file. This API uses a promise to return the result. +> This API is deprecated since API version 9. You are advised to use [zlib.decompressFile](#zlibdecompressfile9) instead. + **System capability**: SystemCapability.BundleManager.Zlib **Parameters** | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) and [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| | outFile | string | Yes | Path of the unzipped file. | | options | [Options](#options) | No | Optional parameters for the unzip operation. | @@ -100,11 +101,11 @@ Unzips a file. This API uses a promise to return the result. **Example** -```javascript +```typescript // Unzip a file. -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, @@ -112,11 +113,202 @@ let options = { strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.unzipFile(inFile, outFile, options).then((data) => { - console.log("unzipFile result: " + data); + console.log('unzipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }) - +``` + +## zlib.compressFile9+ + +compressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; + +Compresses a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BundleManager.Zlib + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the compressed file. | +| options | [Options](#options) | Yes | Compression parameters. | +| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | + +**Error codes** + +| ID| Error Message | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +**Example** + +```typescript +// Compress a file. +// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.compressFile(inFile, outFile, options, (errData) => { + if (erData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + } + }) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +compressFile(inFile: string, outFile: string, options: Options): Promise\; + +Compresses a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.BundleManager.Zlib + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the compressed file. | +| options | [Options](#options) | Yes | Compression parameters. | + +**Error codes** + +| ID| Error Message | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +```typescript +// Compress a file. +// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.compressFile(inFile, outFile, options).then((data) => { + console.info('compressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + }) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + + + +## zlib.decompressFile9+ + +decompressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; + +Decompresses a file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BundleManager.Zlib + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. | +| options | [Options](#options) | Yes | Decompression parameters. | +| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | + +**Error codes** + +| ID| Error Message | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +**Example** + +```typescript +// Decompress a file. +// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.decompressFile(inFile, outFile, options, (errData) => { + if (erData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + } + }) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +decompressFile(inFile: string, outFile: string, options: Options): Promise\; + +Decompress a file. This API uses a promise to return the result. + +**System capability**: SystemCapability.BundleManager.Zlib + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| outFile | string | Yes | Path of the decompressed file. | +| options | [Options](#options) | Yes | Decompression parameters. | + +**Error codes** + +| ID| Error Message | +| ------ | -------------------------------------- | +| 401 | wrong param type | +| 900001 | The Input source file is invalid. | +| 900002 | The Input destination file is invalid. | + +```typescript +// Decompress a file. +// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY +}; + +try { + zlib.deCompressFile(inFile, outFile, options).then((data) => { + console.info('deCompressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + }) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` ## Options @@ -129,16 +321,6 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { | memLevel | MemLevel | No | See [zip.MemLevel](#zipmemlevel). | | strategy | CompressStrategy | No | See [zip.CompressStrategy](#zipcompressstrategy).| -## zip.MemLevel - -**System capability**: SystemCapability.BundleManager.Zlib - -| Name | Value | Description | -| ----------------- | ---- | -------------------------------- | -| MEM_LEVEL_MIN | 1 | Minimum memory used by the **zip** API during compression.| -| MEM_LEVEL_MAX | 9 | Maximum memory used by the **zip** API during compression.| -| MEM_LEVEL_DEFAULT | 8 | Default memory used by the **zip** API during compression.| - ## zip.CompressLevel **System capability**: SystemCapability.BundleManager.Zlib @@ -150,6 +332,16 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { | COMPRESS_LEVEL_BEST_COMPRESSION | 9 | Compression level 9 that gives the best compression. | | COMPRESS_LEVEL_DEFAULT_COMPRESSION | -1 | Default compression level. | +## zip.MemLevel + +**System capability**: SystemCapability.BundleManager.Zlib + +| Name | Value | Description | +| ----------------- | ---- | -------------------------------- | +| MEM_LEVEL_MIN | 1 | Minimum memory used by the **zip** API during compression.| +| MEM_LEVEL_MAX | 9 | Maximum memory used by the **zip** API during compression.| +| MEM_LEVEL_DEFAULT | 8 | Default memory used by the **zip** API during compression.| + ## zip.CompressStrategy **System capability**: SystemCapability.BundleManager.Zlib diff --git a/en/application-dev/reference/arkui-ts/figures/align.png b/en/application-dev/reference/arkui-ts/figures/align.png new file mode 100644 index 0000000000000000000000000000000000000000..beed805dbff1ec1526bf034c011cf2c7b926eae8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/align.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif deleted file mode 100644 index 3174da059167d3560a99d50cca06ec678cabed96..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif deleted file mode 100644 index ee69d15a36eda3047be045a3d037fd27a37166fe..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png deleted file mode 100644 index 5499902761b534f84a0405094afe2fb5d4724322..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif deleted file mode 100644 index fe69ab973cfd17f540dd1da4fd04de890af95c74..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png deleted file mode 100644 index 92ddc7d5d9ee2f87128ed8951b2294ea3c07f650..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif deleted file mode 100644 index dffa33c4389c4576d2492cd98499b71715b8ead8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/nozindex.png b/en/application-dev/reference/arkui-ts/figures/nozindex.png new file mode 100644 index 0000000000000000000000000000000000000000..8c131eabacb8bcdee0b8ba891faaab69bb2a08bd Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/nozindex.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/position.png b/en/application-dev/reference/arkui-ts/figures/position.png new file mode 100644 index 0000000000000000000000000000000000000000..0c9e34bf611b4d51a49875d71f23fef24d6e2571 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/position.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/size.png b/en/application-dev/reference/arkui-ts/figures/size.png new file mode 100644 index 0000000000000000000000000000000000000000..5170abe9fb68747018cecc57e27df68806bafac4 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/size.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textstyle.png b/en/application-dev/reference/arkui-ts/figures/textstyle.png new file mode 100644 index 0000000000000000000000000000000000000000..38128cb5f1a6aa7a36a3b4e483bf2815c7170117 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textstyle.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/visibility.png b/en/application-dev/reference/arkui-ts/figures/visibility.png new file mode 100644 index 0000000000000000000000000000000000000000..89018fade9d9bef19dfc8a55d4477ba309353871 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/visibility.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/zindex.png b/en/application-dev/reference/arkui-ts/figures/zindex.png new file mode 100644 index 0000000000000000000000000000000000000000..bb2193d497c6cce42b5d7c6c94671c8bf7f6158e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/zindex.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index 25737f363751988499f8bc93232b6d4733470b54..0bde935d8e104ad982c322c342abb71b96909a31 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ You can set the background of a component. | Name| Type| Description| | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. | -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.
**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.| +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.| | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.
Default value: **ImageSize.Auto**| -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
**{
x: 0,
y: 0
}** | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.
Default value:
{
x: 0,
y: 0
}
When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index b9121ea16f40a620a93c4638772ea1bc76a35cd9..00099110825c5f1ba47594cf3ce9cd671f40f987 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -11,8 +11,8 @@ Layout constraints refer to constraints on the aspect ratio and display priority | Name | Type | Description | | --------------- | ------ | ---------------------------------------- | -| aspectRatio | number | Aspect ratio of the component. | -| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components.| +| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. | +| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components. | ## Example @@ -22,29 +22,32 @@ Layout constraints refer to constraints on the aspect ratio and display priority @Entry @Component struct AspectRatioExample { - private children : string[] = ['1', '2', '3', '4', '5', '6'] + private children: string[] = ['1', '2', '3', '4', '5', '6'] build() { - Column({space: 20}) { + Column({ space: 20 }) { Text('using container: row').fontSize(14).fontColor(0xCCCCCC).width('100%') - Row({space: 10}) { + Row({ space: 10 }) { ForEach(this.children, (item) => { + // Component width = Component height x 1.5 = 90 Text(item) .backgroundColor(0xbbb2cb) .fontSize(20) .aspectRatio(1.5) .height(60) + // Component height = Component width/1.5 = 60/1.5 = 40 Text(item) .backgroundColor(0xbbb2cb) .fontSize(20) .aspectRatio(1.5) .width(60) - }, item=>item) + }, item => item) } - .size({width: "100%", height: 100}) + .size({ width: "100%", height: 100 }) .backgroundColor(0xd2cab3) .clip(true) + // Grid child component width/height = 3/2 Text('using container: grid').fontSize(14).fontColor(0xCCCCCC).width('100%') Grid() { ForEach(this.children, (item) => { @@ -54,12 +57,12 @@ struct AspectRatioExample { .fontSize(40) .aspectRatio(1.5) } - }, item=>item) + }, item => item) } .columnsTemplate('1fr 1fr 1fr') .columnsGap(10) .rowsGap(10) - .size({width: "100%", height: 165}) + .size({ width: "100%", height: 165 }) .backgroundColor(0xd2cab3) }.padding(10) } @@ -67,47 +70,53 @@ struct AspectRatioExample { ``` **Figure 1** Portrait display + ![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif) **Figure 2** Landscape display + ![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ```ts class ContainerInfo { - label : string = '' - size : string = '' + label: string = ''; + size: string = ''; } class ChildInfo { - text : string = '' - priority : number = 0 + text: string = ''; + priority: number = 0; } @Entry @Component struct DisplayPriorityExample { - private container : ContainerInfo[] = [ - {label: 'Big container', size: '90%'}, - {label: 'Middle container', size: '50%'}, - {label: 'Small container', size: '30%'} + // Display the container size. + private container: ContainerInfo[] = [ + { label: 'Big container', size: '90%' }, + { label: 'Middle container', size: '50%' }, + { label: 'Small container', size: '30%' } ] - private children : ChildInfo[] = [ - {text: '1\n(priority:2)', priority: 2}, - {text: '2\n(priority:1)', priority: 1}, - {text: '3\n(priority:3)', priority: 3}, - {text: '4\n(priority:1)', priority: 1}, - {text: '5\n(priority:2)', priority: 2} + private children: ChildInfo[] = [ + { text: '1\n(priority:2)', priority: 2 }, + { text: '2\n(priority:1)', priority: 1 }, + { text: '3\n(priority:3)', priority: 3 }, + { text: '4\n(priority:1)', priority: 1 }, + { text: '5\n(priority:2)', priority: 2 } ] - @State currentIndex : number = 0 + @State currentIndex: number = 0; build() { - Column({space: 10}) { + Column({ space: 10 }) { + // Switch the size of the parent container. Button(this.container[this.currentIndex].label).backgroundColor(0x317aff) - .onClick((event: ClickEvent) => { - this.currentIndex = (this.currentIndex + 1) % this.container.length + .onClick(() => { + this.currentIndex = (this.currentIndex + 1) % this.container.length; }) - Flex({justifyContent: FlexAlign.SpaceBetween}) { - ForEach(this.children, (item)=>{ + // Set the width for the parent flex container through variables. + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + ForEach(this.children, (item) => { + // Bind the display priority to the child component through displayPriority. Text(item.text) .width(120) .height(60) @@ -115,11 +124,11 @@ struct DisplayPriorityExample { .textAlign(TextAlign.Center) .backgroundColor(0xbbb2cb) .displayPriority(item.priority) - }, item=>item.text) + }, item => item.text) } .width(this.container[this.currentIndex].size) .backgroundColor(0xd2cab3) - }.width("100%").margin({top:50}) + }.width("100%").margin({ top: 50 }) } } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 3cab264048f797063baf0d40f5b489807033967a..0670ab7d107bc99606d151b229b470b7a42a27a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -1,6 +1,6 @@ # Location -The location attribute sets the alignment mode, layout direction, and position of a component. +The location attributes set the alignment mode, layout direction, and position of a component. > **NOTE** > @@ -12,25 +12,25 @@ The location attribute sets the alignment mode, layout direction, and position o | Name| Type| Description| | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.
Default value: **Alignment.Center**| +| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
Default value: **Alignment.Center**| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**| -| position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| -| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
**{
x: 0,
y: 1**
} | -| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
**{
x: 0,
y: 1
}** | +| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| +| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | +| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | | alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example - +### Example 1 ```ts // xxx.ets @Entry @Component -struct PositionExample { - +struct PositionExample1 { build() { Column() { - Column({space: 10}) { + Column({ space: 10 }) { + // When the component content is within the area specified by the component width and height, set the alignment mode of the content in the component. Text('align').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('top start') .align(Alignment.TopStart) @@ -39,6 +39,14 @@ struct PositionExample { .fontSize(16) .backgroundColor(0xFFE4C4) + Text('Bottom end') + .align(Alignment.BottomEnd) + .height(50) + .width('90%') + .fontSize(16) + .backgroundColor(0xFFE4C4) + + // To arrange the child components from left to right, set direction of the parent container to Direction.Auto or Direction.Ltr, or leave it to the default value. Text('direction').fontSize(9).fontColor(0xCCCCCC).width('90%') Row() { Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) @@ -47,6 +55,15 @@ struct PositionExample { Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) } .width('90%') + .direction(Direction.Auto) + // To arrange the child components from right to left, set direction of the parent container to Direction.Rtl. + Row() { + Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) + Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) + Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) + Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) + } + .width('90%') .direction(Direction.Rtl) } } @@ -55,54 +72,75 @@ struct PositionExample { } ``` -![en-us_image_0000001212218456](figures/en-us_image_0000001212218456.gif) +![align.png](figures/align.png) +### Example 2 ```ts // xxx.ets @Entry @Component struct PositionExample2 { - build() { Column({ space: 20 }) { + // Set the offset of the component's upper left corner relative to the parent component's upper left corner. Text('position').fontSize(12).fontColor(0xCCCCCC).width('90%') - Row({ space: 20 }) { - Text('1').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }) .fontSize(16) - Text('2 position(25, 15)') - .size({ width: '60%', height: '30' }).backgroundColor(0xbbb2cb).border({ width: 1 }) - .fontSize(16).align(Alignment.Start) - .position({ x: 25, y: 15 }) + Row() { + Text('1').size({ width: '30%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('2 position(30, 10)') + .size({ width: '60%', height: '30' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) + .align(Alignment.Start) + .position({ x: 30, y: 10 }) Text('3').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) Text('4 position(50%, 70%)') - .size({ width: '50%', height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16) + .size({ width: '50%', height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) .position({ x: '50%', y: '70%' }) }.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed }) + // Offset relative to the start point. x indicates the horizontal distance between the end point and the start point. If the value of x is greater than 0, the component is offset to the left. Otherwise, the component is offset to the right. + // y indicates the vertical distance between the end point and the start point. If the value of y is greater than 0, the component is offset to the top. Otherwise, the component is offset to the bottom. Text('markAnchor').fontSize(12).fontColor(0xCCCCCC).width('90%') Stack({ alignContent: Alignment.TopStart }) { Row() .size({ width: '100', height: '100' }) .backgroundColor(0xdeb887) - Image($r('app.media.ic_health_heart')) + Text('text') .size({ width: 25, height: 25 }) + .backgroundColor(Color.Green) .markAnchor({ x: 25, y: 25 }) - Image($r('app.media.ic_health_heart')) + Text('text') .size({ width: 25, height: 25 }) - .markAnchor({ x: 25, y: 25 }) - .position({ x: '100%', y: '100%' }) + .backgroundColor(Color.Green) + .markAnchor({ x: -100, y: -25 }) + Text('text') + .size({ width: 25, height: 25 }) + .backgroundColor(Color.Green) + .markAnchor({ x: 25, y: -25 }) }.margin({ top: 25 }).border({ width: 1, style: BorderStyle.Dashed }) + // Offset of the component relative to itself. If the value of x is greater than 0, the component is offset to the right. Otherwise, the component is offset to the left. If the value of y is greater than 0, the component is offset to the bottom. Otherwise, the component is offset to the top. Text('offset').fontSize(12).fontColor(0xCCCCCC).width('90%') Row() { Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) - Text('2\noffset(15, 15)') - .size({ width: 120, height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 }) - .fontSize(16).align(Alignment.Start) - .offset({ x: 15, y: 15 }) + Text('2 offset(15, 30)') + .size({ width: 120, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) + .align(Alignment.Start) + .offset({ x: 15, y: 30 }) Text('3').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) - Text('4\noffset(-10%, 20%)') - .size({ width: 150, height: '50' }) .backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16) - .offset({ x: '-10%', y: '20%' }) + Text('4 offset(-10%, 20%)') + .size({ width: 100, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) + .offset({ x: '-5%', y: '20%' }) }.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed }) } .width('100%').margin({ top: 25 }) @@ -110,4 +148,4 @@ struct PositionExample2 { } ``` -![en-us_image_0000001256858409](figures/en-us_image_0000001256858409.gif) +![position.png](figures/position.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 0f34f7464c8826adece2aad5c1ccace799786cd3..4bb23b9f11f8f7ab4aa187fedaca3ab37716a461 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -8,10 +8,9 @@ You can set overlay text for a component. ## Attributes -| Name | Type | Description | -| ------- | ----------------------------- | ------------------------- | -| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {
x?: number,
y?: number
}
} | Overlay added to the component. The overlay has the same layout as the component.
Default value:
{
align: Alignment.Center,
offset: {0, 0}
} | - +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | Overlay added to the component.
**value**: mask text.
**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.
If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.| ## Example @@ -28,7 +27,10 @@ struct OverlayExample { Column() { Image($r('app.media.img')) .width(240).height(240) - .overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, offset: { x: 0, y: -15 } }) + .overlay("Winter is a beautiful season, especially when it snows.", { + align: Alignment.Bottom, + offset: { x: 0, y: -15 } + }) }.border({ color: Color.Black, width: 2 }) }.width('100%') }.padding({ top: 20 }) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 9710a01a6870933d3b832ce589e192fe0cbcb87d..74d546c622afe8785f4507ea8ab74ba18806febe 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -85,7 +85,7 @@ struct PopupExample { } }, onStateChange: (e) => { - console.info(e.isVisible.toString()) + console.info(JSON.stringify(e.isVisible)) if (!e.isVisible) { this.handlePopup = false } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index de23ed8824f18e44b59d70dd282794193df31b18..87e47dd06c71cb138311fa221e658d3451d9b2ef 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -1,6 +1,6 @@ # Size -The size attributes are used to set the width, height, padding, and margin of a component. +The size attributes set the width, height, and margin of a component. > **NOTE** > @@ -16,9 +16,9 @@ The size attributes are used to set the width, height, padding, and margin of a | height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn. | | size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Size of the component. | | padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.
When the parameter is of the **Length** type, the four paddings take effect.
Default value: **0**
When **padding** is set to a percentage, the width of the parent container is used as the basic value.| -| margin | [Margin](ts-types.md#margin)) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.| +| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.| | constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
} | -| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.
Default value: **0**| +| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.| ## Example @@ -31,30 +31,41 @@ struct SizeExample { build() { Column({ space: 10 }) { Text('margin and padding:').fontSize(12).fontColor(0xCCCCCC).width('90%') - // The width is 80, the height is 80, the padding is 20, and the margin is 20. Row() { + // Width: 80; height: 80; margin: 20 (blue area); padding: 10 (white area) Row() { - Row().size({ width: '100%', height: '100%' }).backgroundColor(0xAFEEEE) - }.width(80).height(80).padding(20).margin(20).backgroundColor(0xFDF5E6) - }.backgroundColor(0xFFA500) + Row().size({ width: '100%', height: '100%' }).backgroundColor(Color.Yellow) + } + .width(80) + .height(80) + .padding(10) + .margin(20) + .backgroundColor(Color.White) + }.backgroundColor(Color.Blue) + + Text('constraintSize').fontSize(12).fontColor(0xCCCCCC).width('90%') + Text('this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text') + .width('90%') + .constraintSize({ maxWidth: 200 }) Text('layoutWeight').fontSize(12).fontColor(0xCCCCCC).width('90%') - // When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored. + // When the container size is determined, the component occupies the space along the main axis based on the layout weight, and the component size setting is ignored. Row() { - // Weight 1 + // Weight 1: The component occupies 1/3 of the remaining space along the main axis. Text('layoutWeight(1)') .size({ width: '30%', height: 110 }).backgroundColor(0xFFEFD5).textAlign(TextAlign.Center) .layoutWeight(1) - // Weight 2 + // Weight 2: The component occupies 2/3 of the remaining space along the main axis. Text('layoutWeight(2)') .size({ width: '30%', height: 110 }).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .layoutWeight(2) - // The default weight is 0. + // If layoutWeight is not set, the component is rendered based on its own size setting. Text('no layoutWeight') .size({ width: '30%', height: 110 }).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) }.size({ width: '90%', height: 140 }).backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) - }} + } +} ``` -![en-us_image_0000001257138367](figures/en-us_image_0000001257138367.gif) +![size](figures/size.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index f7937b97bffbb5ab4f596940910a22e9922b4040..8330e79474aef2c523fadaf3677323c724e3570a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -1,23 +1,23 @@ # Text Style - -The text style attributes are used to set the style for text in a component. +The text style attributes set the style for text in a component. > **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. + ## Attributes | Name | Type | Description | | -----------| ---------------------------------------- | ------------------------------------ | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. | -| fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. | +| fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 10. This attribute cannot be set in percentage. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal** | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal** | -| fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.| +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in FontWeight.
Default value: **FontWeight.Normal** | +| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
Default value: **'HarmonyOS Sans'**
Currently, only the default font is supported. | ## Example @@ -30,40 +30,38 @@ struct TextStyleExample { build() { Column({ space: 5 }) { Text('default text') - - Text('text font color red') - .fontColor(Color.Red) - - Text('text font size 20') - .fontSize(20) - - Text('text font style Italic') - .fontStyle(FontStyle.Italic) - - Text('text fontWeight bold') - .fontWeight(700) - - Text('text fontFamily sans-serif') - .fontFamily('sans-serif') - - Text('red 20 Italic bold cursive text') + Divider() + + Text('text font color red').fontColor(Color.Red) + Divider() + + Text('text font default') + Text('text font size 10').fontSize(10) + Text('text font size 10fp').fontSize('10fp') + Text('text font size 20').fontSize(20) + Divider() + + Text('text font style Italic').fontStyle(FontStyle.Italic) + Divider() + + Text('text fontWeight bold').fontWeight(700) + Text('text fontWeight lighter').fontWeight(FontWeight.Lighter) + Divider() + + Text('red 20 Italic bold text') .fontColor(Color.Red) .fontSize(20) .fontStyle(FontStyle.Italic) - .fontWeight(700) - .fontFamily('cursive') - .textAlign(TextAlign.Center) - .width('90%') - - Text('Orange 18 Normal source-sans-pro text') + .fontWeight(FontWeight.Bold) + Divider() + + Text('Orange 18 Normal text') .fontColor(Color.Orange) .fontSize(18) .fontStyle(FontStyle.Normal) - .fontWeight(400) - .fontFamily('source-sans-pro,cursive,sans-serif') }.width('100%') } } ``` -![en-us_image_0000001256978333](figures/en-us_image_0000001256978333.png) +![textstyle](figures/textstyle.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md index 40b83f1cb3f00f756e73b6c95f990c6fced9a272..82d42267a5e9b81c29063ad232c5212bbbf02574 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md @@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible. | Name | Type | Description | | ---------- | ---------------------------- | ------------------------------------------ | -| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible**| +| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible**| ## Example @@ -23,20 +23,21 @@ struct VisibilityExample { build() { Column() { Column() { - Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC) - Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE) - - Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC) // The component is hidden, and no placeholder is used. + Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC) Row().visibility(Visibility.None).width('90%').height(80).backgroundColor(0xAFEEEE) - Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC) // The component is hidden, and a placeholder is used for it in the layout. + Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC) Row().visibility(Visibility.Hidden).width('90%').height(80).backgroundColor(0xAFEEEE) + + // The component is visiable, which is the default display mode. + Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC) + Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE) }.width('90%').border({ width: 1 }) }.width('100%').margin({ top: 5 }) } } ``` -![en-us_image_0000001257058421](figures/en-us_image_0000001257058421.gif) +![visibility.png](figures/visibility.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md index 627f185a148369e77b8cce138b2d62723ddcf584..24be504eef9a302db845b10a0f1e9f082d6d6efd 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md @@ -25,20 +25,24 @@ struct ZIndexExample { build() { Column() { Stack() { - // Components are stacked. By default, the component defined later is on the top. - Text('first child, zIndex(2)') - .size({width: '40%', height: '30%'}).backgroundColor(0xbbb2cb) + // Components are stacked. By default, the component defined later is on the top. A component with a larger zIndex value is displayed before one with a smaller zIndex value. + Text('1, zIndex(2)') + .size({ width: '40%', height: '30%' }).backgroundColor(0xbbb2cb) .zIndex(2) - // The default value is 0. - Text('second child, default zIndex(0)') - .size({width: '90%', height: '80%'}).backgroundColor(0xd2cab3).align(Alignment.TopStart) - Text('third child, zIndex(1)') - .size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart) + Text('2, default zIndex(1)') + .size({ width: '70%', height: '50%' }).backgroundColor(0xd2cab3).align(Alignment.TopStart) .zIndex(1) + Text('3, zIndex(0)') + .size({ width: '90%', height: '80%' }).backgroundColor(0xc1cbac).align(Alignment.TopStart) }.width('100%').height(200) }.width('100%').height(200) } } ``` +Display of child components in the **\** component when **zIndex** is not set -![en-us_image_0000001257058443](figures/en-us_image_0000001257058443.png) +![nozindex.png](figures/nozindex.png) + +Display of child components in the **\** component when **zIndex** is set + +![zindex.png](figures/zindex.png) diff --git a/en/application-dev/reference/errorcodes/errcode-DistributedSchedule.md b/en/application-dev/reference/errorcodes/errcode-DistributedSchedule.md new file mode 100644 index 0000000000000000000000000000000000000000..e815e8e881396cde327155f2c4593778d277b19c --- /dev/null +++ b/en/application-dev/reference/errorcodes/errcode-DistributedSchedule.md @@ -0,0 +1,375 @@ +# Distributed Scheduler Error Codes + +## 16600001 The system ability works abnormally. + +**Error Message** + +The system ability works abnormally. + +**Description** + +This error code is reported when the system ability is abnormal. + +**Possible Causes** + +The possible causes are as follows: +1. The DMS service is not started. +2. The **binder** object of DMS is not obtained. +3. Other services on which ability continuation depends are not started or the **binder** object is not obtained. + +**Solution** + +Try again later or restart the device. + +## 16600002 The specified token or callback is not registered. + +**Description** + +This error code is reported if the token or callback used in an API of **continuationManager** is not registered when the API is called. + +**Error Message** + +The specified token or callback is not registered. + +**Possible Causes** + +The specified token or callback is not registered. + +**Solution** + +Register the token or callback before calling the API. + +## 16600003 The number of token registration times has reached the upper limit. + +**Description** + +This error code is reported when the number of times that the **continuationManager.registerContinuation** API is called has reached the upper limit. + +**Error Message** + +The number of token registration times has reached the upper limit. + +**Possible Causes** + +The number of token registration times has reached the upper limit. + +**Solution** + +Use a registered token. Do not register the token too frequently. + +## 16600004 The specified callback has been registered. + +**Description** + +This error code is reported when the **continuationManager.on** API is called with a callback the same as a previous one. + +**Error Message** + +The specified callback has been registered. + +**Possible Causes** + +The same callback is used for repeated registration. + +**Solution** + +Use a different callback for registration. + +## 16300501 The system ability works abnormally. + +**Description** + +This error code is reported when the system ability is abnormal. + +**Error Message** + +The system ability works abnormally. + +**Possible Causes** + +The possible causes are as follows: +1. The DMS service is not started. +2. The **binder** object of DMS is not obtained. +3. Other services on which ability continuation depends are not started or the **binder** object is not obtained. + +**Solution** + +Try again later or restart the device. + +## 16300502 Failed to get the missionInfo of the specified missionId. + +**Description** + +This error code is reported when calling the **distributedMissionManager.continueMission** API fails. + +**Error Message** + +Failed to get the missionInfo of the specified missionId. + +**Possible Causes** + +The possible causes are as follows: +1. The mission ID is incorrect. +2. The mission information corresponding to the mission ID does not exist. + +**Solution** + +Verify the mission ID. + +## 16300503 The application is not installed on the remote end and installation-free is not supported. + +**Description** + +This error code is reported if the application is not installed on the remote end and the installation-free feature is not supported when the **distributedMissionManager.continueMission** API is called. + +**Error Message** + +The application is not installed on the remote end and installation-free is not supported. + +**Possible Causes** + +The application to continue is not installed on the remote end, and the installation-free feature is not supported. + +**Solution** + +1. Check whether the application has been installed on the remote end. +2. Check whether the remote end supports installation-free. + +## 16300504 The application is not installed on the remote end and installation-free is supported. Try again with the freeInstall flag. + +**Description** + +This error code is reported if the application is not installed on the remote end and installation-free is supported when the **distributedMissionManager.continueMission** API is called. + +**Error Message** + +The application is not installed on the remote end and installation-free is supported. Try again with the freeInstall flag. + +**Possible Causes** + +The application to continue is not installed on the remote end, and installation-free is supported. However, the **freeInstall** flag is not carried. + +**Solution** + +Try again with the **freeInstall** flag. + +## 16300505 The operation device must be the device where the application to be continued is currently located or the target device. + +**Description** + +This error code is reported if the operation device is not the device where the application to be continued is currently located (source device) or the target device when the **distributedMissionManager.continueMission** API is called. + +**Error Message** + +The operation device must be the device where the application to be continued is currently located or the target device. + +**Possible Causes** + +The operation device is not the source or target device. + +**Solution** + +Use the source or target device for the operation. + +## 16300506 The local continuation task is already in progress. + +**Description** + +This error code is reported if the local continuation task is in progress when the **distributedMissionManager.continueMission** API is called. + +**Error Message** + +The local continuation task is already in progress. + +**Possible Causes** + +The continuation task has been initiated and is not complete yet. + +**Solution** + +Wait until the continuation task is complete. + +## 3 Failed to flatten the object. + +**Description** + +This error code is reported if the system parameter **DMS_PROXY_INTERFACE_TOKEN** fails flattening when an API of **continuationManager** is called. + +**Error Message** + +Failed to flatten the object. + +**Possible Causes** + +The system parameter **DMS_PROXY_INTERFACE_TOKEN** fails to be written in serialization. + +**Solution** + +Make sure the system functions properly. Restart the system when needed. + +## 7 The object is null. + +**Error Message** + +The object is null. + +**Description** + +This error code is reported if DMS and other objects are empty or reading in serialization fails when an API of **continuationManager** is called. + +**Possible Causes** + +The possible causes are as follows: +1. Reading the input parameters in serialization fails. +2. The DMS service is not started or the **binder** object is not obtained. +3. Other services on which DMS depends are not started or the **binder** object is not obtained. + +**Solution** + +1. Check whether the input parameters are valid. +2. Check whether the DMS service is started normally. Restart the service or device when needed. +3. Check whether other services on which DMS depends are started normally. Restart the services or device when needed. + +## 29360207 The number of registrations has reached the upper limit. + +**Description** + +This error code is reported when the number of times that the **continuationManager.register** API is called exceeds the upper limit. + +**Error Message** + +The number of registrations has reached the upper limit. + +**Possible Causes** + +The number of device registration times has reached the upper limit. + +**Solution** + +Restart the service and avoid frequent registration. + +## 29360208 The token is not registered. + +**Description** + +This error code is reported when an API of **continuationManager** is called with an unregistered token. + +**Error Message** + +The token is not registered. + +**Possible Causes** + +The token is not registered. + +**Solution** + +Register a token and use it in the API. + +## 29360209 The callback has been registered. + +**Description** + +This error code is reported when the **continuationManager.on** API is called with a callback the same as a previous one. + +**Error Message** + +The callback has been registered. + +**Possible Causes** + +The specified callback has been registered. + +**Solution** + +Do not use the same callback for repeated registration. + +## 29360210 The callback is not registered. + +**Description** + +This error code is reported when the **off**, **updateConnectStatus**, or **startDeviceManager** API of **continuationManager** is called with a callback that has been not registered by calling **on**. + +**Error Message** + +The callback is not registered. + +**Possible Causes** + +The specified callback is not registered. + +**Solution** + +Register a callback and use it in the API. + +## 29360211 Failed to connect to the ability. + +**Description** + +This error code is reported if connection to the specified ability fails when the **startDeviceManager** API of **continuationManager** is called. + +**Error Message** + +Failed to connect to the ability. + +**Possible Causes** + +The specified token is invalid or the target ability is not working properly. + +**Solution** + +Check whether the token is valid and whether the corresponding ability is normal. Restart the service or device when needed. + +## 29360214 The type of callback is not supported. + +**Description** + +This error code is reported when the **callback** parameter in the **on** or **off** API of **continuationManager** is set to an incorrect type. + +**Error Message** + +The type of callback is not supported. + +**Possible Causes** + +The callback type is not supported. + +**Solution** + +Pass a supported type for the **callback** parameter. + +## 29360215 Invalid connection state. + +**Description** + +This error code is reported when the **status** parameter in the **updateConnectStatus** API of **continuationManager** is invalid. + +**Error Message** + +Invalid connection state. + +**Possible Causes** + +The **status** parameter is invalid. + +**Solution** + +Use a valid value for the **status** parameter. + +## 29360216 Invalid continuation mode. + +**Error Message** + +Invalid continuation mode. + +**Description** + +This error code is reported when the **ContinuationExtraParams.continuationMode** parameter in the **register** or **startDeviceManager** API of **continuationManager** is invalid. + +**Possible Causes** + +The **ContinuationExtraParams.continuationMode** parameter is invalid. + +**Solution** + +Use a valid value for the **ContinuationExtraParams.continuationMode** parameter. diff --git a/en/application-dev/reference/errorcodes/errcode-bundle.md b/en/application-dev/reference/errorcodes/errcode-bundle.md new file mode 100644 index 0000000000000000000000000000000000000000..a7a0b452137bf1cbd66af1e0e541d9421b491eb1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errcode-bundle.md @@ -0,0 +1,371 @@ +# Bundle Error Codes + +## 17700001 Nonexistent Bundle Name + +**Error Message** +The specified bundle name is not found. + +**Description** +This error code is reported when the bundle name passed in the API does not exist. + +**Possible Causes** +1. The bundle name is misspelled. +2. The corresponding application is not installed. + +**Solution** +1. Check whether the spelling of the bundle name is correct. +2. Check whether the corresponding application is installed. + +## 17700002 Nonexistent Module Name + +**Error Message** +The specified module name is not found. + +**Description** +This error code is reported when the module name passed in the API does not exist. + +**Possible Causes** +1. The module name is misspelled. +2. The module is not installed for the application. + +**Solution** +1. Check whether the spelling of the module name is correct. +2. Check whether the module is installed for the application. + +## 17700003 Nonexistent Ability Name + +**Error Message** +The specified ability name is not found. + +**Description** +This error code is reported when the ability name passed in the API does not exist. + +**Possible Causes** +1. The ability name is misspelled. +2. The corresponding application is not installed. + +**Solution** +1. Check whether the spelling of the ability name is correct. +2. Check whether the ability is installed for the application. + +## 17700004 Nonexistent User ID + +**Error Message** +The specified user id is not found. + +**Description** +This error code is reported when the user ID passed in the API does not exist. + +**Possible Causes** +The user ID is incorrect. The user does not exist. + +**Solution** +1. Check whether the user ID is correct. +2. Check whether the user exists. + +## 17700005 Nonexistent Application ID + +**Error Message** +The specified appId is not found. + +**Description** +This error code is reported when the value of **appId** passed in the API is an empty string. + +**Possible Causes** +**appId** is an empty string. + +**Solution** +Check whether **appId** is an empty string. + +## 17700006 Nonexistent Permission + +**Error Message** +The specified permission is not found. + +**Description** +This error code is reported when the permission passed in the API does not exist. + +**Possible Causes** +1. The permission name is misspelled. +2. The permission does not exist. + +**Solution** +1. Check whether the spelling of the permission name is correct. +2. Check whether the permission exists. + +## 17700007 Incorrect Device ID + +**Error Message** +The specified deviceId is not found. + +**Description** +This error code is reported when the device ID passed in the API is incorrect. + +**Possible Causes** +1. The device ID is incorrect. +2. The device ID does not exist. + +**Solution** +1. Check whether the device ID is correct. +2. Check whether the device ID exists. + +## 17700010 Application Installation Failure Due to File Parsing Failure + +**Error Message** +Failed to install the hap since the hap fails to be parsed. + +**Description** +This error code is reported when the application fails to be installed because the HAP fails to be parsed. + +**Possible Causes** +1. The HAP is not in ZIP format. +2. The configuration file in the HAP is not in JSON format. +3. Necessary fields are missing in the configuration file. + +**Solution** +1. Check whether the HAP is in ZIP format. +2. Check whether the configuration file is in [JSON format](../../quick-start/stage-structure.md). +3. Check whether an error message is displayed when DevEco Studio compiles the HAP. If necessary fields are missing, an error message will be displayed. + +## 17700011 Application Installation Failure Due to Signature Verification Failure + +**Error Message** +Failed to install the hap since the hap signature fails to be verified. + +**Description** +This error code is reported when the application fails to be installed due to signature verification failure. + +**Possible Causes** + +1. The HAP is not signed. +2. The source of the HAP signature information is unreliable. +3. The signature information of the HAP used for an upgrade is different from that of the installed HAP. +4. The signature information of multiple HAPs is inconsistent. + +**Solution** +1. Check whether the HAP is signed. +2. Check whether the same certificate is used for signing multiple HAPs. +3. Check whether the certificate used for signing the upgrade HAP is the same as the certificate used for signing the installed HAP. + +## 17700012 Application Installation Failure Due to Invalid File Path or Too Large File + +**Error Message** +Failed to install the hap since the path of the hap is invalid or too large size. + +**Description** +This error code is reported when the application fails to be installed because the HAP path is invalid or the HAP is too large. + +**Possible Causes** +1. The path of the HAP does not exist. +2. The path of the HAP is inaccessible. +3. The size of the HAP exceeds the upper limit 4 GB. + +**Solution** +1. Check whether the HAP path exists. +2. Check whether the HAP is read only or executable. +3. Check whether the size of the HAP exceeds 4 GB. + +## 17700015 Application Installation Failure Due to Different Configuration Information of Multiple HAP Packages + +**Error Message** +Failed to install haps since the configuration information of multi haps is inconsistent. + +**Description** +This error code is reported when the application fails to be installed because the HAPs have different configuration information. + +**Possible Causes** +The fields under **app** in the configuration files of these HAPs are inconsistent. + +**Solution** +Check whether the fields under **app** are the same. + +## 17700016 Application Installation Failure Due to Insufficient System Disk Space + +**Error Message** +Failed to install the hap since the system disk space is insufficient. + +**Description** +This error code is reported when the application fails to be installed due to insufficient system disk space. + +**Possible Causes** +The system disk space is insufficient. + +**Solution** +Check whether the system has sufficient disk space. + +## 17700017 Application Installation Failure Because the Version to Install is Too Earlier + +**Error Message** +Failed to install the hap since the version of the newly installed hap is too early. + +**Description** +This error code is reported when the version number of the application to install is earlier than the version in use. + +**Possible Causes** +The version number is earlier than the version in use. + +**Solution** +Ensure that the version of the application to install is later than the version in use. + +## 17700020 Failure to Uninstall Preinstalled Applications + +**Error Message** +The preinstalled app cannot be uninstalled. + +**Description** +This error code is reported when you attempt to uninstall a preinstalled application. + +**Possible Causes** +1. You might want to uninstall a non-preinstalled application but passed the bundle name of a preinstalled app. +2. The preinstalled application cannot be uninstalled. + +**Solution** +1. Check whether the bundle name is correct. +1. Check whether the preinstalled application can be uninstalled. + +## 17700021 Invalid UID + +**Error Message** +The specified uid is invalid. + +**Description** +This error code is reported when the UID passed in the API is invalid. + +**Possible Causes** +1. The UID is misspelled. +2. The UID does not exist. + +**Solution** +1. Check whether the UID is correct. +2. Check whether the UID exists. + +## 17700022 Invalid Source File + +**Error Message** +The input source file is invalid. + +**Description** +This error code is reported when the source file to be parsed is invalid. + +**Possible Causes** +1. The source file to be parsed does not exist. +2. The source file to be parsed is not in ZIP format. + +**Solution** +1. Check whether the source file to be parsed exists. +2. Check whether the source file to be parsed is in ZIP format. + +## 17700023 Nonexistent Default Application + +**Error Message** +The specified default app does not exist. + +**Description** +This error code is reported when the specified default application does not exist. + +**Possible Causes** +No default application is set for the device. + +**Solution** +Check whether the default application is set on the device. + +## 17700024 Nonexistent Configuration File + +**Error Message** +Failed to get profile since no profile in the hap. + +**Description** +This error code is reported when you attempt to obtain the configuration file that does not exist. + +**Possible Causes** +1. The metadata name passed in the API does not exist in the configuration file. +2. The content of the configuration file is not in JSON format. + +**Solution** +1. Check whether the metadata name in the **ability** or **extensionAbility** to be queried exists. +2. Check whether the content of the profile to be queried is in JSON format. + +## 17700025 Invalid Type + +**Error Message** +The specified type is invalid. + +**Description** +The type is invalid. + +**Possible Causes** +1. The type passed in the API is misspelled. +2. The type passed in the API does not exist. + +**Solution** +Check whether the spelling of type is correct. + +## 17700026 Application Disabled + +**Error Message** +The specified bundle is disabled. + +**Description** +This error code is reported when the specified application is disabled. + +**Possible Causes** +The application on the device has been disabled and cannot be queried. + +**Solution** +Check whether the application on the device is disabled. + +## 17700027 Distributed Service Not Started + +**Error Message** +The distributed service is not running. + +**Description** +This error code is reported when the distributed service is not started. + +**Possible Causes** +The device is not networked. + +**Solution** +Check whether the device is networked. +## 17700028 Mismatch Between Ability and Type + +**Error Message** +The ability does not match the type. + +**Description** +This error code is reported when the ability and type passed in the API do not match. + +**Possible Causes** +The ability and type are misspelled. + +**Solution** +Check whether the spellings of ability and type are correct. + +## 17700029 Disabled Ability + +**Error Message** +The specified ability is disabled. + +**Description** +This error code is reported when the specified ability is disabled. + +**Possible Causes** +The specified ability is disabled. + +**Solution** +Check whether the ability is disabled. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information. + +## 17700030 Failure in Clearing Cache Files + +**Error Message** +The specified bundle does not support clearing cache files. + +**Description** +This error code is reported when the application does not support cache file clearing. + +**Possible Causes** +The application is a system application and the **AllowAppDataNotCleared** field is configured in the signing certificate. + +**Solution** +1. Check whether the application is a system application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **isSystemApp** is **true**. +2. Check whether the **AllowAppDataNotCleared** field is configured for the application. You can run the [bm commands](../../../readme/bundle-management.md#bm-commands) to query the application information and check whether the value of **userDataClearable** is **true**. diff --git a/en/application-dev/reference/errorcodes/errorcode-AccessToken.md b/en/application-dev/reference/errorcodes/errorcode-AccessToken.md new file mode 100644 index 0000000000000000000000000000000000000000..306ad41da505db3a42a8d6668ce00b47c7e3f60e --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-AccessToken.md @@ -0,0 +1,140 @@ +# Access Token Error Codes + +## 401 Parameter Error + +### Error Message +Parameter error.${messageInfo}. + +### Possible Causes +This error code is reported if an error occurs during JS parameter parsing. The possible causes are as follows: +1. The number of input parameters is insufficient. +2. The parameter type is incorrect. + +### Solution +1. Add input parameters. +2. Correct parameter types. + + +## 201 Permission denied. + +### Error Message +Permission denied.${messageInfo}. + +### Possible Causes +This error code is reported if the application process that calls an API is not granted the required permission. The possible causes are as follows: +1. The application process is not granted the required permission. +2. The permission requires user authorization to take effect, but the application process does not obtain the user authorization. + +### Solution +1. Check whether the application process is granted the required permission. +2. Check whether the application process has obtained the user authorization if the permission requires user authorization to take effect. + + +## 12100001 Invalid Parameters + +### Error Message +Parameter invalid, message is ${messageInfo}. + +### Possible Causes +This error code is reported if an error occurs during parameter verification. The possible causes are as follows: +1. The value of **tokenId** is **0**. +2. The specified permission name is empty or contains more than 256 characters. +3. The **flag** value in the permission authorization or revocation request is invalid. +4. The input parameters specified for registering a listener are incorrect. + +### Solution +1. Correct the invalid parameter values. + + +## 12100002 TokenId does not exist. + +### Error Message +TokenId does not exist. + +### Possible Causes +1. The specified **tokenId** does not exist. +2. The process corresponding to the specified **tokenId** is not an application process. + +### Solution +Set a correct **tokenId**, and make sure that the process corresponding to the specified **tokenId** is an application process. + + +## 12100003 Permission Not Exist + +### Error Message +Permission does not exist. + +### Possible Causes +1. The specified **permissionName** does not exist. +2. The specified **permissionName** does not match the specified **tokenId** in the permission authorization or revocation scenario. +3. The specified **permissionName** is not a sensitive permission that requires user authorization. + +### Solution +Set the **permissionName** parameter correctly. For details, see [permission-list](../../security/permission-list.md). + + +## 12100004 Listener APIs Not Used in Pairs + +### Error Message +The listener interface is not used together. + +### Possible Causes +This error code is reported if listener APIs are not used in pairs. The possible causes are as follows: +1. The listener APIs that need to be used in pairs are repeatedly called. +2. The listener APIs that need to be used in pairs are independently called. + +### Solution +1. Check whether the API needs to be used in pairs. That is, if an API is called to enable listening, an API with the same input parameters cannot be called unless an API is called to stop listening first. +2. Check whether the API needs to be used in pairs. That is, an API for disabling listening or unregistering a listener can only be called after the API for enabling listening or registering a listener is called. + + +## 12100005 Listener Overflow + +### Error Message +The number of listeners exceeds the limit. + +### Possible Causes +The number of listeners exceeds 200 (the upper limit). + +### Solution +Abandon unused listeners in a timely manner. + + +## 12100006 Permission Granting or Revocation Not Supported for the Specified Application + +### Error Message +The specified application does not support the permissions granted or ungranted as specified. + +### Possible Causes +1. The specified **tokenId** is the identity of the remote device. Distributed granting and revocation are not yet supported. +2. The specified **tokenId** belongs to a sandbox application, which is not allowed to apply for the specified permission. + +### Solution +1. Check whether the method of obtaining **tokenId** is correct. +2. Check whether the sandbox application works in restrictive mode. Most permissions cannot be granted to a sandbox application in restrictive mode. + + +## 12100007 System Services Not Working Properly + +### Error Message +Service is abnormal. + +### Possible Causes +This error code is reported if system services are not working properly. The possible causes are as follows: +1. The permission management service cannot be started properly. +2. An error occurs while reading or writing IPC data. + +### Solution +System services do not work properly. Try again later or restart the device. + + +## 12100008 Out of Memory + +### Error Message +Out of memory. + +### Possible Causes +The system memory is insufficient. + +### Solution +Try again later or restart the device. diff --git a/en/application-dev/reference/errorcodes/errorcode-audio.md b/en/application-dev/reference/errorcodes/errorcode-audio.md new file mode 100644 index 0000000000000000000000000000000000000000..31825c31e8990d94d7c8abf5253cdd6e82216bde --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-audio.md @@ -0,0 +1,131 @@ +# Audio Error Codes + +## 6800101 Invalid Parameter + +**Error Message** + +invalid parameter. + +**Description** + +A parameter passed in the API is invalid. + +**Possible Causes** + +The parameter is invalid. For example, the parameter value is not within the range supported. + +**Solution** + +Pass the correct parameters in the API. + +## 6800102 Memory Allocation Failure + +**Error Message** + +allocate memory failed. + +**Description** + +When the API is called, the memory fails to be allocated or a null pointer occurs. + +**Possible Causes** + +1. The system does not have sufficient memory for mapping. +2. Invalid instances are not destroyed in time to release the memory. + +**Solution** + +1. Destroy the existing instances. +2. Create a new instance. If the creation fails, stop related operations. + +## 6800103 Unsupported State + +**Error Message** + +Operation not permit at current state. + +**Description** + +This operation is not allowed in the current state. + +**Possible Causes** + +The operation is not supported in the current state. For example, data is played before streams are started. + +**Solution** + +1. Check whether this operation is supported in the current state. +2. Switch the instance to the correct state and perform the operation. + +## 6800104 Unsupported Parameter Value + +**Error Message** + +unsupported operation. + +**Description** + +The parameter value is not supported. + +**Possible Causes** + +The value of the input parameter is not within the range supported. + +**Solution** + +1. Check the enums or other input parameters supported by the API. +2. Use a supported value. + +## 6800105 Processing Timeout + +**Error Message** + +time out. + +**Description** + +Waiting for external processing times out. + +**Possible Causes** + +Waiting for external processing times out. For example, waiting for the application to fill in audio data times out. + +**Solution** + +Control the time of the write operation, for example, adding delayed processing. + +## 6800201 Too Many Audio Streams + +**Error Message** + +stream number limited. + +**Description** + +The number of audio streams reaches the upper limit. + +**Possible Causes** + +Invalid audio streams are not released in time. + +**Solution** + +Release audio streams that are no longer used. + +## 6800301 System Error + +**Error Message** + +system error. + +**Description** + +The system processing is abnormal. + +**Possible Causes** + +The system processing is abnormal, for example, system service restart or IPC exceptions. + +**Solution** + +Create the service again. diff --git a/en/application-dev/reference/errorcodes/errorcode-device-manager.md b/en/application-dev/reference/errorcodes/errorcode-device-manager.md index 3e0459cebcb89d3d501bc331f9526320cd7d72e6..3d23690c0ded759312b899c49cfb7d265f9f8e7d 100644 --- a/en/application-dev/reference/errorcodes/errorcode-device-manager.md +++ b/en/application-dev/reference/errorcodes/errorcode-device-manager.md @@ -10,7 +10,7 @@ Failed to execute the function. An error occurred during internal invocation. -**Procedure** +**Solution** Call the API again. @@ -24,7 +24,7 @@ Failed to obtain the service. The service is not started or fails to start. -**Procedure** +**Solution** Check whether the service is started normally and obtain the service again. @@ -52,7 +52,7 @@ Discovery invalid. The last discovery service is still in progress. -**Procedure** +**Solution** Wait until the last discovery service is complete and call the discovery API again. @@ -66,6 +66,6 @@ Publish invalid. The last publish service is still in progress. -**Procedure** +**Solution** Wait until the last publish service is complete and call the publish API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-display.md b/en/application-dev/reference/errorcodes/errorcode-display.md index f86b0b10736c407cefb288e317288c66a9fd5a07..1a0fb96dbb909a8915569e0daf8f7aa497425038 100644 --- a/en/application-dev/reference/errorcodes/errorcode-display.md +++ b/en/application-dev/reference/errorcodes/errorcode-display.md @@ -2,42 +2,53 @@ ## 1400001 Invalid Display or Screen **Error Message** + Invalid display or screen. **Description** + This error code is reported when an invalid display, including a virtual screen, is operated. **Possible Causes** 1. The virtual screen has not been created. 2. The virtual screen has been destroyed. -**Procedure** +**Solution** + 1. Before operating the virtual screen, check whether the virtual screen has been created. 2. Check whether the virtual screen has been destroyed. ## 1400002 Unauthorized Operation **Error Message** + Unauthorized operation. **Description** + This error code is reported when the API does not have the required permissions to operate an object. **Possible Causes** + The virtual screen object of another process is operated. -**Procedure** +**Solution** + Check whether unauthorized operations are performed on the object of another process. If yes, delete the operations. ## 1400003 Abnormal Display Manager Service **Error Message** + This display manager service works abnormally. **Description** + This error code is reported when the display manager service is abnormal. **Possible Causes** + 1. The display manager service is not started normally. 2. The bottom-layer graphics synthesis and rendering are abnormal. -**Procedure** -Try again later or restart the device. +**Solution** + +Try again later or restart the device. \ No newline at end of file diff --git a/en/application-dev/reference/errorcodes/errorcode-huks.md b/en/application-dev/reference/errorcodes/errorcode-huks.md index 7bab2f0be7353cefecbe458b6435aaaf213429d4..66409a6381a59d5dfe3cace75fe90ca19cb8f52d 100644 --- a/en/application-dev/reference/errorcodes/errorcode-huks.md +++ b/en/application-dev/reference/errorcodes/errorcode-huks.md @@ -10,7 +10,7 @@ The API is supported, but certain features in the API, such as the algorithm, are not supported. -**Procedure** +**Solution** Modify the parameters and use the features supported. @@ -23,7 +23,7 @@ Failed to obtain `${messageInfo}`. It is not set in ParamSet. The key parameter is not set. -**Procedure** +**Solution** 1. Determine the missing parameter from the error message. 2. Set the parameter. @@ -38,7 +38,7 @@ Invalid `${messageInfo}`. An invalid parameter is found. -**Procedure** +**Solution** 1. Determine the invalid parameter from the error message. 2. Correct the invalid parameter. @@ -55,7 +55,7 @@ Failed to write the file. The file operation failed. -**Procedure** +**Solution** 1. Check whether the disk space is used up and whether the file system is abnormal. 2. Clear the disk space. @@ -72,7 +72,7 @@ Failed to obtain messages from IPC. IPC failed. -**Procedure** +**Solution** Locate and rectify the IPC failure. @@ -89,7 +89,7 @@ The algorithm library operation fails. The possible causes include the following 1. The encryption and decryption on the algorithm library failed due to incorrect ciphertext data. 2. Incorrect key parameters exist. -**Procedure** +**Solution** 1. Check and correct the ciphertext data. 2. Check and correct the key parameters. @@ -107,7 +107,7 @@ The possible causes include the following: 1. The key is configured with the user access control attribute and becomes invalid after the password is cleared. 2. The key is configured with the user access control attribute and becomes invalid after a new biometric feature is enrolled. -**Procedure** +**Solution** 1. Locate the cause of the authentication failure based on the log. 2. If the authentication fails due to the access control attribute configured, the key cannot be used any more. @@ -122,7 +122,7 @@ The authentication token verification failed. The authentication token verification failed due to an incorrect challenge value. -**Procedure** +**Solution** 1. Check whether the challenge for userIAM authentication is correctly assembled. 2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication. @@ -137,7 +137,7 @@ The Authentication token timed out. The authentication failed because the authentication token timed out. -**Procedure** +**Solution** The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected. @@ -151,7 +151,7 @@ The number of key operation sessions has reached the limit. The number of concurrent key operation sessions has reached the maximum (15). -**Procedure** +**Solution** 1. Check whether there are multiple key session operations (**init** operations) for the same application. If yes, modify the code to avoid concurrent invoking. 2. If the key operation sessions are set up for different applications, wait until the sessions are released. @@ -166,7 +166,7 @@ The entity does not exist. The key corresponding to the key alias does not exist. -**Procedure** +**Solution** 1. Check whether the key alias is misspelled. 2. Check whether the key corresponding to the key alias is successfully generated. @@ -181,7 +181,7 @@ External error `${messageInfo}`. An external error, such as a hardware fault or file error occurs. -**Procedure** +**Solution** Provide the error code and log information to the related party. @@ -195,7 +195,7 @@ The credential does not exist. The credential, such as the PIN, fingerprint, or face image, is not enrolled. -**Procedure** +**Solution** Enroll the credential or change the authentication type bound to the key. @@ -209,7 +209,7 @@ Memory is insufficient. The system memory is insufficient. -**Procedure** +**Solution** Release memory or restart the device. @@ -223,6 +223,6 @@ Failed to call the `${messageInfo}` service to do `${messageInfo}`. The called system service has not started. -**Procedure** +**Solution** Wait for the system service to start and call the API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-promptAction.md b/en/application-dev/reference/errorcodes/errorcode-promptAction.md new file mode 100644 index 0000000000000000000000000000000000000000..15266ac738f9f330d1327b517e8494dce04971d1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-promptAction.md @@ -0,0 +1,19 @@ +# promptAction Error Codes + +## 100001 Internal Error + +**Error Message** + +Internal error. + +**Description** + +This error code is reported when an internal error that cannot be rectified by developers occurs. The internal error type is included in the error information. + +**Possible Causes** + +The operation for obtaining the rendering engine or parsing parameters fails. + +**Solution** + +NA diff --git a/en/application-dev/reference/errorcodes/errorcode-router.md b/en/application-dev/reference/errorcodes/errorcode-router.md new file mode 100644 index 0000000000000000000000000000000000000000..9a993e71c1fbcac9d28d8039b674770c1175174d --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-router.md @@ -0,0 +1,73 @@ +# Router Error Codes + +## 100001 Internal Error + +**Error Message** + +Internal error. + +**Description** + +This error code is reported when an internal error that cannot be rectified by developers occurs. The internal error type is included in the error information. + +**Possible Causes** + +The operation for obtaining the rendering engine or parsing parameters fails. + +**Solution** + +NA + +## 100002 Incorrect URI + +**Error Message** + +Uri error. The uri of router is not exist. + +**Description** + +This error code is reported when the URI of the page to redirect is incorrect or does not exist. + +**Possible Causes** + +The entered URI is incorrect or does not exist. + +**Solution** + +Ensure that the URI is correct. + +## 100003 Too Many Pages Are Pushed into the Page Stack + +**Error Message** + +Page stack error. The pages are pushed too much. + +**Description** + +This error code is reported when more than 32 pages are pushed into the page stack. + +**Possible Causes** + +Too many pages are pushed. + +**Solution** + +Delete unnecessary or invalid pages. + +## 200002 Incorrect URI + +**Error Message** + +Uri error. The uri of router is not exist. + +**Description** + +This error code is reported when the URI of the page to be used for replacement is incorrect or does not exist. + +**Possible Causes** + +The entered URI is incorrect or does not exist. + +**Solution** + +Ensure that the URI is correct. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensor.md b/en/application-dev/reference/errorcodes/errorcode-sensor.md index 571156ec00328b0ba564cd6174e6fb81aa5154b1..3e4170b55dcd6235031e1c4aea41b048a6a883da 100644 --- a/en/application-dev/reference/errorcodes/errorcode-sensor.md +++ b/en/application-dev/reference/errorcodes/errorcode-sensor.md @@ -1,6 +1,6 @@ # Sensor Error Codes -## 14500101 Service exception. +## 14500101 Service Exception **Error Message** @@ -14,7 +14,7 @@ This error code is reported if the HDI service is abnormal when the **on**, **on The HDI service is abnormal. -**Procedure** +**Solution** 1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. 2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensors.md b/en/application-dev/reference/errorcodes/errorcode-sensors.md new file mode 100644 index 0000000000000000000000000000000000000000..155ff9263f550685e1b8dfc47016acc242ab5c9c --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-sensors.md @@ -0,0 +1,40 @@ +# Pan-Sensor Error Codes + +## 14500101 Service exception. + +### Error information + +Service exception. + +### Description + +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. + +### Possible Causes + +The HDI service is abnormal. + +### Procedure + +1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. +2. If the operation fails for three consecutive times, stop the attempt. You can also attempt to obtain the sensor list to check for device availability. + +## 14600101 Device operation failed. + +### Error Message + +Device operation failed. + +### Description + +This error code is reported if the HDI service is abnormal or the device is occupied when the **startVibration** interface of the vibrator module is called. + +### Possible Causes + +1. The HDI service is abnormal. +2. The device is occupied. + +### Procedure + +1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. +2. Set a higher priority for the vibrator. diff --git a/en/application-dev/reference/errorcodes/errorcode-vibrator.md b/en/application-dev/reference/errorcodes/errorcode-vibrator.md index f5dc329c1e96d945f76c7625b365a53fe50477b4..f04a47bb5f5578d61eafa9b75ae650acdab41747 100644 --- a/en/application-dev/reference/errorcodes/errorcode-vibrator.md +++ b/en/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -15,7 +15,7 @@ This error code is reported if the HDI service is abnormal or the device is occu 1. The HDI service is abnormal. 2. The device is occupied. -**Procedure** +**Solution** 1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. 2. Set a higher priority for the vibrator. diff --git a/en/application-dev/reference/errorcodes/errorcode-window.md b/en/application-dev/reference/errorcodes/errorcode-window.md index 9e61c92b592c2e155ac6757f8e1dee4a01d762e9..5c034e88468111e4a67ad56da737ee62d8cbf536 100644 --- a/en/application-dev/reference/errorcodes/errorcode-window.md +++ b/en/application-dev/reference/errorcodes/errorcode-window.md @@ -2,78 +2,101 @@ ## 1300001 Repeated Operation **Error Message** + Repeated operation. **Description** + This error code is reported when a repeated operation is performed. **Possible Causes** + The window to create already exists. -**Procedure** +**Solution** + Before creating a window, check whether the window already exists. If it already exists, use it directly. ## 1300002 Abnormal Window State **Error Message** + This window state is abnormal. **Description** + This error code is reported when you operate a window in an abnormal state, for example, a window that has been destroyed. **Possible Causes** + The window has been destroyed when being operated. -**Procedure** +**Solution** + Before operating the window, check whether it exists. ## 1300003 Abnormal Window Manager Service **Error Message** + This window manager service works abnormally. **Description** + This error code is reported when the window manager service is abnormal. **Possible Causes** + The internal services of the window are not started normally. -**Procedure** +**Solution** + Try again later or restart the device. ## 1300004 Unauthorized Operation **Error Message** + Unauthorized operation. **Description** + This error code is reported when the API does not have the required permissions to operate an object. **Possible Causes** + The window object of another process is operated. -**Procedure** +**Solution** + Check whether unauthorized operations are performed on the object of another process. If yes, delete the operations. ## 1300005 Abnormal Window Stage **Error Message** + This window stage is abnormal. **Description** + This error code is reported when you operate a window stage in the abnormal state, for example, a window stage that has been destroyed. **Possible Causes** + The window stage has been destroyed when being operated. **Procedure** + Before operating a window stage, check whether it exists. ## 1300006 Abnormal Window Context **Error Message** + This window context is abnormal. **Description** + This error code is reported when you operate a window context in the abnormal state, for example, a window context that has been destroyed. **Possible Causes** + The window context has been destroyed when being operated. -**Procedure** -Before operating the window context, check whether it exists. +**Solution** +Before operating the window context, check whether it exists. \ No newline at end of file diff --git a/en/application-dev/reference/errorcodes/errorcode-zlib.md b/en/application-dev/reference/errorcodes/errorcode-zlib.md new file mode 100644 index 0000000000000000000000000000000000000000..ea2b330abea46f7f9a9eebfff7e427cf57197cc2 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-zlib.md @@ -0,0 +1,40 @@ +# zlib Error Codes + +## 900001 Invalid Source File + +**Error Message** + +The input source file is invalid. + +**Description** + +This error code is reported when the source file passed in the **compress** or **decompress** API is invalid. + +**Possible Causes** + +When the **compress** API is called, the file to compress does not exist. When the **decompress** API is called, the file to decompress does not exist. + +**Procedure** + +1. Check whether the source file exists. +2. Check whether the path of the source file exists and whether the path is the correct sandbox path. + +## 900002 Invalid Destination File + +**Error Message** + +The input destination file is invalid. + +**Description** + +This error code is reported when the destination file passed in the **compress** or **decompress** API is invalid. + +**Possible Causes** + +1. When the **compress** API is called, the passed destination file path is invalid, for example, a non-exist sandbox path. +2. When the **decompress** API is called, the destination folder does not exist. + +**Procedure** + +1. Check whether the destination file path is correct. If not, enter the correct sandbox path. +2. Check whether the destination folder exists. If not, create the folder. diff --git a/en/application-dev/reference/errorcodes/errorcodes-multimodalinput.md b/en/application-dev/reference/errorcodes/errorcodes-multimodalinput.md new file mode 100644 index 0000000000000000000000000000000000000000..bca5dbf90bcec2b16c36c45edee7576ef50f3358 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcodes-multimodalinput.md @@ -0,0 +1,43 @@ +# Screen Hopping Error Codes + +## 4400001 Incorrect Target Device Descriptor + +**Error Message** + +Incorrect descriptor for the target device. + +**Description** + +This error code is reported if an invalid device descriptor is passed to the screen hopping API. + +**Possible Causes** + +1. The target device does not exist, or the device is not networked. +2. The target device descriptor is empty. + +**Solution** + +1. Check whether the target device for screen hopping is correctly networked with the local device. +2. Set the target device descriptor correctly. + +## 4400002 Input Device Operation Failed + +**Error Message** + +Failed to operate the input device. + +**Description** + +This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. + +**Possible Causes** + +1. When screen hopping is initiated, the local device is in the hopped state. +2. When screen hopping is disabled, the local device is in the free state. +3. When screen hopping is disabled, the local device is in the hopping state. + +**Solution** + +1. When initiating screen hopping, make sure that the local device is not in the hopped state. +2. When disabling screen hopping, make sure that the local device is not in the free state. +3. When disabling screen hopping, make sure that the local device is not in the hopping state. diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 8116d311b340c020f1ac5c07e6aa0269fa690a2d..9f4a69cf61b3e6967575bdfd8e60660b8481af19 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -4,10 +4,9 @@ - Getting Started - [Preparations](quick-start/start-overview.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 ArkTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with ArkTS 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) @@ -176,6 +175,7 @@ - Access Control - [Access Control Overview](security/accesstoken-overview.md) - [Access Control Development](security/accesstoken-guidelines.md) + - [Permission Verification Guide](security/permission-verify-guidelines.md) - [Permission List](security/permission-list.md) - User Authentication - [User Authentication Overview](security/userauth-overview.md) @@ -265,6 +265,7 @@ - [Drawing Development](napi/drawing-guidelines.md) - [Raw File Development](napi/rawfile-guidelines.md) - [Native Window Development](napi/native-window-guidelines.md) + - [Using MindSpore Lite for Model Inference](napi/mindspore-lite-guidelines.md) - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials @@ -579,6 +580,7 @@ - [@ohos.application.formInfo](reference/apis/js-apis-formInfo.md) - [@ohos.application.formProvider](reference/apis/js-apis-formprovider.md) - [@ohos.application.missionManager](reference/apis/js-apis-missionManager.md) + - [@ohos.application.quickFixManager](reference/apis/js-apis-application-quickFixManager.md) - [@ohos.application.Want](reference/apis/js-apis-application-Want.md) - [@ohos.continuation.continuationManager](reference/apis/js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager](reference/apis/js-apis-continuation-continuationManager.md) @@ -610,6 +612,7 @@ - [ApplicationInfo](reference/apis/js-apis-bundle-ApplicationInfo.md) - [BundleInfo](reference/apis/js-apis-bundle-BundleInfo.md) - [BundleInstaller](reference/apis/js-apis-bundle-BundleInstaller.md) + - [BundleStatusCallback](reference/apis/js-apis-Bundle-BundleStatusCallback.md) - [CustomizeData](reference/apis/js-apis-bundle-CustomizeData.md) - [DispatchInfo](reference/apis/js-apis-dispatchInfo.md) - [ElementName](reference/apis/js-apis-bundle-ElementName.md) @@ -618,6 +621,7 @@ - [LauncherAbilityInfo](reference/apis/js-apis-bundle-LauncherAbilityInfo.md) - [Metadata](reference/apis/js-apis-bundle-Metadata.md) - [ModuleInfo](reference/apis/js-apis-bundle-ModuleInfo.md) + - [PackInfo](reference/apis/js-apis-bundle-PackInfo.md) - [PermissionDef](reference/apis/js-apis-bundle-PermissionDef.md) - [RemoteAbilityInfo](reference/apis/js-apis-bundle-remoteAbilityInfo.md) - [ShortcutInfo](reference/apis/js-apis-bundle-ShortcutInfo.md) @@ -631,6 +635,7 @@ - [@ohos.animation.windowAnimationManager](reference/apis/js-apis-windowAnimationManager.md) - [@ohos.display](reference/apis/js-apis-display.md) - [@ohos.effectKit](reference/apis/js-apis-effectKit.md) + - [@ohos.graphics.colorSpaceManager](reference/apis/js-apis-colorSpaceManager.md) - [@ohos.screen](reference/apis/js-apis-screen.md) - [@ohos.screenshot](reference/apis/js-apis-screenshot.md) - [@ohos.window](reference/apis/js-apis-window.md) @@ -677,6 +682,7 @@ - [@ohos.document](reference/apis/js-apis-document.md) - [@ohos.environment](reference/apis/js-apis-environment.md) - [@ohos.fileio](reference/apis/js-apis-fileio.md) + - [@ohos.filemanagement.userfile_manager](reference/apis/js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md) - [@ohos.statfs](reference/apis/js-apis-statfs.md) @@ -692,8 +698,13 @@ - [@ohos.telephony.sms](reference/apis/js-apis-sms.md) - Network Management - [@ohos.net.connection](reference/apis/js-apis-net-connection.md) + - [@ohos.net.ethernet](reference/apis/js-apis-net-ethernet.md) - [@ohos.net.http](reference/apis/js-apis-http.md) + - [@ohos.net.policy](reference/apis/js-apis-net-policy.md) + - [@ohos.net.sharing](reference/apis/js-apis-net-sharing.md) - [@ohos.net.socket](reference/apis/js-apis-socket.md) + - [@ohos.net.statistics](reference/apis/js-apis-net-statistics.md) + - [@ohos.net.tlsSocket](reference/apis/js-apis-tlsSocket.md) - [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md) - [@ohos.request](reference/apis/js-apis-request.md) - Connectivity @@ -819,7 +830,7 @@ - [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) - [Ability Framework Development](faqs/faqs-ability.md) - [ArkUI (JavaScript) Development](faqs/faqs-ui-js.md) - - [ArkUI (eTS) Development](faqs/faqs-ui-ets.md) + - [ArkUI (ArkTS) Development](faqs/faqs-ui-ets.md) - [Graphics and Image Development](faqs/faqs-graphics.md) - [File Management Development](faqs/faqs-file-management.md) - [Network and Connection Development](faqs/faqs-connectivity.md) diff --git a/en/application-dev/windowmanager/application-window-stage.md b/en/application-dev/windowmanager/application-window-stage.md index 0b074ce93fed6734ef6744c184e0a92b4d5544a9..4388719ee9e5e6b2bce2ddea95bac03d49ea4fc8 100644 --- a/en/application-dev/windowmanager/application-window-stage.md +++ b/en/application-dev/windowmanager/application-window-stage.md @@ -56,9 +56,9 @@ In the stage model, the main window of an application is created and maintained ### How to Develop 1. Obtain the main window. - - Call **getMainWindow** to obtain the main window of the application. - + +Call **getMainWindow** to obtain the main window of the application. + 2. Set the properties of the main window. You can set multiple properties of the main window, such as the background color, brightness, and whether the main window is touchable. The code snippet below uses the **touchable** property as an example. @@ -112,11 +112,11 @@ You can create an application subwindow, such as a dialog box, and set its prope ### How to Develop 1. Create or obtain a subwindow. - - Call **createSubWindow** to create a subwindow. - - Call **getSubWindow** to obtain a subwindow. - + +Call **createSubWindow** to create a subwindow. + +Call **getSubWindow** to obtain a subwindow. + 2. Set the properties of the subwindow. After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness. @@ -132,11 +132,12 @@ You can create an application subwindow, such as a dialog box, and set its prope ```ts import Ability from '@ohos.application.Ability' + let windowStage_ = null; + let sub_windowClass = null; class MainAbility extends Ability { - onWindowStageCreate(windowStage) { + showSubWindow() { // 1. Create a subwindow. - let sub_windowClass = null; - windowStage.createSubWindow("mySubWindow", (err, data) => { + windowStage_.createSubWindow("mySubWindow", (err, data) => { if (err.code) { console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); return; @@ -144,7 +145,7 @@ You can create an application subwindow, such as a dialog box, and set its prope sub_windowClass = data; console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); // 1. Obtain an available subwindow. - windowStage.getSubWindow((err, data) => { + windowStage_.getSubWindow((err, data) => { if (err.code) { console.error('Failed to obtain the subWindow. Cause:' + JSON.stringify(err)); return; @@ -183,19 +184,30 @@ You can create an application subwindow, such as a dialog box, and set its prope console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); }); }); - // 4. Destroy the subwindow when a click event outside the window is detected. - sub_windowClass.on('touchOutside', () => { - console.info('touch outside'); - sub_windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); - }); - }); }) } + + destroySubWindow() { + // 4. Destroy the subwindow when it is no longer needed (depending on the service logic). + sub_windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + }); + } + + onWindowStageCreate(windowStage) { + windowStage_ = windowStage; + // Create the subwindow when it is needed, for example, when a click event occurs in the main window. Calling onWindowStageCreate is not always necessary. The code here is for reference only. + this.showSubWindow(); + } + + onWindowStageDestroy() { + // Destroy the subwindow when it is no longer needed, for example, when the Close button in the subwindow is clicked. Calling onWindowStageDestroy is not always necessary. The code here is for reference only. + this.destroySubWindow(); + } }; ``` @@ -208,9 +220,9 @@ To create a better video watching and gaming experience, you can use the immersi ### How to Develop 1. Obtain the main window. - - Call **getMainWindow** to obtain the main window of the application. - + +Call **getMainWindow** to obtain the main window of the application. + 2. Implement the immersive effect. You can use any of the following methods: - Method 1: Call **setFullScreen** to set the main window to be displayed in full screen. In this case, the navigation bar and status bar are hidden. - Method 2: Call **setSystemBarEnable** to hide the navigation bar and status bar. @@ -298,13 +310,13 @@ A floating window is created based on an existing task. It is always displayed i ### How to Develop 1. Apply for permissions. - - To create a floating window (of the **WindowType.TYPE_FLOAT** type), you must configure the **ohos.permission.SYSTEM_FLOAT_WINDOW** permission in the **requestPermissions** field of the **module.json5** file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). - + +To create a floating window (of the **WindowType.TYPE_FLOAT** type), you must configure the **ohos.permission.SYSTEM_FLOAT_WINDOW** permission in the **requestPermissions** field of the **module.json5** file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + > **NOTE** > > If the task for creating the floating window is reclaimed by the system, the floating window will no longer be displayed. If you want the floating window to be displayed in such a case, apply for a [continuous task](../task-management/background-task-overview.md). - + ```json { "module": { @@ -320,9 +332,9 @@ A floating window is created based on an existing task. It is always displayed i } ] } - } +} ``` - + 2. Create a floating window. Call **window.create** to create a floating window. @@ -386,16 +398,13 @@ A floating window is created based on an existing task. It is always displayed i console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); }); }); - // 5. Destroy the floating window when a click event outside the window is detected. - windowClass.on('touchOutside', () => { - console.info('touch outside'); - windowClass.destroy((err, data) => { - if (err.code) { - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); - }); + // 5. Destroy the floating window when it is no longer needed (depending on the service logic). + windowClass.destroy((err, data) => { + if (err.code) { + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); }); }); } diff --git a/en/application-dev/windowmanager/system-window-stage.md b/en/application-dev/windowmanager/system-window-stage.md index d3870d665bb39be5c4b454f6fd5e10b189758ea0..e4e8cf63fdf5f03e2dbbad868ee42be9d924f440 100644 --- a/en/application-dev/windowmanager/system-window-stage.md +++ b/en/application-dev/windowmanager/system-window-stage.md @@ -2,7 +2,11 @@ ## Overview -In the stage model, system applications are allowed to create and manage system windows, including the volume bar, wallpaper, notification panel, status bar, and navigation bar. For details about the supported system window types, see "WindowType" in [Window](../reference/apis/js-apis-window.md). +In the stage model, system applications are allowed to create and manage system windows, including the volume bar, wallpaper, notification panel, status bar, and navigation bar. For details about the supported system window types, see [WindowType in Window](../reference/apis/js-apis-window.md#windowtype7). + +> **NOTE** +> +> This document involves the use of system APIs. Use the full SDK for development. For details, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). ## Available APIs @@ -11,7 +15,7 @@ For details, see [Window](../reference/apis/js-apis-window.md). | Instance| API| Description| | -------- | -------- | -------- | -| Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void | Creates a system window when `ctx` is [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md).
-`ctx`: application context.
-`type`: window type. | +| Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void | Creates a system window when **ctx** is [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md).
- **ctx**: application context.
- **type**: window type.| | Window | resetSize(width: number, height: number, callback: AsyncCallback<void>): void | Changes the window size.| | Window | moveTo(x: number, y: number, callback: AsyncCallback<void>): void | Moves this window.| | Window | loadContent(path: string, callback: AsyncCallback<void>): void | Loads the page content to this window.| @@ -29,7 +33,7 @@ This section uses the volume bar as an example to describe the steps for system 1. Create a system window. - In the case of [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md), call `window.create` to create a system window of the volume bar type. + In the case of [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md), call **window.create** to create a system window of the volume bar type. 2. Set the properties of the system window. @@ -37,11 +41,11 @@ This section uses the volume bar as an example to describe the steps for system 3. Load content for the system window and show it. - You can call `loadContent` and `show` to load and display the content in the volume bar window. + You can call **loadContent** and **show** to load and display the content in the volume bar window. 4. Hide or destroy the system window. - When the volume bar window is no longer needed, you can call `hide` or `destroy` to hide or destroy it. + When the volume bar window is no longer needed, you can call **hide** or **destroy** to hide or destroy it. ```ts import ExtensionContext from '@ohos.application.ServiceExtensionAbility'; diff --git a/en/contribute/FAQ.md b/en/contribute/FAQ.md index ec7ef6d5de3e99875995e98a2e780ee520506652..64f2375abe23b2735f77fc72d74f39826cc2d6cc 100644 --- a/en/contribute/FAQ.md +++ b/en/contribute/FAQ.md @@ -1,6 +1,6 @@ -# FAQs +# FAQs -## How Do I Create PRs at the Same Time If Multiple Code Repositories Have Compilation Dependencies? +## How Do I Create PRs at the Same Time If Multiple Code Repositories Have Compilation Dependencies? During the development of the operating system \(OS\), it is common that multiple code repositories have compilation dependencies. Therefore, the PRs need to be created and merged at the same time. For this reason, Gitee uses issues as the association identifiers for code repositories with dependency dependencies to commit the PRs. Follow the operations below: @@ -8,11 +8,11 @@ During the development of the operating system \(OS\), it is common that multipl 2. Associate PRs need to be built and merged at the same time with the issue. For details, visit [https://gitee.com/help/articles/4142](https://gitee.com/help/articles/4142). 3. After the build is triggered, the build center identifies the PRs associated with the same issue, downloads the build, and merges the PRs into the code library after the code is approved. -## Sign-off-by Operations +## Sign-off-by Operations #### How to Add signoff Records in Commits? -Execute the **git commit -s **or **git commit –signo** command to submit signoff records. +Execute the **git commit -s **or **git commit –sigoff** command to submit signoff records. #### How to Add a signoff record to the Previous Commit? @@ -20,7 +20,7 @@ Execute the **git commit --amend --signoff** command. For more options about commit, see [https://](https://git-scm.com/docs/git-commit)[git-scm.com/docs/git-commit](https://git-scm.com/docs/git-commit). -## Handling Exceptions of DCO Verification +## Handling Exceptions of DCO Verification After developers submit Pull Request, commenting "**start build**" in the PR will trigger the gated commit. In this sense, you should consider: @@ -61,11 +61,11 @@ The possible causes for a verification failure include: Enter **check dco** in the Pull Requests comment box and click **Comment**. The system will check the DCO signing status again. -## Rollback +## Rollback Visit [https://gitee.com/help/articles/4195](https://gitee.com/help/articles/4195). -## Resolving Merge Conflicts +## Resolving Merge Conflicts Visit [https://gitee.com/help/articles/4194](https://gitee.com/help/articles/4194). diff --git a/en/contribute/OpenHarmony-Java-secure-coding-guide.md b/en/contribute/OpenHarmony-Java-secure-coding-guide.md index a5acff2b48e22d91de6b38fe95940a652ad85d87..296b2f687eb46961de7e7b65a7bb6160cae772cb 100644 --- a/en/contribute/OpenHarmony-Java-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-Java-secure-coding-guide.md @@ -1882,7 +1882,7 @@ BaseClass obj = (BaseClass) objClass.newInstance(); obj.doSomething(); ``` -This noncompliant code example uses an external class name to directly construct an object through reflection. An ill-intentioned user can construct a malicious `BaseClass` subclass object, take control over a `BaseClass` subclass, and execute arbitrary code in the `doSomething()` method of the subclass. An ill-intentioned user can further use the code to execute the default constructor of any class. Even if an `ClassCastException` is thrown in class conversion, the code in the constructor is executed as expected by the ill-intentioned user. +This noncompliant code example uses an external class name to directly construct an object through reflection. An ill-intentioned user can construct a malicious `BaseClass` subclass object, take control over a `BaseClass` subclass, and execute arbitrary code in the `doSomething()` method of the subclass. An ill-intentioned user can further use the code to execute the default constructor of any class. Even if a `ClassCastException` is thrown in class conversion, the code in the constructor is executed as expected by the ill-intentioned user. **\[Compliant Code Example]** diff --git a/en/contribute/OpenHarmony-JavaScript-coding-style-guide.md b/en/contribute/OpenHarmony-JavaScript-coding-style-guide.md index ff9bc6ddcaaf7395604a2a5303cda93d06cf1d08..939378ea6466d31a2d0bf911424cad79d17e9605 100755 --- a/en/contribute/OpenHarmony-JavaScript-coding-style-guide.md +++ b/en/contribute/OpenHarmony-JavaScript-coding-style-guide.md @@ -32,7 +32,7 @@ The style consistency principle is preferred in the following situations: **Example:**`username`,`account` #### Rule 1.2 Use abbreviations as few as possible, except for common words or professional words. For example, `context` can be shortened to `ctx`, `request` can be shortened to `req`, and `response` can be shortened to `resp`. - + **Note:** Complete spelling of words can avoid unnecessary misunderstanding. **Exceptions:** The variable name of the cyclic condition can be ` i` or ` j` in the cyclic language. @@ -329,7 +329,7 @@ console.log(`${username}'s birthday is ${birthday}`); **Example:** ```javascript -let message = 'wolrd'; +let message = 'world'; console.log(message); ``` @@ -337,7 +337,7 @@ console.log(message); #### Rule 3.1 When declaring a variable, use the keyword `var`, `let`, or `const` to prevent the variable from being exposed to the global scope. -**Note:** If the keyword `var`, `let`, or `const` is not used to declare a variable, the variable will be exposed to the global scope, which may overwrite the variable with the same name in the global scope. As a result, the GC cannot effectively reclaim the memory. In addition, when a variable contains sensitive information, exposuring to the global scope may result in information leakage. ** Use `const` instead of `var` for all references; Use `let` instead of `var` if you need a variable reference.** Because the scope of `const` and `let` is smaller, writing code is easier to control. Const ensures that the reference cannot be re-assigned. The pointer referenced by const is immutable, and an error will be reported during re-assignment, avoiding overwriting. +**Note:** If the keyword `var`, `let`, or `const` is not used to declare a variable, the variable will be exposed to the global scope, which may overwrite the variable with the same name in the global scope. As a result, the GC cannot effectively reclaim the memory. In addition, when a variable contains sensitive information, exposing to the global scope may result in information leakage. ** Use `const` instead of `var` for all references; Use `let` instead of `var` if you need a variable reference.** Because the scope of `const` and `let` is smaller, writing code is easier to control. Const ensures that the reference cannot be re-assigned. The pointer referenced by const is immutable, and an error will be reported during re-assignment, avoiding overwriting. **Counterexample:** diff --git a/en/contribute/OpenHarmony-c-coding-style-guide.md b/en/contribute/OpenHarmony-c-coding-style-guide.md index bd2fdf2bdac82f3ecabfaef2759fd587542132eb..75f6e5bcf0915c12a65912a2daf48229ef507fe7 100755 --- a/en/contribute/OpenHarmony-c-coding-style-guide.md +++ b/en/contribute/OpenHarmony-c-coding-style-guide.md @@ -1054,7 +1054,7 @@ DoSomething(); DoSomething(); ``` -Leave at least one space between the code and the comment on the right. No more than four spaces is recommended. +Leave at least one space between the code and the comment on the right. No more than four spaces are recommended. You can use the extended Tab key to indent 1-4 spaces. @@ -1561,7 +1561,7 @@ Note: Whether to declare the pointer parameter as `const` depends on the functio ### Rec 5.6 Include no more than 5 parameters in a function. -If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increases the workload for testing. +If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increase the workload for testing. The number of parameters in a function must not exceed 5. If the number of parameters exceeds 5, consider the following: @@ -2029,7 +2029,7 @@ However, due to invalid initialization, the defect of placing "UseData" before " Therefore, simple code should be written to initialize variables or memory blocks as required. -The C99 does not limit the definition position of local variables to before the first statement in a function. That is, a variable can now be defined close to a variable. +The C99 does not limit the definition position of local variables before the first statement in a function. That is, a variable can now be defined close to a variable. This concise approach not only limits the scope of the variable scope, but also solves the problem of how to initialize the variable when it is defined. @@ -2080,7 +2080,7 @@ if (v < MAX) ... There are special cases: for example, the expression `if (MIN < v && v < MAX)` is used to check for a range. This first constant should be placed on the left. -You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. +You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that code is readable. ### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. diff --git a/en/contribute/OpenHarmony-cpp-coding-style-guide.md b/en/contribute/OpenHarmony-cpp-coding-style-guide.md index ad0fd531bda1fe47201a2dd1e68a645d6c3b92be..8e3051e2fce6cadecd258b61bacb1450e4d31023 100755 --- a/en/contribute/OpenHarmony-cpp-coding-style-guide.md +++ b/en/contribute/OpenHarmony-cpp-coding-style-guide.md @@ -1,43 +1,49 @@ # C++ Coding Style Guide -## Purpose +## Purpose Rules are not perfect. They might disable useful features in specific situations and therefore affect code implementation. However, the purpose of developing rules is to get more benefits for most programmers. If a rule cannot be followed in your team operation, we can improve the rule together. + Before referring to this coding style guide, you are expected to have the following basic capabilities of the C++programming language: + 1. Have a general knowledge of ISO standards for C++. 2. Be familiar with the basic features of C++, including those of C++ 03/11/14/17. 3. Have a general knowledge of the C++ standard library. -## General Principles +## General Principles Code must meet the requirements for readability, maintainability, security, reliability, testability, efficiency, and portability while ensuring functionality correctness. -## Key Points +## Key Points 1. C++ programming style, such as naming and typesetting. 2. C++ modular design, including how to design header files, classes, interfaces, and functions. 3. Best practices of C++ features, including constants, type casting, resource management, and templates. 4. Best practices of modern C++, including conventions that can improve code maintainability and reliability in C++ 11/14/17. 5. This coding style guide is preferentially applicable to C++17. -## Conventions +## Conventions **Rule**: Conventions that must be followed during programming. **Rec**: Conventions that must be considered during programming. This document is applicable to standard C++ versions (C++ 03/11/14/17) unless otherwise specified. -## Exceptions +## Exceptions It is necessary to understand the reason for these conventions and try to comply with them, no matter if they are rules or recommendations. + However, some rules and recommendations have exceptions. The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for the exception. + Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare. -The style consistency principle is preferred in the following case: +The style consistency principle is preferred in the following case: + When you modify open-source or third-party code, comply with their respective code specifications. -# 2 Naming -## General Naming Rules +# 2 Naming +## General Naming Rules __CamelCase__ CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. + There are two conventions: UpperCamelCase and lowerCamelCase. @@ -49,12 +55,15 @@ There are two conventions: UpperCamelCase and lowerCamelCase. | Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_)| Note: + **Constant** in the above table refers to the variable that is of the basic data type, enumeration type, and string type and modified by **const** or **constexpr** under the global scope, the namespace scope, and the scope of a static member of a class, excluding arrays and other variables. + **Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style. -## File Naming -### Rule 2.2.1 Use .cpp as the C++ file name extension and .h as the header file name extension. +## File Naming +### Rule 2.2.1 Use .cpp as the C++ file name extension and .h as the header file name extension. It is recommended that you use .h as the file name extension of a header file so that the header file is compatible with C and C++. + It is recommended that you use .cpp as the file name extension of an implementation file. In this way, you can easily distinguish C++ code from C code. At present, there are some other file name extensions used by programmers: @@ -63,10 +72,11 @@ At present, there are some other file name extensions used by programmers: - Implementation files: .cc, .cxx, .C If your project team uses a specific file name extension, you can continue to use it and keep the style consistent. + This document uses .h and .cpp extensions. -### Rule 2.2.2 Keep C++ file names the same as the class name. +### Rule 2.2.2 Keep C++ file names the same as the class name. The names of the C++ header file and the C++ implementation file must be the same as the class name. Use the unix\_like style and keep the style consistent. For example, if there is a class named DatabaseConnection, the corresponding file names are as follows: @@ -75,7 +85,7 @@ For example, if there is a class named DatabaseConnection, the corresponding fil The naming rules of struct, namespace, and enumeration definition files are similar to the rules above. -## Function Naming +## Function Naming Functions are named in the UpperCamelCase style. Generally, the verb or verb-object structure is used. ```cpp class List { @@ -90,10 +100,12 @@ namespace Utils { } ``` -## Type Naming +## Type Naming Types are named in the UpperCamelCase style. + All types, such as classes, structs, unions, typedefs, and enumerations, use the same conventions. Example: + ```cpp // Classes, structs, and unions class UrlTable { ... @@ -121,8 +133,9 @@ namespace FileUtils { ``` -### Rec 2.4.1 Do not abuse typedef or #define to set alias for the basic data types. +### Rec 2.4.1 Do not abuse typedef or #define to set alias for the basic data types. Unless otherwise specified, do not use typedef or #define to redefine basic data types. + The basic data types found in the `` header file are preferable. | Signed Type | Unsigned Type | Description | @@ -134,7 +147,7 @@ The basic data types found in the `` header file are preferable. | intptr_t | uintptr_t | The signed or unsigned integer type large enough to hold a pointer. | -## Variable Naming +## Variable Naming General variables, including global variables, function parameters, local variables, and member variables, are named in the lowerCamelCase style. ```cpp std::string tableName; // Good: Recommended style. @@ -142,7 +155,7 @@ std::string tablename; // Bad: Forbidden style. std::string path; // Good: When there is only one word, lowerCamelCase (all lowercase) is used. ``` -### Rule 2.5.1 Add the prefix 'g_' to global variables. Do not add a prefix to a static variable. +### Rule 2.5.1 Add the prefix 'g_' to global variables. Do not add a prefix to a static variable. Global variables should be used as little as possible, and special attention should be paid to their use. This prefix highlights global variables so that developers can be more careful when handling them. - Global static variables and global variables are named in the same way. - Static variables in functions and common local variables are named in the same way. @@ -158,7 +171,7 @@ void Func() } ``` -### Rule 2.5.2 Name member variables in classes in the unix\_like style. +### Rule 2.5.2 Name member variables in classes in the unix\_like style. ```cpp class Foo { @@ -168,7 +181,7 @@ private: ``` Use the lowerCamelCase style and do not add prefixes or suffixes to name a member variable of the struct or union type. Keep the naming style consistent with that for a local variable. -## Macro, Constant, and Enum Naming +## Macro, Constant, and Enum Naming Use uppercase letters separated by underscores (\_) for macro names and enumerated values. In the global scope, constants of named and unnamed namespaces and static member constants should be capitalized and separated with underscores (\_).Local constants and ordinary const member variables use the lowerCamelCase naming style. @@ -195,11 +208,11 @@ namespace Utils { ``` -# 3 Formatting +# 3 Formatting -## Line Length +## Line Length -### Rule 3.1.1 Include 120 characters or less in each line. +### Rule 3.1.1 Include 120 characters or less in each line. If the line of code exceeds the permitted length, wrap the line appropriately. Exceptions: @@ -213,16 +226,19 @@ Exceptions: #endif ``` -## Indentation +## Indentation -### Rule 3.2.1 Use spaces to indent and indent 4 spaces at a time. +### Rule 3.2.1 Use spaces to indent and indent 4 spaces at a time. Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. + Currently, almost all integrated development environments (IDEs) support automatic conversion of a Tab input to four spaces. Configure your IDE to support indentation with spaces. -## Braces -### Rule 3.3.1 Use the K&R indentation style. +## Braces +### Rule 3.3.1 Use the K&R indentation style. __K&R style__ + While wrapping a line, the left brace of the function (excluding the lambda statement) starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. + The right brace takes a single line, unless it is followed by the rest of the same statement, such as `while` in the `do` statement, `else` or `else if` in the `if` statement, a comma, or a semicolon. Example: @@ -259,10 +275,10 @@ private: }; ``` -## Function Declarations and Definitions +## Function Declarations and Definitions -### Rule 3.4.1 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. -When a function is declared and defined, the return value type of the function should be in the same line as the function name. When the function parameter list is wrapped, it should be aligned appropriately. +### Rule 3.4.1 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. +When a function is declared and defined, the return value type of the function should be in the same line as the function name. When the function parameter list is wrapped, it should be aligned appropriately. The left parenthesis of a parameter list is always in the same line as the function name. The right parenthesis always follows the last parameter. Example: @@ -292,9 +308,10 @@ ReturnType ReallyReallyReallyReallyLongFunctionName( // The line leng } ``` -## Function Calls -### Rule 3.5.1 A function call parameter list should be placed on one line. When the parameter list exceeds the line length and requires a line break, the parameters should be properly aligned. +## Function Calls +### Rule 3.5.1 A function call parameter list should be placed on one line. When the parameter list exceeds the line length and requires a line break, the parameters should be properly aligned. A function call parameter list should be placed on one line. When the parameter list exceeds the line length and requires a line break, the parameters should be properly aligned. + The left parenthesis always follows the function name, and the right parenthesis always follows the last parameter. The following are examples of proper line breaks: @@ -319,9 +336,9 @@ int result = DealWithStructureLikeParams(left.x, left.y, // A group of relat right.x, right.y); // Another group of related parameters. ``` -## if Statements +## if Statements -### Rule 3.6.1 Use braces to include an if statement. +### Rule 3.6.1 Use braces to include an if statement. We require that all if statements use braces, even if there is only one statement. Reasons: @@ -334,7 +351,7 @@ if (objectIsNotExist) { // Good: Braces are added to a single-line condi return CreateNewObject(); } ``` -### Rule 3.6.2 Place if, else, and else if keywords on separate lines. +### Rule 3.6.2 Place if, else, and else if keywords on separate lines. If there are multiple branches in a conditional statement, they should be placed on separate lines. Good example: @@ -354,8 +371,8 @@ Bad example: if (someConditions) { ... } else { ... } // Bad: The if and else keywords are put on the same line. ``` -## Loop Statements -### Rule 3.7.1 Use braces after loop statements. +## Loop Statements +### Rule 3.7.1 Use braces after loop statements. Similar to if statements, we require that the for and while loop statements contain braces, even if the loop body is empty or there is only one loop statement. ```cpp for (int i = 0; i < someRange; i++) { // Good: Braces are used. @@ -380,8 +397,8 @@ for (int i = 0; i < someRange; i++) while (someCondition) ; // Bad: Using a semicolon here will make people misunderstand that it is a part of the while statement and not the end to it. ``` -## Switch Statements -### Rule 3.8.1 Indent case and default in a switch statement with four spaces. +## Switch Statements +### Rule 3.8.1 Indent case and default in a switch statement with four spaces. The indentation style of the switch statement is as follows: ```cpp switch (var) { @@ -407,10 +424,13 @@ default: // Bad: default is not indented. } ``` -## Expressions +## Expressions + +### Rec 3.9.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line. +A long expression that does not meet the line length requirement must be wrapped appropriately. + +Generally, the expression is wrapped at an operator of a lower priority or a connector, and the operator or connector is placed at the end of the line. -### Rec 3.9.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line. -A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped at an operator of a lower priority or a connector, and the operator or connector is placed at the end of the line. Placing these at the end of a line indicates that the operation is to be continued on the next line. Example: @@ -434,9 +454,9 @@ int sum = longVariableName1 + longVariableName2 + longVariableName3 + int sum = longVariableName1 + longVariableName2 + longVariableName3 + longVariableName4 + longVariableName5 + longVariableName6; // Good: The lines are aligned. ``` -## Variable Assignment +## Variable Assignment -### Rule 3.10.1 Multiple variable definitions and assignment statements cannot be written on one line. +### Rule 3.10.1 Multiple variable definitions and assignment statements cannot be written on one line. Each line should have only one variable initialization statement. It is easier to read and understand. ```cpp @@ -457,10 +477,10 @@ pointX = 1; pointY = 2; // Bad: Multiple variable assignment statements must be ``` Exception: Multiple variables can be declared and initialized in the for loop header, if initialization statement (C++17), and structured binding statement (C++17). Multiple variable declarations in these statements have strong associations. Forcible division into multiple lines may cause problems such as scope inconsistency and separation of declaration from initialization. -## Initialization +## Initialization Initialization is applicable to structs, unions, and arrays. -### Rule 3.11.1 When an initialization list is wrapped, ensure that the line after the break is indented and aligned properly. +### Rule 3.11.1 When an initialization list is wrapped, ensure that the line after the break is indented and aligned properly. If a structure or array initialization list is wrapped, the line after the break is indented with four spaces. Choose the wrap location and alignment style for best comprehension. @@ -471,8 +491,8 @@ const int rank[] = { }; ``` -## Pointers and References -### Rec 3.12.1 The pointer type `*` follows a variable name or type. There can be only one space to the side of it. +## Pointers and References +### Rec 3.12.1 The pointer type `*` follows a variable name or type. There can be only one space to the side of it. Pointer naming: There can be only one space next to `*`. ```cpp int* p = NULL; // Good @@ -487,7 +507,7 @@ Exception: When a variable is modified by const or restrict, `*` cannot follow t const char * const VERSION = "V100"; ``` -### Rec 3.12.2 The reference type `&` follows a variable name or type. There can be only one space to the side of it. +### Rec 3.12.2 The reference type `&` follows a variable name or type. There can be only one space to the side of it. Reference naming: There can be only one space around `&`. ```cpp int i = 8; @@ -496,17 +516,17 @@ int& p = i; // Good int &p = i; // Good int*& rp = pi; // Good: The reference type `*&` follows the type. int *&rp = pi; // Good: The reference type `*&` follows the variable name. -int* &rp = pi; // Good: The pointer type `*` follows the type and the eference type `&` follows the variable name. +int* &rp = pi; // Good: The pointer type `*` follows the type and the reference type `&` follows the variable name. int & p = i; // Bad int&p = i; // Bad ``` -## Compilation Preprocessing -### Rule 3.13.1 Place a number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. +## Compilation Preprocessing +### Rule 3.13.1 Place a number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body. -### Rule 3.13.2 Do not use macros. +### Rule 3.13.2 Do not use macros. Macros do not obey scope, type system, and other rules, and may easily lead to issues. Avoid macro definitions wherever possible. If you must use macros, give them unique names. In C++, there are many ways to avoid using macros: - Use `const` or `enum` to define constants that are easy to understand. @@ -515,12 +535,14 @@ In C++, there are many ways to avoid using macros: - Use the `template` function to handle multiple types. Macros can be used in scenarios such as header guards, conditional compilation, and logging. -### Rule 3.13.3 Do not use macros to represent constants. +### Rule 3.13.3 Do not use macros to represent constants. Macros involve simple text replacement, which is completed during preprocessing. When an error occurs, the macro value is reported without the macro name. During tracing and debugging, the macro name is not displayed either. Besides, macros do not have type checking or scopes. -### Rule 3.13.4 Do not use function-like macros. +### Rule 3.13.4 Do not use function-like macros. Before defining a function-like macro, consider whether it can be replaced with a function. If yes, you are advised to use a function for replacement. + The disadvantages of the function-like macro are as follows: + - Function-like macros have no type check, which is not as strict as the function call check. - If macro parameters are not evaluated during macro expansion, unexpected results may occur. - A macro has no independent scope. @@ -530,6 +552,7 @@ The disadvantages of the function-like macro are as follows: - Macros containing a large number of statements must be expanded at each call point. If there are many call points, the code will be expanded. Unlike macros, functions do not have these disadvantages. However, the biggest disadvantage of functions is low execution efficiency (increasing the overhead of function calls and the difficulty of compiler optimization). + In light of this, you can use inline functions when necessary. Similar to macros, inline functions are expanded at the call point. The difference is that inline functions are expanded during compilation. Inline functions have the advantages of both functions and macros: @@ -540,10 +563,11 @@ Inline functions have the advantages of both functions and macros: For performance-sensitive code, consider using inline functions instead of standard functions. Exceptions: + In logging scenarios, only function-like macros can be used to keep information such as the file name (__FILE__) and line number (__LINE__) of the call point. -## Whitespace -### Rule 3.14.1 Ensure that horizontal spaces are used to highlight keywords and important information, and avoid unnecessary whitespace. +## Whitespace +### Rule 3.14.1 Ensure that horizontal spaces are used to highlight keywords and important information, and avoid unnecessary whitespace. Horizontal spaces are used to highlight keywords and important information. Spaces are not allowed at the end of each code line. The general rules are as follows: - Add spaces after keywords such as if, switch, case, do, while, and for. @@ -688,7 +712,7 @@ switch (value) Note: Currently, all IDEs support automatic deletion of spaces at the end of a line. Please configure your IDE correctly. -### Rec 3.14.1 Use blank lines only when necessary to keep code compact. +### Rec 3.14.1 Use blank lines only when necessary to keep code compact. There must be as few blank lines as possible so that more code can be displayed for easy reading. Recommendations: - Add blank lines according to the correlation between lines. @@ -723,8 +747,8 @@ int Foo(...) } ``` -## Classes -### Rule 3.15.1 Class access specifier declarations are in the sequence: public, protected, private. Indent these specifiers to the same level as the class keyword. +## Classes +### Rule 3.15.1 Class access specifier declarations are in the sequence: public, protected, private. Indent these specifiers to the same level as the class keyword. ```cpp class MyClass : public BaseClass { public: // Not indented. @@ -751,7 +775,7 @@ private: In each part, it is recommended that similar statements be put together and in the following order: Type (including typedef, using, nested structs and classes), Constant, Factory Function, Constructor, Assignment Operator, Destructor, Other Member Function, and Data Member -### Rule 3.15.2 The constructor initialization list must be on the same line or wrapped and aligned with four spaces of indentation. +### Rule 3.15.2 The constructor initialization list must be on the same line or wrapped and aligned with four spaces of indentation. ```cpp // If all variables can be placed on the same line MyClass::MyClass(int var) : someVar_(var) @@ -776,28 +800,33 @@ MyClass::MyClass(int var) } ``` -# 4 Comments -Generally, clear architecture and good naming are recommended to improve code readability, and comments are provided only when necessary. +# 4 Comments +Generally, clear architecture and good naming are recommended to improve code readability, and comments are provided only when necessary. + Comments are used to help readers quickly understand code. Therefore, **comments should be provided for the sake of readers**. Comments must be concise, clear, and unambiguous, ensuring that information is complete and not redundant. -**Comments are as important as code**. -When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than repeating code. +**Comments are as important as code**. + +When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than repeating code. + When modifying the code, ensure that the comments are consistent with the modified code. It is not polite to modify only code and keep the old comments, which will undermine the consistency between code and comments, and may confuse or even mislead readers. Comments should be made in English. -## Comment Style +## Comment Style + +In C++ code, both ` /* */` and ` // ` can be used for commenting. + +Comments can be classified into different types, such as file header comments, function header comments, and code comments. This is based on their purposes and positions. -In C++ code, both ` /* */` and ` // ` can be used for commenting. -Comments can be classified into different types, such as file header comments, function header comments, and code comments. This is based on their purposes and positions. Comments of the same type must keep a consistent style. Note: Example code in this document uses comments in the `//` format only to better describe the rules and recommendations. This does not mean this comment format is better. -## File Header Comments -### Rule 4.2.1 File header comments must contain the copyright notice. +## File Header Comments +### Rule 4.2.1 File header comments must contain the copyright notice. /* * Copyright (c) 2020 Huawei Device Co., Ltd. @@ -814,16 +843,18 @@ Note: Example code in this document uses comments in the `//` format only to bet * limitations under the License. */ -## Function Header Comments -### Rule 4.3.1 Write function header comments for public functions. +## Function Header Comments +### Rule 4.3.1 Write function header comments for public functions. Public functions are interfaces provided by classes for external systems. To use public functions, the caller must understand the functionalities, parameter value ranges, return values, and precautions of the functions. Write function header comments for the function value range, return value, and precautions, since they cannot be self-explained. -### Rule 4.3.2 Function header comments with no content are forbidden. +### Rule 4.3.2 Function header comments with no content are forbidden. Not all functions need function header comments. + For information that cannot be described by function signatures, add function header comments. Function header comments are placed above the function declaration or definition. Use one of the following styles: + Use '//' to start the function header. ```cpp @@ -852,9 +883,11 @@ int Func2(void); int Func3(void); ``` Use function names to describe functions, and add function header comments if necessary. + Do not write useless or redundant function headers. Do not write empty function headers with no content. The function header comment content will depend on the function and includes but is not limited to: a function description, return value, performance constraints, usage comments, memory conventions, algorithm implementation, reentering requirements. + In the function interface declaration in the external header file, the function header comment should clearly describe important and useful information. Good example: @@ -883,9 +916,9 @@ Problems: - The function name is redundant. - The most import thing, that is, who needs to release the buffer, is not clearly stated. -## Code Comments -### Rule 4.4.1 Code comments are placed above or on the right of the corresponding code. -### Rule 4.4.2 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code. +## Code Comments +### Rule 4.4.1 Code comments are placed above or on the right of the corresponding code. +### Rule 4.4.2 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code. Comments placed above code should be indented the same as that of the code. Use one of the following styles: Use "//". @@ -911,6 +944,7 @@ DoSomething(); DoSomething(); ``` Leave at least one space between the code and the comment on the right. It is recommended that no more than four spaces be left. + You can use the Tab key to indent 1–4 spaces. Select and use one of the following styles: @@ -920,6 +954,7 @@ int foo = 100; // Comment on the right int bar = 200; /* Comment on the right */ ``` It is more appealing sometimes when the comment is placed on the right of code and the comments and code are aligned vertically. + After the alignment, ensure that the comment is 1–4 spaces away from the widest line of code. Example: @@ -929,21 +964,26 @@ const int ANOTHER_CONST = 200; /* Leave spaces after code to align comments ve ``` When the comment on the right exceeds the line width, consider placing the comment above the code. -### Rule 4.4.3 Delete unused code segments. Do not comment them out. +### Rule 4.4.3 Delete unused code segments. Do not comment them out. Code that is commented out cannot be maintained. If you attempt to restore the code, it is very likely to introduce ignorable defects. + The correct method is to delete unnecessary code directly. If necessary, consider porting or rewriting the code. Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /* */, //, #if 0, #ifdef NEVER_DEFINED, and so on. -# 5 Header Files -## Header File Responsibility +# 5 Header Files +## Header File Responsibility A header file is an external interface of a module or file. The design of a header file shows most of the system design. + The interface declaration for most functions is more suitable placed in the header file, but implementation (except inline functions) cannot be placed in the header file. Functions, macros, enumerations, and structure definitions that need to be used in .cpp files cannot be placed in the header file. + The header responsibility should be simple. An overly complex header file will make dependencies complex and cause long compilation times. -### Rec 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally. +### Rec 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally. Generally, each .cpp file has a corresponding .h file. This .cpp file is used to store the function declarations, macro definitions, and class definitions that are to be exposed. + If a .cpp file does not need to open any interface externally, it should not exist. + Exception: __An entry point (for example, the file where the main function is located), unit tests, and dynamic libraries __ Example: @@ -983,19 +1023,22 @@ void Foo::Fun() } ``` -## Header File Dependency -### Rule 5.2.1 Header file cyclic dependency is forbidden. -An example of cyclic dependency (also known as circular dependency) is: a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any of these header files is modified, all code containing a.h, b.h, and c.h needs to be recompiled. +## Header File Dependency +### Rule 5.2.1 Header file cyclic dependency is forbidden. +An example of cyclic dependency (also known as circular dependency) is: a.h contains b.h, b.h contains c.h, and c.h contains a.h. If any of these header files is modified, all code containing a.h, b.h, and c.h needs to be recompiled. + For a unidirectional dependency, for example if: a.h contains b.h, b.h contains c.h, and c.h does not contain any header file, modifying a.h does not mean that we need to recompile the source code for b.h or c.h. The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization. -### Rule 5.2.2 Header files should have #define guards to prevent multiple inclusion. +### Rule 5.2.2 Header files should have #define guards to prevent multiple inclusion. To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once. When defining a protection character, comply with the following rules: + 1) The protection character uses a unique name. + 2) Do not place code or comments (except for file header comments) before or after the protected part. Example: Assume that the timer.h file of the timer module is in the timer/include/timer.h directory. Perform the following operations to safeguard the timer.h file: @@ -1007,9 +1050,11 @@ Example: Assume that the timer.h file of the timer module is in the timer/includ #endif ``` -### Rule 5.2.3 It is prohibited to reference external function interfaces and variables in extern declaration mode. +### Rule 5.2.3 It is prohibited to reference external function interfaces and variables in extern declaration mode. Interfaces provided by other modules or files can be used only by including header files. + Using external function interfaces and variables in extern declaration mode may cause inconsistency between declarations and definitions when external interfaces are changed. + In addition, this kind of implicit dependency may cause architecture corruption. Cases that do not comply with specifications: @@ -1058,11 +1103,14 @@ int Fun() } ``` In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. + Example: + When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. + When a function needs to be stubbed or patched, the function can be declared using extern. -### Rule 5.2.4 Do not include header files in extern "C". +### Rule 5.2.4 Do not include header files in extern "C". If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the nesting of extern "C". If there are too many nested layers, compilation errors may occur. When C and C++ programmings are used together and if extern "C" includes a header file, the original intent behind the header file may be hindered. For example, when the link specifications are modified incorrectly. @@ -1108,7 +1156,7 @@ However, because `#include "a.h"` is placed inside `extern "C"` in b.h, the link Exceptions: In the C++ compilation environment, if you want to reference the header file of pure C, the C header files should not contain `extern "C"`. The non-intrusive approach is to include the C header file in `extern "C"`. -### Rec 5.2.1 Use `#include` instead of a forward declaration to include header files. +### Rec 5.2.1 Use `#include` instead of a forward declaration to include header files. A forward declaration is for the declaration of classes, functions, and templates and is not meant for its definition. - Advantages: @@ -1124,11 +1172,11 @@ A forward declaration is for the declaration of classes, functions, and template Therefore, we should avoid using forward declarations as much as possible. Instead, we use the #include statement to include a header file and ensure dependency. -# 6 Scopes +# 6 Scopes -## Namespaces +## Namespaces -### Rec 6.1.1 For code that does not need to be exported from the .cpp file, you are advised to use an unnamed namespace for encapsulation or use static to modify the variables, constants, or functions that need hiding. +### Rec 6.1.1 For code that does not need to be exported from the .cpp file, you are advised to use an unnamed namespace for encapsulation or use static to modify the variables, constants, or functions that need hiding. In the C++ 2003 standard, using static to modify the external availability of functions and variables was marked as deprecated. Therefore, unnamed namespaces are the recommended method. Main Reasons: @@ -1156,7 +1204,7 @@ void Foo::Fun() ``` -### Rule 6.1.1 Do not use "using" to import namespace in a header file or before #include statements. +### Rule 6.1.1 Do not use "using" to import namespace in a header file or before #include statements. Note: Using "using" to import namespace will affect any subsequent code and may cause symbol conflicts. Example: @@ -1207,9 +1255,9 @@ namespace Foo { ``` -## Global Functions and Static Member Functions +## Global Functions and Static Member Functions -### Rec 6.2.1 Use namespaces to manage global functions. If global functions are closely tied to a class, you can use static member functions. +### Rec 6.2.1 Use namespaces to manage global functions. If global functions are closely tied to a class, you can use static member functions. Note: Placing non-member functions in a namespace avoids polluting the global scope. Do not use "class + static member function" to simply manage global functions. If a global function is closely tied to a class, it can be used as a static member function of the class. If you need to define some global functions for a .cpp file, use unnamed namespaces for management. @@ -1224,9 +1272,9 @@ public: }; ``` -## Global Constants and Static Member Constants +## Global Constants and Static Member Constants -### Rec 6.3.1 Use namespaces to manage global constants. If global constants are closely tied to a class, you can use static member constants. +### Rec 6.3.1 Use namespaces to manage global constants. If global constants are closely tied to a class, you can use static member constants. Note: Placing global constants in a namespace avoids polluting the global scope. Do not use "class + static member constant" to simply manage global constants. If a global constant is closely tied to a class, it can be used as a static member constant of the class. If you need to define some global constants only for a .cpp file, use unnamed namespaces for management. @@ -1241,9 +1289,9 @@ public: }; ``` -## Global Variables +## Global Variables -### Rec 6.4.1 Do not use global variables. Use the singleton pattern instead. +### Rec 6.4.1 Do not use global variables. Use the singleton pattern instead. Note: Global variables can be modified and read, which results in data coupling between production code and the global variables. ```cpp int g_counter = 0; @@ -1299,9 +1347,9 @@ After the singleton is implemented, there is a unique global instance, which can Exception: In some cases, the scope of a global variable is contained inside a module. Multiple instances of the same global variable may exist, and each module holds one copy. In this case, a singleton cannot be used as it is limited to one instance. -# 7 Classes +# 7 Classes -## Constructors, Copy/Move Constructors, Copy/Move Assignment Operators, and Destructors +## Constructors, Copy/Move Constructors, Copy/Move Assignment Operators, and Destructors Constructors, copy/move constructors, copy/move assignment operators, and destructors provide lifetime management methods for objects. - Constructor: `X()` - Copy constructor: `X(const X&)` @@ -1310,7 +1358,7 @@ Constructors, copy/move constructors, copy/move assignment operators, and destru - Move assignment operator: `operator=(X&&)` *Provided in versions later than C++ 11*. - Destructor: `~X()` -### Rule 7.1.1 The member variables of a class must be initialized explicitly. +### Rule 7.1.1 The member variables of a class must be initialized explicitly. Note: If a class has members but no constructor and a default constructor is defined, the compiler will automatically generate a constructor, but it will not initialize member variables. The content of each object is uncertain. Exceptions: @@ -1355,7 +1403,7 @@ private: }; ``` -### Rec 7.1.1 Initialization during declaration (C++ 11) and initialization using the constructor initialization list are preferred for member variables. +### Rec 7.1.1 Initialization during declaration (C++ 11) and initialization using the constructor initialization list are preferred for member variables. Note: Initialization during declaration (C++11) is preferred because initialized values of member variables can be easily understood. If initialized values of certain member variables are relevant to constructors, or C++ 11 is not supported, the constructor initialization list is used preferentially to initialize these member variables. Compared with the assignment statements in constructors, code of the constructor initialization list is simpler and has higher performance, and can be used to initialize constant and reference members. ```cpp @@ -1373,7 +1421,7 @@ private: }; ``` -### Rule 7.1.2 Declare single-parameter constructors as explicit to prevent implicit conversion. +### Rule 7.1.2 Declare single-parameter constructors as explicit to prevent implicit conversion. Note: If a single-parameter constructor is not declared as explicit, it will become an implicit conversion function. Example: @@ -1402,7 +1450,7 @@ The preceding code fails to be compiled because the parameter required by `Proce If the explicit keyword of the Foo constructor is removed, implicit conversion is triggered and a temporary Foo object is generated when `ProcessFoo` is called with the string parameter. Usually, this implicit conversion is confusing and bugs are apt to be hidden, due to unexpected type conversion. Therefore, single-parameter constructors require explicit declaration. -### Rule 7.1.3 If copy/move constructors and copy/move assignment operators are not needed, clearly prohibit them. +### Rule 7.1.3 If copy/move constructors and copy/move assignment operators are not needed, clearly prohibit them. Note: If users do not define it, the compiler will generate copy constructors and copy assignment operators, move constructors and move assignment operators (move semantic functions will be available in versions later than C++ 11). If we do not use copy constructors or copy assignment operators, explicitly delete them. @@ -1439,7 +1487,7 @@ public: }; ``` -### Rule 7.1.4 Copy constructors and copy assignment operators should be implemented or forbidden together. +### Rule 7.1.4 Copy constructors and copy assignment operators should be implemented or forbidden together. Both copy constructors and copy assignment operators provide copy semantics. They should be implemented or hidden together. ```cpp @@ -1467,7 +1515,7 @@ private: }; ``` -### Rule 7.1.5 Move constructors and move assignment operators should be implemented or hidden together. +### Rule 7.1.5 Move constructors and move assignment operators should be implemented or hidden together. The move operation is added in C++ 11. If a class is required to support the move operation, move constructors and move assignment operators need to be implemented. Both move constructors and move assignment operators provide move semantics. They should be implemented or hidden together. @@ -1496,8 +1544,9 @@ public: }; ``` -### Rule 7.1.6 It is prohibited to call virtual functions in constructors and destructors. +### Rule 7.1.6 It is prohibited to call virtual functions in constructors and destructors. Note: Calling a virtual function of the current object in a constructor or destructor will cause behaviors of non-polymorphism. + In C++, a base class constructs only one complete object at a time. Example: Base indicates the base class, and Sub indicates the derived class. @@ -1520,15 +1569,22 @@ public: ``` When running the following statement: + `Sub sub;` + The constructor of the derived class is executed first. However, the constructor of the base class is called first. Because the constructor of the base class calls the virtual function log, the log is in the base class version. The derived class is constructed only after the base class is constructed. As a result, behaviors of non-polymorphism are caused. + This also applies to destructors. -### Rule 7.1.7 The copy constructors, copy assignment operators, move constructors, and move assignment operators in polymorphic base classes must be non-public or delete functions. +### Rule 7.1.7 The copy constructors, copy assignment operators, move constructors, and move assignment operators in polymorphic base classes must be non-public or delete functions. Slicing occurs if the value of a derived class object is directly assigned to a base class object. In this case, only the base class part is copied or moved, which undermines polymorphism. + [Counterexample] + In the following code example, the copy constructor and copy assignment operator are not defined in the base class. The compiler automatically generates two special member functions. + If the value of a derived class object is assigned to the base class object, slicing occurs. The copy constructor and copy assignment operator can be declared as **deleted** so that the compiler can check such assignment behavior. + ```cpp class Base { public: @@ -1553,11 +1609,11 @@ void Foo(const Base &base) Derived d; Foo(d); // A derived class object is passed. ``` -1. Set copy constructors or copy assignment operators to **private** and do not implement them. +Set copy constructors or copy assignment operators to **private** and do not implement them. -## Inheritance +## Inheritance -### Rule 7.2.1 Declare destructors of a base class as virtual, and declare the class that is not to be inherited as final. +### Rule 7.2.1 Declare destructors of a base class as virtual, and declare the class that is not to be inherited as final. Note: Destructors of the derived class can be called during polymorphism invocation only when destructors of the base class are virtual. Example: There will be memory leak if destructors of the base class are not declared as virtual. @@ -1616,12 +1672,16 @@ int main(int argc, char* args[]) } ``` Because destructors of the base class are not declared as virtual, only destructors of the base class are called when an object is destroyed. Destructors of the derived class Sub are not called. As a result, a memory leak occurs. + Exceptions: + For classes such as **NoCopyable** and **NoMovable** that have no behavior and are used only as identifiers, you do not need to define them as final. -### Rule 7.2.2 Do not use default parameter values for virtual functions. +### Rule 7.2.2 Do not use default parameter values for virtual functions. Note: In C++, virtual functions are dynamically bound, but the default parameters of functions are statically bound during compilation. This means that the function you finally execute is a virtual function that is defined in the derived class but uses the default parameter value in the base class. To avoid confusion and other problems caused by inconsistent default parameter declarations during overriding of virtual functions, it is prohibited to declare default parameter values for all virtual functions. + Example: The default value of parameter "text" of the virtual function "Display" is determined at compilation time instead of runtime, which does not fit with polymorphism. + ```cpp class Base { public: @@ -1659,7 +1719,7 @@ int main() }; ``` -### Rule 7.2.3 Do not redefine inherited non-virtual functions. +### Rule 7.2.3 Do not redefine inherited non-virtual functions. Note: Non-virtual functions cannot be dynamically bound (only virtual functions can be dynamically bound). You can obtain the correct result by operating on the pointer of the base class. Example: @@ -1683,7 +1743,7 @@ base->Fun(); // Call Fun of the base class. ``` -## Multiple Inheritance +## Multiple Inheritance In the actual development process, multiple inheritance is seldom used because the following typical problems may occur: 1. Data duplication and name ambiguity caused by "diamond" inheritance. C++ introduces virtual inheritance to solve these problems. 2. In addition to "diamond" inheritance, names of multiple base classes may also conflict with each other, resulting in name ambiguity. @@ -1695,7 +1755,7 @@ Multiple inheritance provides a simpler method for assembling and reusing multip Therefore, multiple inheritance can be used only in the following cases: -### Rec 7.3.1 Use multi-inheritance to implement interface separation and multi-role combination. +### Rec 7.3.1 Use multi-inheritance to implement interface separation and multi-role combination. If a class requires multiple interfaces, combine multiple separated interfaces by using multiple inheritance. This is similar to the Traits mixin of the Scala language. ```cpp @@ -1723,7 +1783,7 @@ class basic_iostream : public basic_istream, public basic_ostream { }; ``` -## Overloading +## Overloading Overload operators should be used when there are sufficient reasons, and they do not change the original perception of the operators. For example, do not use the plus sign (+) to perform subtraction. Operator overloading can make code more intuitive but has some disadvantages: @@ -1732,11 +1792,9 @@ Operator overloading can make code more intuitive but has some disadvantages: - Overloading operators can cause confusion if behavior definitions are not intuitive (for example, if the "+" operator is used for subtraction). - The implicit conversion caused by the overloading of assignment operators may lead to entrenched bugs. Functions such as Equals () and CopyFrom () can be defined to replace the = and == operators. - - -# 8 Functions -## Function Design -### Rule 8.1.1 Avoid long functions and ensure that each function contains no more than 50 lines (non-null and non-comment). +# 8 Functions +## Function Design +### Rule 8.1.1 Avoid long functions and ensure that each function contains no more than 50 lines (non-null and non-comment). A function should be displayed on one screen (no longer than 50 lines). It should do only one thing, and do it well. Long functions often mean that the functions are too complex to implement in more than one function, or overly detailed but not further abstracted. @@ -1744,11 +1802,12 @@ Long functions often mean that the functions are too complex to implement in mor Exception: Some algorithms may be longer than 50 lines due to algorithm convergence and functional comprehensiveness. Even if a long function works very well now, once someone modifies it, new problems may occur. It might even cause bugs that are difficult to find. + It is recommended that you split a long function into several functions that are simpler and easier to manage, facilitating comprehension and modification. -## Inline Functions +## Inline Functions -### Rec 8.2.1 An inline function cannot exceed 10 lines. +### Rec 8.2.1 An inline function cannot exceed 10 lines. **Note**: An inline function has the same characteristics of a normal function. The difference between an inline function and a normal function lies in the processing of function calls. When a general function is called, the program execution right is transferred to the called function, and then returned to the function that calls it. When an inline function is called, the invocation expression is replaced with an inline function body. Inline functions are only suitable for small functions with only 1-10 lines. For a large function that contains many statements, the function call and return overheads are relatively trivial and do not need the help of an inline function. Most compilers may abandon the inline mode and use the common method to call the function. @@ -1756,9 +1815,9 @@ Inline functions are only suitable for small functions with only 1-10 lines. For If an inline function contains complex control structures, such as loop, branch (switch), and try-catch statements, the compiler may regard the function as a common function. **Virtual functions and recursive functions cannot be used as inline functions**. -## Function Parameters +## Function Parameters -### Rec 8.3.1 Use a reference instead of a pointer for function parameters. +### Rec 8.3.1 Use a reference instead of a pointer for function parameters. **Note**: A reference is more secure than a pointer because it is not empty and does not point to other targets. Using a reference stops the need to check for illegal null pointers. @@ -1767,8 +1826,9 @@ Use const to avoid parameter modification, so that readers can clearly know that Exception: When the input parameter is an array with an unknown compile-time length, you can use a pointer instead of a reference. -### Rec 8.3.2 Use strongly typed parameters. Do not use void*. +### Rec 8.3.2 Use strongly typed parameters. Do not use void*. While different languages have their own views on strong typing and weak typing, it is generally believed that C and C++ are strongly typed languages. Since we use such a strongly typed language, we should keep to this style. + An advantage of this is the compiler can find type mismatch problems at the compilation stage. Using strong typing helps the compiler find more errors for us. Pay attention to the usage of the FooListAddNode function in the following code: @@ -1802,20 +1862,20 @@ void MakeTheList() 1. You can use a template function to change the parameter type. 2. A base class pointer can be used to implement this according to polymorphism. -### Rec 8.3.3 A function can have a maximum of five parameters. +### Rec 8.3.3 A function can have a maximum of five parameters. If a function has too many parameters, it is apt to be affected by external changes, and therefore maintenance is affected. Too many function parameters will also increase the testing workload. If a function has more than five parameters, you can: - Split the function. - Combine related parameters into a struct. -# 9 Other C++ Features +# 9 Other C++ Features -## Constants and Initialization +## Constants and Initialization Unchanged values are easier to understand, trace, and analyze. Therefore, use constants instead of variables as much as possible. When defining values, use const as a default. -### Rule 9.1.1 Do not use macros to replace constants. +### Rule 9.1.1 Do not use macros to replace constants. **Note**: Macros are a simple text replacement that is completed in the preprocessing phase. When an error is reported, the corresponding value is reported. During tracing and debugging, the value is also displayed instead of the macro name. A macro does not support type checking and is insecure. A macro has no scope. @@ -1829,7 +1889,7 @@ const int MAX_MSISDN_LEN = 20; // Good constexpr int MAX_MSISDN_LEN = 20; ``` -### Rec 9.1.1 A group of related integer constants must be defined as an enumeration. +### Rec 9.1.1 A group of related integer constants must be defined as an enumeration. **Note**: Enumerations are more secure than `#define` or `const int`. The compiler checks whether a parameter value is within the enumerated value range to avoid errors. @@ -1908,23 +1968,29 @@ enum RTCPType { }; ``` -### Rule 9.1.2 Magic numbers cannot be used. +### Rule 9.1.2 Magic numbers cannot be used. So-called magic numbers are numbers that are unintelligible and difficult to understand. Some numbers can be understood based on context. + For example, the number 12 varies in different contexts. + type = 12; is not intelligible (and a magic number), but `month = year * 12`; can be understood, so we wouldn't really class this as a magic number. + The number 0 is often seen as a magic number. For example, `status = 0`; cannot truly express any status information. Solution: + Comments can be added for numbers that are used locally. + For the numbers that are used multiple times, you must define them as constants and give them descriptive names. The following cases are forbidden: + No symbol is used to explain the meaning of a number, for example, ` const int ZERO = 0`. The symbol name limits the value. For example, for example, `const int XX_TIMER_INTERVAL_300MS = 300`. Use `XX_TIMER_INTERVAL_MS` instead. -### Rule 9.1.3 Ensure that a constant has only one responsibility. +### Rule 9.1.3 Ensure that a constant has only one responsibility. **Note**: A constant is used for only one specific function, that is, a constant cannot be used for multiple purposes. @@ -1943,7 +2009,7 @@ namespace Namespace2 { } ``` -### Rule 9.1.4 Do not use memcpy_s or memset_s to initialize non-POD objects. +### Rule 9.1.4 Do not use memcpy_s or memset_s to initialize non-POD objects. **Note**: `POD` is short for `Plain Old Data`, which is a concept introduced in the C++ 98 standard (ISO/IEC 14882, first edition, 1998-09-01). The `POD` types include the original types and aggregate types such as `int`, `char`, `float`, `double`, `enumeration`, `void`, and pointer. Encapsulation and object-oriented features cannot be used (for example, user-defined constructors, assignment operators, destructors, base classes, and virtual functions). @@ -1953,7 +2019,7 @@ Even if a class of the aggregate type is directly copied and compared, and any f For details about the POD type, see the appendix. -### Rec 9.1.2 Declare and initialize variables only when they are used. +### Rec 9.1.2 Declare and initialize variables only when they are used. **Note**: It is a common low-level programming error that a variable is not assigned an initial value before being used. Declaring and initializing a variable just before using it will prevent this. @@ -1973,8 +2039,8 @@ string name("zhangsan"); // Invoke a constructor. ``` -## Expressions -### Rule 9.2.1 A variable cannot be referenced again if it is contained in an increment or decrement operation in an expression. +## Expressions +### Rule 9.2.1 A variable cannot be referenced again if it is contained in an increment or decrement operation in an expression. In an expression where the increment or decrement operations are performed on a variable, the variable cannot be referenced again. The result of a second referencing is not explicitly defined in C++ standards. The results in different compilers or different versions of a compiler may be different. Therefore, it is recommended that an undefined operation sequence not be assumed. @@ -2001,11 +2067,13 @@ i++; // Good: i++ is placed in a single line. x = Func(i, i); ``` -### Rule 9.2.2 A switch statement must have a default branch. +### Rule 9.2.2 A switch statement must have a default branch. In most cases, a switch statement requires a default branch to ensure that there is a default action when the case tag is missing for a processed value. Exceptions: + If the switch condition variables are enumerated and the case branch covers all values, the default branch is redundant. + Because modern compilers can check which case branches are missing in the switch statement and provide an advanced warning. ```cpp @@ -2026,7 +2094,7 @@ switch (color) { } ``` -### Rec 9.2.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. +### Rec 9.2.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. When a variable is compared with a constant, placing the constant on the left, for example, if (MAX == v), does not comply with standard reading habits and is more difficult to understand. The constant should be placed on the right. The expression is written as follows: ```cpp @@ -2042,7 +2110,7 @@ There are special cases: for example, if the expression `if (MIN < value && valu You do not need to worry about writing '==' as '=' because a compilation alarm will be generated for `if (value = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. -### Rec 9.2.2 Use parentheses to specify the operator precedence. +### Rec 9.2.2 Use parentheses to specify the operator precedence. Use parentheses to specify the operator precedence. This will prevent program errors due to the inconsistency between default priority and the intended design. At the same time, it makes the code clearer and more readable. However, too many parentheses muddy the code, reducing readability. The following is a recommendation on their correct usage. - For binary and ternary operators, if multiple operators are involved, parentheses should be used. @@ -2055,7 +2123,7 @@ x = (a == b) ? a : (a – b); /* More than one operator is used and thus pare ``` -## Type Casting +## Type Casting Do not use type branches to customize behaviors. Type branch customization behavior is prone to errors and is an obvious sign of attempting to compile C code using C++. This is very inflexible technology. If you forget to modify all branches when adding a new type to a compiler, you will not be notified. Use templates and virtual functions to let the type define itself rather than letting the calling side determine behavior. @@ -2068,7 +2136,7 @@ However, we cannot prohibit the use of type casting because the C++ language is Exception: When calling a function, if we do not want to process the result of the function, first consider whether this is your best choice. If you do not want to process the return value of the function, cast it to void. -### Rule 9.3.1 If type casting is required, use the type casting provided by the C++ instead of the C style. +### Rule 9.3.1 If type casting is required, use the type casting provided by the C++ instead of the C style. **Note**: @@ -2086,15 +2154,15 @@ The type casting provided by C++ is more targeted, easy to read, and more secure int64_t i{ someInt32 }; ``` -### Rec 9.3.1 Avoid using `dynamic_cast`. +### Rec 9.3.1 Avoid using `dynamic_cast`. 1. `dynamic_cast` depends on the RTTI of C++ so that the programmer can identify the type of the object in C++ at run time. 2. `dynamic_cast` indicates that a problem has occurred in the design of the base class and derived class.The derived class destroys the contract of the base class and it is necessary to use `dynamic_cast` to convert the class to a subclass for special processing. In this case, it is more desirable to improve the design of the class, instead of using `dynamic_cast` to solve the problem. -### Rec 9.3.2 Avoid using `reinterpret_cast`. +### Rec 9.3.2 Avoid using `reinterpret_cast`. **Note**: `reinterpret_cast` is used to convert irrelevant types. Trying to use `reinterpret_cast` to force a type to another type destroys the security and reliability of the type and is an insecure casting method. Avoid casting between completely different types. -### Rec 9.3.3 Avoid using `const_cast`. +### Rec 9.3.3 Avoid using `const_cast`. **Note**: The `const_cast` command is used to remove the `const` and `volatile` properties of an object. @@ -2132,9 +2200,9 @@ int main(void) ``` -## Resource Allocation and Release +## Resource Allocation and Release -### Rule 9.4.1 When a single object is released, delete is used. When an array object is released, delete [] is used. +### Rule 9.4.1 When a single object is released, delete is used. When an array object is released, delete [] is used. Note: To delete a single object, use delete; to delete an array object, use delete []. The reasons are as follows: - new: Apply for memory from the system and call the corresponding constructor to initialize an object. @@ -2162,7 +2230,7 @@ delete[] numberArray; numberArray = NULL; ``` -### Rec 9.4.1 Use the RAII feature to trace dynamic allocation. +### Rec 9.4.1 Use the RAII feature to trace dynamic allocation. Note: RAII is an acronym for Resource Acquisition Is Initialization. It is a simple technology that controls program resources (such as memory, file handle, network connections, and mutexes) by using the object lifecycle. @@ -2204,11 +2272,11 @@ bool Update() } ``` -## Standard Template Library +## Standard Template Library The standard template library (STL) varies between products. The following table lists some basic rules and suggestions for each team. -### Rule 9.5.1 Do not save the pointer returned by c_str () of std::string. +### Rule 9.5.1 Do not save the pointer returned by c_str () of std::string. Note: The C++ standard does not specify that the string::c_str () pointer is permanently valid. Therefore, the STL implementation used can return a temporary storage area and release it quickly when calling string::c_str (). Therefore, to ensure the portability of the program, do not save the result of string::c_str (). Instead, call it directly. @@ -2240,45 +2308,53 @@ void Fun2() Exception: In rare cases where high performance coding is required , you can temporarily save the pointer returned by string::c_str() to match the existing functions which support only the input parameters of the const char* type. However, you should ensure that the lifecycle of the string object is longer than that of the saved pointer, and that the string object is not modified within the lifecycle of the saved pointer. -### Rec 9.5.1 Use std::string instead of char*. +### Rec 9.5.1 Use std::string instead of char*. Note: Using string instead of `char*` has the following advantages: 1. There is no need to consider the null character '\0' at the end. 2. You can directly use operators such as `+`, `=`, and `==`, and other character and string operation functions. -3. There is no need to consider memory allocation operations.This helps avoid explicit usage of `new` and `delete` and the resulting errors. +3. There is no need to consider memory allocation operations. This helps avoid explicit usage of `new` and `delete` and the resulting errors. Note that in some STL implementations, string is based on the copy-on-write policy, which causes two problems. One is that the copy-on-write policy of some versions does not implement thread security, and the program breaks down in multi-threaded environments. Second, dangling pointers may be caused when a dynamic link library transfers the string based on the copy-on-write policy, due to the fact that reference count cannot be reduced when the library is unloaded. Therefore, it is important to select a reliable STL implementation to ensure the stability of the program. Exception: + When an API of a system or other third-party library is called, only `char*` can be used for defined interfaces. However, before calling the interfaces, you can use string. When calling the interfaces, you can use `string::c_str()` to obtain the character pointer. + When a character array is allocated as a buffer on the stack, you can directly define the character array without using string or containers such as `vector`. -### Rule 9.5.2 Do not use auto_ptr. +### Rule 9.5.2 Do not use auto_ptr. Note: The `std::auto_ptr` in the STL library has an implicit ownership transfer behavior. The code is as follows: ```cpp auto_ptr p1(new T); auto_ptr p2 = p1; ``` After the second line of statements is executed, p1 does not point to the object allocated in line 1 and becomes `NULL`. Therefore, `auto_ptr` cannot be placed in any standard containers. + This ownership transfer behavior is not expected. In scenarios where ownership must be transferred, implicit transfer should not be used. This often requires the programmer to keep extra attention on code that uses `auto_ptr`, otherwise access to a null pointer will occur. + There are two common scenarios for using auto_ptr . One is to transfer it as a smart pointer to outside the function that generates the auto_ptr , and the other is to use auto_ptr as the RAII management class. Resources are automatically released when the lifecycle of auto_ptr expires. + In the first scenario, you can use std::shared_ptr instead. + In the second scenario, you can use std::unique_ptr in the C++ 11 standard. std::unique_ptr is a substitute for std::auto_ptr and supports explicit ownership transfer. Exception: + Before the C++ 11 standard is widely used, std::auto_ptr can be used in scenarios where ownership needs to be transferred. However, it is recommended that std::auto_ptr be encapsulated. The copy constructor and assignment operator of the encapsulation class should not be used in a standard container. -### Rec 9.5.2 Use the new standard header files. +### Rec 9.5.2 Use the new standard header files. Note: When using the standard header file of C++, use `` instead of ``. -## Usage of const +## Usage of const Add the keyword const before the declared variable or parameter (example: `const int foo`) to prevent the variable from being tampered with. Add the const qualifier to the function in the class (example: `class Foo {int Bar (char c) const;} ;`) to make sure the function does not modify the status of the class member variable. const variables, data members, functions, and parameters ensure that the type detection during compilation is accurate and errors are found as soon as possible. Therefore, we strongly recommend that const be used in any possible case. + Sometimes it is better to use constexpr from C++ 11 to define real constants. -### Rule 9.6.1 For formal parameters of pointer and reference types, if the parameters do not need to be modified, use const. +### Rule 9.6.1 For formal parameters of pointer and reference types, if the parameters do not need to be modified, use const. Unchanging values are easier to understand, trace, and analyze. `const` is used as the default option and is checked during compilation to make the code more secure and reliable. ```cpp class Foo; @@ -2286,9 +2362,11 @@ class Foo; void PrintFoo(const Foo& foo); ``` -### Rule 9.6.2 For member functions that do not modify member variables, use const. +### Rule 9.6.2 For member functions that do not modify member variables, use const. Declare the member function as `const` whenever possible. The access function should always be const. So long as the function of a member is not modified, the function is declared with const. + When you need to modify data members in a virtual function, take all classes in the inheritance chain into account instead of only focusing on the implementation of a single class. + ```cpp class Foo { public: @@ -2310,7 +2388,7 @@ private: }; ``` -### Rec 9.6.1 Member variables that will not be modified after initialization should be defined as constants. +### Rec 9.6.1 Member variables that will not be modified after initialization should be defined as constants. ```cpp class Foo { @@ -2321,9 +2399,9 @@ private: }; ``` -## Exceptions +## Exceptions -### Rec 9.7.1 If the function does not throw an exception, the declaration is `noexcept`. +### Rec 9.7.1 If the function does not throw an exception, the declaration is `noexcept`. **Reasons:** 1. If the function does not throw an exception, the declaration is `noexcept`, which enables the compiler to optimize the function to the maximum extent, for example, reducing the execution paths and improving the efficiency of exiting when an error occurs. 2. For STL containers such as `vector`, to ensure the interface robustness, if the `move ` constructor of saved items is not declared as `noexcept`, the `copy machanism` instead of the `move machanism` is used when the items are removed from the container. This would cause performance loss risks. If the function does not throw an exception, or a program does not intercept and process an exception thrown by the function, new `noexcept` keywords can be used to modify the function, indicating that the function does not throw an exception or the thrown exception is not intercepted or processed. For example: @@ -2341,7 +2419,7 @@ std::vector MyComputation(const std::vector& v) noexcept } ``` -**Example:** +**Example** ```cpp RetType Function(Type params) noexcept; // Maximized optimization @@ -2368,11 +2446,12 @@ a2.push_back(Foo2()); //Triggers container expansion and invokes the move constr ``` **Note** + The default constructor, destructor, `swap` function, and `move` operator should not throw an exception. -## Templates and Generic Programming +## Templates and Generic Programming -### Rule 9.8.1 Do not use generic programming. +### Rule 9.8.1 Do not use generic programming. OpenHarmony adopts object-oriented programming, which has ideas, concepts, and techniques totally different from those of generic programming. Generic programming in C++ allows for extremely flexible interfaces that are type safe and high performance, enabling reuse of code of different types but with the same behavior. @@ -2386,10 +2465,12 @@ However, generic programming has the following disadvantages: 5. It is difficult to modify or refactor the template code. The template code is expanded in multiple contexts, and it is hard to verify that the code refactoring makes sense in all of them. Only __a few components of OpenHarmony__ support generic programming, and the templates developed using generic programming must have detailed comments. + Exceptions: -1. The STL adaptation layer can use generic programming. -## Macros +The STL adaptation layer can use generic programming. + +## Macros In the C++ language, it is strongly recommended that complex macros be used as little as possible. - For constant definitions, use `const` or `enum` as stated in the preceding sections. - For macro functions, try to be as simple as possible, comply with the following principles, and use inline functions and template functions for replacement. @@ -2405,13 +2486,13 @@ template T Square(T a, T b) { return a * b; } For details about how to use macros, see the related chapters about the C language specifications. **Exception**: For some common and mature applications, for example, encapsulation for new and delete, the use of macros can be retained. -# 10 Modern C++ Features +# 10 Modern C++ Features As the ISO released the C++ 11 language standard in 2011 and released the C++ 17 in March 2017, the modern C++ (C++ 11/14/17) adds a large number of new language features and standard libraries that improve programming efficiency and code quality. This chapter describes some guidelines for modern C++ use, to avoid language pitfalls. -## Code Simplicity and Security Improvement -### Rec 10.1.1 Use `auto` properly. +## Code Simplicity and Security Improvement +### Rec 10.1.1 Use `auto` properly. **Reasons** * `auto` can help you avoid writing verbose, repeated type names, and can also ensure initialization when variables are defined. @@ -2463,8 +2544,9 @@ auto s1 = v[0]; // auto deduction changes s1 to std::string in order to copy v[0 If `auto` is used to define an interface, such as a constant in a header file, the type may be changed if the developer has modified the value. -### Rule 10.1.1 Use the keyword `override` when rewriting virtual functions. -**Reason:** +### Rule 10.1.1 Use the keyword `override` when rewriting virtual functions. +**Reason** + The keyword `override` ensures that the function is a virtual function and an overridden virtual function of the base class. If the subclass function is different from the base class function prototype, a compilation alarm is generated. `final` also ensures that virtual functions are not overridden by subclasses. If you modify the prototype of a base class virtual function but forget to modify the virtual function overridden by the subclass, you can find inconsistency during compilation. You can also avoid forgetting to modify the overridden function when there are multiple subclasses. @@ -2493,11 +2575,12 @@ public: 2. When overriding the virtual function by a subclass in a base class, including destructors, use the keyword `override` or `final` instead of `virtual`. 3. For the non-virtual function, do not use `virtual` or `override`. -### Rule: 10.1.2 Use the keyword `delete` to delete functions. +### Rule: 10.1.2 Use the keyword `delete` to delete functions. **Reason** + The `delete` keyword is clearer and the application scope is wider than a class member function that is declared as private and not implemented. -**Example:** +**Example** ```cpp class Foo { @@ -2523,8 +2606,9 @@ template<> void Process(void) = delete; ``` -### Rule 10.1.3 Use `nullptr` instead of `NULL` or `0`. -**Reason:** +### Rule 10.1.3 Use `nullptr` instead of `NULL` or `0`. +**Reason** + For a long time, C++ has not had a keyword that represents a null pointer, which is embarrassing: ```cpp @@ -2577,7 +2661,7 @@ if (result == nullptr) { // Find() returns a pointer. } ``` -### Rule 10.1.4 Use `using` instead of `typedef`. +### Rule 10.1.4 Use `using` instead of `typedef`. For versions earlier than `C++11`, you can define the alias of the type by using `typedef`. No one wants to repeat code like `std::map>`. ```cpp @@ -2632,11 +2716,13 @@ private: }; ``` -### Rule 10.1.5 Do not use std::move to operate the const object. +### Rule 10.1.5 Do not use std::move to operate the const object. Literally, `std::move` means moving an object. The const object cannot be modified and cannot be moved. Therefore, using `std::move` to operate the const object may confuse code readers. + Regarding actual functions, `std::move` converts an object to the rvalue reference type. It can convert the const object to the rvalue reference of const. Because few types define the move constructor and the move assignment operator that use the const rvalue reference as the parameter, the actual function of code is often degraded to object copy instead of object movement, which brings performance loss. -**Bad example:** +**Bad example** + ```cpp std::string g_string; std::vector g_stringList; @@ -2650,14 +2736,14 @@ void func() } ``` -## Smart Pointers -### Rule 10.2.1 Preferentially use the original pointer instead of the smart pointer for singletons and class members that are not held by multiple parties. -**Reason:** +## Smart Pointers +### Rule 10.2.1 Preferentially use the original pointer instead of the smart pointer for singletons and class members that are not held by multiple parties. +**Reason** Smart pointers automatically release object resources to prevent resource leakage, but they require extra resource overheads. For example, the classes, constructors, and destructors automatically generated by smart pointers consume more resources such as memory. When singletons, class members, and the like are not held by multiple parties, resources can be released only in class destructors. In this case, smart pointers should not be used. -**Example:** +**Example** ```cpp class Foo; @@ -2699,18 +2785,20 @@ public: ``` 2. When the created object is returned and needs to be referenced by multiple parties, `shared_ptr` can be used. -### Rule 10.2.2 Use `unique_ptr` instead of `shared_ptr`. -**Reasons:** +### Rule 10.2.2 Use `unique_ptr` instead of `shared_ptr`. +**Reasons** + 1. Using `shared_ptr` a lot has an overhead (atomic operations on the `shared_ptr`s reference count have a measurable cost). 2. Shared ownership in some cases (such as circular dependency) may create objects that can never be released. 3. Shared ownership can be an attractive alternative to careful ownership design but it may obfuscate the design of a system. -### Rule 10.2.2 Use `std::make_unique` instead of `new` to create a `unique_ptr`. -**Reasons:** +### Rule 10.2.2 Use `std::make_unique` instead of `new` to create a `unique_ptr`. +**Reasons** + 1. `make_unique` provides a simpler creation method. 2. `make_unique` ensures the exception safety of complex expressions. -**Example:** +**Example** ```cpp // Bad: MyClass appears twice, which carries a risk of inconsistency. @@ -2737,31 +2825,40 @@ F(unique_ptr(new Foo()), Bar()); F(make_unique(), Bar()); ``` -**Exception:** +**Exception** + `std::make_unique` does not support user-defined `deleter`. + In the scenario where the `deleter` needs to be customized, it is recommended that `make_unique` be implemented in the customized version's own namespace. + Using `new` to create `unique_ptr` with the user-defined `deleter` is the last choice. -### Rule 10.2.4 Create `shared_ptr` by using `std::make_shared` instead of `new`. -**Reason:** +### Rule 10.2.4 Create `shared_ptr` by using `std::make_shared` instead of `new`. +**Reason** + In addition to the consistency factor similar to that in `std::make_unique` when using `std::make_shared`, performance is also a factor to consider. `std::shared_ptr` manages two entities: + * Control block (storing reference count, `deleter`, etc.) * Managed objects When `std::make_shared` creates `std::shared_ptr`, it allocates sufficient memory for storing control blocks and managed objects on the heap at a time. When `std::shared_ptr(new MyClass)`is used to create a `std::shared_ptr`, not only does `new MyClass` trigger heap allocation, but the constructor function of `std::shard_ptr` triggers a second heap allocation, resulting in extra overhead. -**Exception:** +**Exception** + Similar to `std::make_unique`, `std::make_shared` does not support `deleter` customization. -## Lambda -### Rec 10.3.1 Use `lambda` to capture local variables or write local functions when normal functions do not work. -**Reason:** +## Lambda +### Rec 10.3.1 Use `lambda` to capture local variables or write local functions when normal functions do not work. +**Reason** + Functions cannot capture local variables or be declared at local scope. If you need those things, choose `lambda` instead of handwritten `functor`. + On the other hand, `lambda` and `functor` objects do not support overloading. If overloading is required, use a function. + If both `lambda` and functions work, a function is preferred. Use the simplest tool. -**Example:** +**Example** ```cpp // Write a function that accepts only an int or string. @@ -2778,11 +2875,12 @@ for (int taskNum = 0; taskNum < max; ++taskNum) { pool.Join(); ``` -### Rule 10.3.1 Avoid capturing by reference in lambdas that will not be used locally. -**Reason:** +### Rule 10.3.1 Avoid capturing by reference in lambdas that will not be used locally. +**Reason** + Using `lambdas` at a "nonlocal" scope includes returning, storing on the heap, and passing to another thread. Local pointers and references should not outlive their scope. Capturing by reference in `lambdas` indicates storing a reference to a local object. If this leads to a reference that exceeds the lifecycle of a local variable, capturing by reference should not be used. -**Example:** +**Example** ```cpp // Bad @@ -2805,11 +2903,12 @@ void Foo() } ``` -### Rec 10.3.2 All variables are explicitly captured if `this` is captured. -**Reason:** +### Rec 10.3.2 All variables are explicitly captured if `this` is captured. +**Reason** + The `[=]` in the member function seems to indicate capturing by value but actually it is capturing data members by reference because it captures the invisible `this` pointer by value. Generally, it is recommended that capturing by reference be avoided. If it is necessary to do so, write `this` explicitly. -**Example:** +**Example** ```cpp class MyClass { @@ -2833,14 +2932,19 @@ private: }; ``` -### Rec 10.3.3 Avoid default capture modes. -**Reason:** +### Rec 10.3.3 Avoid default capture modes. +**Reason** + The lambda expression provides two default capture modes: by-reference (&) and by-value (=). + By default, the "by-reference" capture mode will implicitly capture the reference of all local variables, which will easily lead to dangling references. By contrast, explicitly writing variables that need to be captured can make it easier to check the lifecycle of an object and reduce the possibility of making a mistake. -By default, the "by-value" capture mode will implicitly capture this pointer, and it is difficult to find out which variables the lambda function depends on.If a static variable exists, the reader mistakenly considers that the lambda has copied a static variable. + +By default, the "by-value" capture mode will implicitly capture this pointer, and it is difficult to find out which variables the lambda function depends on. If a static variable exists, the reader mistakenly considers that the lambda has copied a static variable. + Therefore, it is required to clearly state the variables that lambda needs to capture, instead of using the default capture mode. -**Bad example:** +**Bad example** + ```cpp auto func() { @@ -2854,7 +2958,8 @@ auto func() } ``` -**Good example:** +**Good example** + ```cpp auto func() { @@ -2870,14 +2975,15 @@ auto func() Reference: Effective Modern C++: Item 31: Avoid default capture modes. -## Interfaces -### Rec 10.4.1 Use `T*` or `T&` arguments instead of a smart pointer in scenarios where ownership is not involved. -**Reasons:** +## Interfaces +### Rec 10.4.1 Use `T*` or `T&` arguments instead of a smart pointer in scenarios where ownership is not involved. +**Reasons** + 1. Passing a smart pointer to transfer or share ownership should only be used when the ownership mechanism is explicitly required. -2. Passing a smart pointer (for example, passing the `this` smart pointer) restricts the use of a function to callers using smart pointers. +2. Passing a smart pointer (for example, passing `this` ) restricts the use of a function to callers using smart pointers. 3. Passing a shared smart pointer adds a runtime performance cost. -**Example:** +**Example** ```cpp // Accept any int*. diff --git a/en/contribute/OpenHarmony-security-design-guide.md b/en/contribute/OpenHarmony-security-design-guide.md index 361d7f5c7628b4669b782c40a4457b42840ce429..9a4897773e016fa95da09b2c84cd5f865cf2f7f0 100644 --- a/en/contribute/OpenHarmony-security-design-guide.md +++ b/en/contribute/OpenHarmony-security-design-guide.md @@ -4,25 +4,25 @@ With reference to industry standards and best practices, this document provides ## 1\. Access Channel Control -1-1 To prevent unauthorized access to the system and resources, all system management interfaces unless otherwise specified by standards protocols must be provided with access control mechanisms (enabled by default) +1-1 To prevent unauthorized access to the system and resources, all system management interfaces unless otherwise specified by standards protocols must be provided with access control mechanisms (enabled by default). **Description**: To reduce the attack surface of the system, authentication mechanisms must be enabled for system management interfaces (including those used for configuration, upgrade, and commissioning) to prevent unauthorized access. -1-2 All external connections of the system must be necessary for system operation and maintenance. All unnecessary connections and ports must be disabled +1-2 All external connections of the system must be necessary for system operation and maintenance. All unnecessary connections and ports must be disabled. **Description**: Disabling unnecessary communication ports can greatly reduce security threats and is a basic means of system security protection. ## 2\. Application Security -2-1 The session ID and user permission must be verified for each access request if authorization is required +2-1 The session ID and user permission must be verified for each access request if authorization is required. **Description**: It is a means to prevent unauthorized access. -2-2 User authentication must be conducted on the server since it may be easily bypassed if being conducted on the client +2-2 User authentication must be conducted on the server since it may be easily bypassed if being conducted on the client. -## 3\. Encryption +## 3. Encryption -3-1 Use verified, secure, and open encryption algorithms +3-1 Use verified, secure, and open encryption algorithms. **Description**: The security of an algorithm does not mean its confidentiality. @@ -33,7 +33,7 @@ Recommended cipher algorithms are as follows: - Block cipher algorithm: AES (key length of 128 bits or longer) - Stream cipher algorithm: AES (key length of 128 bits or longer) (OFB/CTR mode) - Asymmetric encryption algorithm: RSA (recommended: 3072 bits) -- Hash algorithm: SHA-2 (256 bits or above) +- Hash algorithm: SHA-2 (256 bits or longer) - Key exchange algorithm: DH (recommended: 3072 bits) - Hash-based message authentication code (HMAC) algorithm: HMAC-SHA-2 @@ -41,9 +41,9 @@ The following are examples of insecure cipher algorithms: MD5, DES, 3DES (Do not use 3DES in TLS/SSH, and ensure K1≠K2≠K3 in non-cryptographic protocols), HMAC-SHA2-256-96, HMAC-SHA1-96, HMAC-MD5, HMAC-MD5-96, SSH CBC, anonymous algorithm suites, DH512, DH1024, SKIPJACK, RC2, RSA (1024 bits or shorter), MD2, MD4, Blowfish, RC4 -3-2 Do not use algorithms for error control coding, such as parity check and CRC, to perform integrity check, unless otherwise specified in standard protocols +3-2 Do not use algorithms for error control coding, such as parity check and CRC, to perform integrity check, unless otherwise specified in standard protocols. -3-3 Cipher algorithms must use cryptographically secure random numbers for security purposes +3-3 Cipher algorithms must use cryptographically secure random numbers for security purposes. **Description**: The use of insecure random numbers may easily weaken a cipher algorithm or even render it ineffective. @@ -56,35 +56,35 @@ The following interfaces can be used to generate secure random numbers: - **java.security.SecureRandom** of the JDK - **/dev/random** file of Unix-like platforms -3-4 By default, use secure cipher algorithms and disable/prohibit insecure cipher algorithms. Use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by OpenHarmony +3-4 By default, use secure cipher algorithms and disable/prohibit insecure cipher algorithms. Use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by OpenHarmony. **Description**: In the context of advances in cryptographic technologies and enhancement in computing capabilities, some cipher algorithms may become insecure. Using such algorithms may bring risks to user data. In addition, unknown flaws may exist in cipher algorithms that are developed by amateurs and not analyzed/verified by the industry. In this regard, use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by OpenHarmony. **Example**: See 3-1. -3-5 The GCM mode is preferred when block cipher algorithms are used +3-5 The GCM mode is preferred when block cipher algorithms are used. -3-6 The OAEP padding scheme is preferred when RSA is used for encryption +3-6 The OAEP padding scheme is preferred when RSA is used for encryption. **Description**: PKCS1 padding has been known to be insecure in the industry and academic field. If OAEP padding is not used, attackers can easily decrypt the ciphertext. -3-7 Do not use private keys to encrypt sensitive data when asymmetric encryption is used for protecting data confidentiality +3-7 Do not use private keys to encrypt sensitive data when asymmetric encryption is used for protecting data confidentiality. **Description**: Using private key for encryption cannot ensure data confidentiality. -3-8 Use different key pairs for asymmetric encryption and signing +3-8 Use different key pairs for asymmetric encryption and signing. -3-9 Use the sign-then-encrypt mode when both symmetric encryption and digital signature are required. Check the order in which cipher algorithms are called, and do not sign cipher text hashes (i.e., do not perform private key operations on cipher text hashes) +3-9 Use the sign-then-encrypt mode when both symmetric encryption and digital signature are required. Check the order in which cipher algorithms are called, and do not sign cipher text hashes (i.e., do not perform private key operations on cipher text hashes). -**Description**: If a cipher text is signed (i.e., the cipher text hash is signed), attackers can obtain the cipher text hash (also the cipher text) through network sniffing. In this case, attackers can tamper with the ciphertext signature +**Description**: If a cipher text is signed (i.e., the cipher text hash is signed), attackers can obtain the cipher text hash (also the cipher text) through network sniffing. In this case, attackers can tamper with the ciphertext signature. -3-10 If the public keys received from peers during key exchange using the DH algorithm are special public keys 0, 1, p-1, or p, negotiation must be performed again +3-10 If the public keys received from peers during key exchange using the DH algorithm are special public keys 0, 1, p-1, or p, negotiation must be performed again. **Description**: If the public keys received from peers during key exchange using the DH algorithm are special key values, the negotiated keys must also be known values. In this case, attackers may easily decrypt the cipher text within five attempts. -3-11 In SSL and TLS protocols, if DH or ECDH algorithm is used for key exchange, use the cipher suite that contains DHE or ECDHE key exchange algorithm to achieve perfect forward secrecy; do not use the cipher suite that only contains DH/ECDH +3-11 In SSL and TLS protocols, if DH or ECDH algorithm is used for key exchange, use the cipher suite that contains DHE or ECDHE key exchange algorithm to achieve perfect forward secrecy; do not use the cipher suite that only contains DH/ECDH. -3-12 Do not use truncated message authentication codes (MACs) in cryptographic protocols +3-12 Do not use truncated message authentication codes (MACs) in cryptographic protocols. **Description**: In cryptographic protocols (such as TLS, SSH, and IKE), MACs are usually used to verify the integrity of messages. Some protocols support truncated MACs. Truncation reduces MAC security. For example, SLOTH attacks against multiple cryptographic protocols (such as TLS and SSH) may craft collisions using truncated hash values. @@ -102,19 +102,19 @@ The standard output lengths of HMAC-MD5-96, HMAC-SHA1-96, and HMAC-SHA2-256-96 c - SHA-512/224/HMAC-SHA-512/224: The standard output length is 224 bits. - SHA-512/256/HMAC-SHA-512/256: The standard output length is 256 bits. -3-13 When HMAC is used for data integrity protection, do not use the calculation result of hash(key\|\|message) or hash(message\|\|key) as the MAC value +3-13 When HMAC is used for data integrity protection, do not use the calculation result of hash(key\|\|message) or hash(message\|\|key) as the MAC value. **Description**: Attackers may add any information to the end of the original plaintext information to compromise data integrity. -3-14 Use different symmetric keys for data encryption and MAC calculation in the same transaction +3-14 Use different symmetric keys for data encryption and MAC calculation in the same transaction. **Description**: If the same key is used for data encryption and MAC calculation, key exposure creates vulnerabilities for attackers to tamper with confidential information. -3-15 Do not use fixed IVs (for example, IVs hard-coded or fixed in configuration files) for encryption +3-15 Do not use fixed IVs (for example, IVs hard-coded or fixed in configuration files) for encryption. **Description**: The randomness of IV in CBC mode ensures the generation of different cipher texts based on the same piece of data in plain text and key. If such randomness cannot be ensured, attackers can easily replace the cipher text. For other block cipher modes, such as OFB and CRT, attackers can easily decrypt the cipher text. -3-16 Do not select anonymous authentication, non-encryption, weak authentication, weak key exchange, weak symmetric key algorithms, or weak message authentication algorithm cipher suites in cryptographic protocols +3-16 Do not select anonymous authentication, non-encryption, weak authentication, weak key exchange, weak symmetric key algorithms, or weak message authentication algorithm cipher suites in cryptographic protocols. **Description**: Their use may compromise system security. @@ -128,25 +128,25 @@ The following is an example of weak authentication: RSA/DSA, with a key length less than 2048 bits -3-17 It is recommended that only ECDHE be used as the cipher suite of the key exchange algorithm +3-17 It is recommended that only ECDHE be used as the cipher suite of the key exchange algorithm. -3-18 Do not hardcode keys used for data encryption/decryption. Use the root key or other means for encryption, and protect the root key with a proper security mechanism (for example, hardcode only some key components) +3-18 Do not hardcode keys used for data encryption/decryption. Use the root key or other means for encryption, and protect the root key with a proper security mechanism (for example, hardcode only some key components). **Description**: Hard-coded keys are likely to be cracked by reverse engineering. -3-19 It is recommended that the function design cover the working key update methods (such as manual or automatic key update) and update rules (online update, offline update, and update time, etc.) +3-19 It is recommended that the function design cover the working key update methods (such as manual or automatic key update) and update rules (online update, offline update, and update time, etc.). **Description**: The longer a key is in use, the more likely it is to be cracked. The larger the amount of data encrypted using the key, the greater the chance for attackers to obtain ciphertext data as it is easier to analyze the ciphertexts encrypted using the same key. If the key is leaked, the loss incurred increases with its service period. **Example**: The system generates new keys based on key generation rules, uses the old key to decrypt the data, uses the new key to encrypt the data again, and destroys the old key. In scenarios where mass data needs to be encrypted, consider reserving the old key to decrypt the old data and use the new key to encrypt the new data. -3-20 Key materials and components must be subject to strict access control (such as permission 600 or 400) +3-20 Key materials and components must be subject to strict access control (such as permission 600 or 400). -3-21 For keys saved in memory, overwrite the memory by other data (such as 0x00) before freeing it +3-21 For keys saved in memory, overwrite the memory by other data (such as 0x00) before freeing it. -## 4\. Sensitive Data Protection +## 4. Sensitive Data Protection -4-1 Store authentication credentials such as passwords in ciphertext and apply access control +4-1 Store authentication credentials such as passwords in ciphertext and apply access control. 4-2 Use irreversible algorithms such as PBKDF2 for encryption in scenarios where authentication credentials do not need to be restored. HMAC (authentication credentials and salt values) can be used in scenarios where performance is sensitive and the security requirement is not high. (Note: Password and salt value locations can be exchanged.) @@ -156,13 +156,13 @@ RSA/DSA, with a key length less than 2048 bits - A salt value is a cryptographically secure random number generated by the system. The salt value has at least 16 bytes and is unique to each user. - Avoid using HASH (user name\|\|password), HMAC (user name, password), and HASH (password XOR salt). -4-3 If sensitive data needs to be transmitted over untrusted networks, ensure that sensitive data is transmitted over secure paths or is transmitted after being encrypted +4-3 If sensitive data needs to be transmitted over untrusted networks, ensure that sensitive data is transmitted over secure paths or is transmitted after being encrypted. -4-4 For access to sensitive data, use appropriate security mechanisms (such as authentication, authorization, or encryption) based on risks. Files and directories containing sensitive data (for example, configuration files, log files, personal sensitive data files, user password files, key files, certificate files, drive files, and backup files) shall be accessible only to their owners or permitted users +4-4 For access to sensitive data, use appropriate security mechanisms (such as authentication, authorization, or encryption) based on risks. Files and directories containing sensitive data (for example, configuration files, log files, personal sensitive data files, user password files, key files, certificate files, drive files, and backup files) shall be accessible only to their owners or permitted users. -4-5 Filter out or shield authentication credentials in logs, debugging information, and error messages +4-5 Filter out or shield authentication credentials in logs, debugging information, and error messages. -## 5\. System Management and Maintenance Security +## 5. System Management and Maintenance Security 5-1 Adopt one or more of the following protection measures for login authentication on system O\&M interfaces to support anti-brute force cracking based on actual scenarios and risks: @@ -171,11 +171,11 @@ RSA/DSA, with a key length less than 2048 bits - Login postponed - Verification code required -5-2 By default, all the passwords entered by users on the GUI for system O\&M purposes are not displayed in plaintext +5-2 By default, all the passwords entered by users on the GUI for system O\&M purposes are not displayed in plaintext. -5-3 The password in a text box cannot be copied out +5-3 The password in a text box cannot be copied out. -5-4 Use appropriate security protocols, and disable insecure protocols by default +5-4 Use appropriate security protocols, and disable insecure protocols by default. **Example**: @@ -189,35 +189,35 @@ The following are examples of insecure protocols: TFTP, FTP, Telnet, SSL 2.0, SSL 3.0, TLS 1.0, TLS 1.1, SNMPv1/v2, and SSHv1.x -5-5 Do not assign a role to a new account or assign a role with the least privilege (for example, read only) by default in line with the principle of least privilege +5-5 Do not assign a role to a new account or assign a role with the least privilege (for example, read only) by default in line with the principle of least privilege. **Description**: In this way, unauthorized users cannot but obtain the least privilege when the authorization mechanism is faulty or bypassed. -## 6\. Privacy Protection +## 6. Privacy Protection -6-1 Explicitly notify users and obtain their consent before collecting/using their personal data or forwarding the data to third parties +6-1 Explicitly notify users and obtain their consent before collecting/using their personal data or forwarding the data to third parties. **Description**: It is to increase transparency and grant users more control over their data in compliance with laws and regulations such as GDPR. -6-2 Provide necessary security protection mechanisms (such as authentication, access control, and logging) for personal data collection, processing, and storage as required by normal services to prevent personal data from being disclosed, lost, or damaged +6-2 Provide necessary security protection mechanisms (such as authentication, access control, and logging) for personal data collection, processing, and storage as required by normal services to prevent personal data from being disclosed, lost, or damaged. -6-3 Describe the product functions involving user privacy in documentation, including the purpose, scope, method, and period of personal data processing, and require that the function should be used in compliance with local laws and regulations +6-3 Describe the product functions involving user privacy in documentation, including the purpose, scope, method, and period of personal data processing, and require that the function should be used in compliance with local laws and regulations. **Description**: It is to increase transparency in compliance with laws and regulations such as GDPR. -6-4 Support filtering, anonymization, or pseudonymization for personal data to be displayed (for example, on UIs or in stored or exported files) +6-4 Support filtering, anonymization, or pseudonymization for personal data to be displayed (for example, on UIs or in stored or exported files). **Description**: It is to reduce the risk of personal privacy breaches. -6-5 To prevent location tracking, do not identify precise locations of users for maintenance purposes (such as troubleshooting) unless it is explicitly required +6-5 To prevent location tracking, do not identify precise locations of users for maintenance purposes (such as troubleshooting) unless it is explicitly required. **Description**: Precise location information is very sensitive, and is not needed in troubleshooting. -6-6 Collect personal data necessary for stated purposes in compliance with the data minimization principle. Comply with the data minimization principle when displaying personal data in fault diagnosis logs +6-6 Collect personal data necessary for stated purposes in compliance with the data minimization principle. Comply with the data minimization principle when displaying personal data in fault diagnosis logs. **Description**: The display of personal data in fault diagnosis logs may arouse users' doubts. Therefore, personal data should not be displayed in fault diagnosis logs. If it has to be displayed (for example, for debugging purpose) anonymization is required. -6-7 In scenarios involving personal data processing, provide mechanisms to ensure that data subjects can query, update, and erase their personal data +6-7 In scenarios involving personal data processing, provide mechanisms to ensure that data subjects can query, update, and erase their personal data. **Description**: It is to protect data subjects' rights. @@ -225,13 +225,13 @@ TFTP, FTP, Telnet, SSL 2.0, SSL 3.0, TLS 1.0, TLS 1.1, SNMPv1/v2, and SSHv1.x | No. | Term | Definition | | :--: | :--------------------------: | ------------------------------------------------------------ | -| 1 | authentication credential | Private or public data declared to prove identity authenticity. Common authentication credentials include passwords, pre-shared keys, private keys, SNMP community names, smart cards, dynamic tokens, fingerprints, and retinas. | -| 2 | personal data | Any information relating to an identified or identifiable natural person ("data subject") who can be identified, directly or indirectly, in particular by reference to an identifier such as a name, an identification number, and location data or to one or more factors specific to the physical, physiological, genetic, mental, economic, cultural, or social identity of that natural person. Personal data includes a natural person's email address, telephone number, biometric information (such as a fingerprint), location data, IP address, health care information, religious belief, social security number, marital status, and so on. | -| 3 | sensitive personal data | An important subset of personal data, referring to the information involving most private data of a data subject, or the data, once leaked or modified, may result in adverse impacts to a data subject. Sensitive personal data includes data revealing racial or ethnic origin, political opinions, religious or philosophical beliefs, trade-union membership, genetic data, biometric information, data concerning health, sex life, or sexual orientation, as well as bank account numbers, ID card numbers, passports, passwords, and other information associated with a natural person's identity. Sensitive personal data requires additional and stricter protection measures. | -| 4 | sensitive data | The scope of sensitive data varies with product application scenarios, and should be analyzed and determined based on risks in specific scenarios. Typical sensitive data includes authentication credentials (such as passwords, private keys, and dynamic token cards), encryption keys, sensitive personal data, etc. | -| 5 | data subject | An individual who provides the data controller and processor with personal data. A data subject can be identified directly by personal data (such as a name) or indirectly by the combination of personal data. | -| 6 | anonymization | A process of irreversibly de-identifying personal data such that the person cannot be identified by using reasonable time, cost, technology either by the controller or by any other person to identify that individual. | -| 7 | pseudonymization | In order to restrict the ability of using personal data to identify a data subject, identity information contained in personal data can be replaced by aliases. The substitution is considered pseudonymization, which has the following features: (1) The remaining attributes linked to the alias do not suffice to identify the data subject to whom they relate; and (2) The alias assignment cannot be reversed by reasonable efforts of the privacy stakeholders (such as the data controller) other than those that performed assignment. Pseudonymized data is still personal data. Pseudonyms are also known as aliases. | -| 8 | precise location information | Precise longitude and latitude. For example, the GPS can locate an object with the precision of dozens of meters. The criterion of precise location information is that the information is precise enough for locating a natural person. | +| 1 | anonymization | A process of irreversibly de-identifying personal data such that the person cannot be identified by using reasonable time, cost, technology either by the controller or by any other person to identify that individual. | +| 2 | authentication credential | Private or public data declared to prove identity authenticity. Common authentication credentials include passwords, pre-shared keys, private keys, SNMP community names, smart cards, dynamic tokens, fingerprints, and retinas. | +| 3 | data subject | An individual who provides the data controller and processor with personal data. A data subject can be identified directly by personal data (such as a name) or indirectly by the combination of personal data. | +| 4 | personal data | Any information relating to an identified or identifiable natural person ("data subject") who can be identified, directly or indirectly, in particular by reference to an identifier such as a name, an identification number, and location data or to one or more factors specific to the physical, physiological, genetic, mental, economic, cultural, or social identity of that natural person. Personal data includes a natural person's email address, telephone number, biometric information (such as a fingerprint), location data, IP address, health care information, religious belief, social security number, marital status, and so on. | +| 5 | precise location information | Precise longitude and latitude. For example, the GPS can locate an object with the precision of dozens of meters. The criterion of precise location information is that the information is precise enough for locating a natural person. | +| 6 | pseudonymization | In order to restrict the ability of using personal data to identify a data subject, identity information contained in personal data can be replaced by aliases. The substitution is considered pseudonymization, which has the following features: (1) The remaining attributes linked to the alias do not suffice to identify the data subject to whom they relate; and (2) The alias assignment cannot be reversed by reasonable efforts of the privacy stakeholders (such as the data controller) other than those that performed assignment. Pseudonymized data is still personal data. Pseudonyms are also known as aliases. | +| 7 | sensitive data | The scope of sensitive data varies with product application scenarios, and should be analyzed and determined based on risks in specific scenarios. Typical sensitive data includes authentication credentials (such as passwords, private keys, and dynamic token cards), encryption keys, sensitive personal data, etc. | +| 8 | sensitive personal data | An important subset of personal data, referring to the information involving most private data of a data subject, or the data, once leaked or modified, may result in adverse impacts to a data subject. Sensitive personal data includes data revealing racial or ethnic origin, political opinions, religious or philosophical beliefs, trade-union membership, genetic data, biometric information, data concerning health, sex life, or sexual orientation, as well as bank account numbers, ID card numbers, passports, passwords, and other information associated with a natural person's identity. Sensitive personal data requires additional and stricter protection measures. | | 9 | standard protocol | An international standard protocol (e.g., ETSI, 3GPP, or ITU-T standard, or that from some other standard-setting organization), regional standard (e.g., standard developed by the European Union), national industry standard (e.g., standard formulated by the Ministry of Industry and Information Technology of China), or de facto industry standard (e.g., industry standard defined by UPnP). | diff --git a/en/contribute/code-contribution.md b/en/contribute/code-contribution.md index 4c340a50ad319bdb122658d6f6bfea7c034de72d..b96d15df710a082c285b2df6f33e86bf96c7bb29 100644 --- a/en/contribute/code-contribution.md +++ b/en/contribute/code-contribution.md @@ -1,6 +1,6 @@ -# Code Contribution +# Code Contribution -## Start Contributions +## Start Contributions ### Design Specifications @@ -8,7 +8,7 @@ - [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) - [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) -### Code Style +### Coding Style Develop, review, and test code following the OpenHarmony coding standards. Make sure code is written in the same style. @@ -22,11 +22,11 @@ Develop, review, and test code following the OpenHarmony coding standards. Make - [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md) - [Logging Guide](OpenHarmony-Log-guide.md) -## Contribution Workflow +## Contribution Workflow -For details, see [Contribution Process](contribution-process.md). +For details, see [Contribution Process](contribution-process.md). -## Security Issue Disclosure +## Security Issue Disclosure - [Security Issue Handling and Release Processes](https://gitee.com/openharmony/security/blob/master/en/security-process/README.md) - [OpenHarmony Security Vulnerability Notice](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md) diff --git a/en/contribute/code-of-conduct.md b/en/contribute/code-of-conduct.md index 09ba997e09eb252f1b30fd14cb63897658abf11e..36d7e15a416f20cfed0c5ef89a42e94f653652f7 100755 --- a/en/contribute/code-of-conduct.md +++ b/en/contribute/code-of-conduct.md @@ -1,6 +1,6 @@ # Code of Conduct -The OpenHarmony community complies with the code of conduct specified in [Contributor Covenant](https://contributor-covenant.org/) of the open source community. For details, see [https://www.contributor-covenant.org/version/1/4/code-of-conduct/](https://www.contributor-covenant.org/version/1/4/code-of-conduct/). +The OpenHarmony community complies with the code of conduct specified in [Contributor Covenant](https://contributor-covenant.org/) of the open source community. To report insults, harassment, or other unacceptable behavior, you can contact the OpenHarmony technical committee at contact@openharmony.io. diff --git a/en/contribute/contribution-guide.md b/en/contribute/contribution-guide.md index 8ae87c6f330d4ae6f44a5001823d1113d1c8a8e5..7cb77bf0c75d731d9801d55b2bae5e6af5aa2bb2 100644 --- a/en/contribute/contribution-guide.md +++ b/en/contribute/contribution-guide.md @@ -1,4 +1,4 @@ -# Contribution Guide +# Contribution Guide - **[How to Contribute](how-to-contribute.md)** - **[Code of Conduct](code-of-conduct.md)** diff --git a/en/contribute/contribution-process.md b/en/contribute/contribution-process.md index 97e7742034627eeae65dfcac2b9295dd886b1302..f7c24afce7972e93949e5f1960878097d18c6d0d 100755 --- a/en/contribute/contribution-process.md +++ b/en/contribute/contribution-process.md @@ -1,19 +1,19 @@ -# Contribution Process +# Contribution Process -## Preparations +## Preparations - Install, configure, and use Git. For details, visit [https://gitee.com/help/categories/43](https://gitee.com/help/categories/43). - Register an SSH public key. For details, visit [https://gitee.com/help/articles/4191](https://gitee.com/help/articles/4191). - Find the repository that you are interested in on the code hosting platform of OpenHarmony. -## Downloading Code +## Downloading Code -## Forking a Code Branch from the Cloud +## Forking a Code Branch from the Cloud 1. Find and open the homepage of the repository. 2. Click the **Fork** button in the upper right corner, and create an individual cloud fork branch as prompted. -## Downloading the Fork Repository to the Local Host +## Downloading the Fork Repository to the Local Host Perform the following steps to download the code in the repository to your computer: @@ -36,7 +36,7 @@ Perform the following steps to download the code in the repository to your compu 2. Clone the remote repository. - You can copy the address of the remote repository on the repository page. - **Figure 1** + **Figure 1** Cloning the remote repository ![](figures/clone.png "clone") @@ -49,7 +49,7 @@ Perform the following steps to download the code in the repository to your compu -## Using the repo Tool to Download Code Repositories in Batches +## Using the repo Tool to Download Code Repositories in Batches 1. Download the repo tool. \(For details, see [https://gitee.com/help/articles/4316](https://gitee.com/help/articles/4316).\) @@ -67,9 +67,9 @@ Perform the following steps to download the code in the repository to your compu ``` -## Committing Code +## Committing Code -## Committing a Repository \(git clone\) +## Committing a Repository \(git clone\) 1. **Update the branch.** @@ -109,7 +109,7 @@ Perform the following steps to download the code in the repository to your compu ``` -## Committing Multiple Repositories \(repo init/sync\) +## Committing Multiple Repositories \(repo init/sync\) 1. Configure the token of the global environment. @@ -181,27 +181,29 @@ Save the settings and exit. The repo tool automatically pushes the local branch The tool automatically associates the PR with the issue. -## Creating a Pull Request +## Creating a Pull Request Access the fork repository on Gitee, click the button for creating a PR, and select the **myfeature** branch to generate a PR. \(Skip this step if a PR has been automatically created using the repo tool.\) For details, visit [https://gitee.com/help/articles/4128](https://gitee.com/help/articles/4128). ->![](public_sys-resources/icon-notice.gif) **NOTICE:** +>![](public_sys-resources/icon-notice.gif) **NOTICE** +> >**How do I create PRs at the same time if multiple code repositories have compilation dependencies?** >During the development of the operating system \(OS\), it is common that multiple code repositories have compilation dependencies. Therefore, the PRs need to be created and merged at the same time. For this reason, Gitee uses issues as the dependency identifiers for code repositories with compilation dependencies to commit the PRs. Follow the operations below: +> >1. Create an issue in any of the code repositories. >2. Associate PRs that need to be built and merged at the same time with the issue. For details, visit [https://gitee.com/help/articles/4142](https://gitee.com/help/articles/4142). >3. After the build is triggered, the build center identifies the PRs associated with the same issue, downloads the build, and merges the PRs into the code library after the code is approved. -## Building Access Control +## Building Access Control -## Creating an Issue +## Creating an Issue 1. Go to the homepage of the repository. 2. Click the **Issues** tab in the upper left corner. Then, click the issue creation button on the right, and create a dedicated task as prompted to execute continuous integration \(CI\) access control for associated code \(feature development/bug fixing\). -## Associating the Issue with the PR +## Associating the Issue with the PR When creating a PR or compiling an existing PR, enter **\#+I+_five-digit issue ID_** in the description box to associate the issue with the PR. @@ -212,7 +214,7 @@ When creating a PR or compiling an existing PR, enter **\#+I+_five-digit issue - Among the PRs associated with the issue, no PR that has been merged or closed is allowed. Otherwise, the CI cannot be triggered. - If an issue has been associated with a merged or closed PR, the issue cannot be reused. In this case, create another issue and associate it with an open PR. -## Triggering Code Access Control +## Triggering Code Access Control Comment "start build" in the PR to trigger CI access control. @@ -235,7 +237,7 @@ On the CI portal, you can detect code bugs in a timely manner to ensure code rel Visit [CI portal](http://ci.openharmony.cn/#/pipeLine). -## Reviewing Code +## Reviewing Code For details, visit [https://gitee.com/help/articles/4304](https://gitee.com/help/articles/4304). diff --git a/en/contribute/docs-release-process.md b/en/contribute/docs-release-process.md index 6b42e934e7e8d5d6b724aefeb26e23642827d289..5a6772284cbd3dbaa9a4514ca26733732944b7d4 100644 --- a/en/contribute/docs-release-process.md +++ b/en/contribute/docs-release-process.md @@ -76,7 +76,7 @@ Members in the Docs SIG or document contributors should cooperate with each serv To know feature and release plans of a release, you can attend the meeting [SIG Release](https://gitee.com/openharmony/release-management/blob/master/README.md) held on Friday every two weeks. Understand the release progress, requirement delivery progress, and document delivery progress. You can also view feature requirements of a release in [OpenHarmony Roadmap](https://gitee.com/openharmony/release-management/blob/master/OpenHarmony-RoadMap.md). You can select feature issues marked with SIG_Docs and associated document PRs. - + ### Reviewing Chinese Documents Submitted in PRs @@ -109,7 +109,7 @@ When reviewing a feature document, you are advised to provide review suggestions - When a Markdown page is deleted or a Markdown page name is changed, ensure that: - The page does not affect links in other documents in the community. You are advised to check the links locally. - - The contents in the **README** file is updated. + - The contents in the **README** file are updated. For more detailed specifications, see [Writing Instructions](writing-instructions.md). diff --git a/en/contribute/documentation-contribution.md b/en/contribute/documentation-contribution.md index 430587fe0ffa3386cf17d64f49af4f9d7f1e2bd4..8901080d124e33855949e5594f1a0e2fb3fd5a46 100755 --- a/en/contribute/documentation-contribution.md +++ b/en/contribute/documentation-contribution.md @@ -26,7 +26,8 @@ Your feedback matters. Submit issues and leave as detailed information as possib 1. On the Gitee page, click the **Issues** tab. On the displayed page, click **New issue**. Then enter the issue title and issue details. 2. Click **New** to submit the issue. The Docs team will confirm the issue. ->![](public_sys-resources/icon-note.gif) **Note:** +>![](public_sys-resources/icon-note.gif) **NOTE** +> >**How can I provide a high-quality issue?** > >- Provide a clear description of the issue, including the missing, outdated, incorrect, or to-be-improved content. diff --git a/en/contribute/figures/example.png b/en/contribute/figures/color.png old mode 100755 new mode 100644 similarity index 100% rename from en/contribute/figures/example.png rename to en/contribute/figures/color.png diff --git a/en/contribute/introducing-third-party-open-source-software.md b/en/contribute/introducing-third-party-open-source-software.md index 9d035a952d283b41604c492639eb2f0f52c37a88..3fd15c24b6df07403b77eff0e71d71cb2dea6414 100644 --- a/en/contribute/introducing-third-party-open-source-software.md +++ b/en/contribute/introducing-third-party-open-source-software.md @@ -37,12 +37,12 @@ For easier maintenance and evolution, comply with the following principles when 9. If you need to modify the software, place the new code in the software repository and ensure that the new code meets the license requirements of the software. Retain the original license for the modified files, and use the same license for the new files (recommended). 10. Provide the **README.OpenSource** file in the root directory of the software repository. Include the following information in the file: software name, license, license file location, version, upstream community address of the corresponding version, software maintenance owner, function description, and introduction reason. 11. Make sure the software you introduce is under the custody of a domain SIG. In principle, the SIG-Architecture will deny the introduction of a piece of software without the confirmation of the SIG-Compliance and the corresponding domain SIG. When introducing multiple pieces of software at a time, you can ask the PMC to hold a temporary review meeting between SIGs for faster introduction. If you want to introduce a piece of software but fail to meet the preceding requirements, send an email to oh-legal@openatom.io. -12. When software introduction depends on other dependency software, it is not allowed to nest the dependency software in the subdirectory of the software introduction, and all dependency softwares must be placed in separate repository, and name it in the format of **third_party_*****softwareName***, because nested placement of dependency software may lead to multiple versions of the same software, old versions of security vulnerabilities cannot be fixed in a timely, and will risk the opensource compliance issues. - - Dependency software are named in the compiled BUILD.gn with part name by prefixing the newly software introduction name, e.g. part_name = "software_introduction_name_dependency software_name". +12. When software introduction depends on other dependency software, it is not allowed to nest the dependency software in the subdirectory of the software introduction, and all dependency software must be placed in separate repository, and name it in the format of **third_party_*****softwareName***, because nested placement of dependency software may lead to multiple versions of the same software, old versions of security vulnerabilities cannot be fixed in a timely, and will risk the open-source compliance issues. + - Dependency software is named in the compiled **BUILD.gn** with part name by prefixing the new software introduction name, e.g. part_name = "software_introduction_name_dependency software_name". - The inter-component dependencies between software introduction and dependency software are resolved via external_deps. 13. OpenHarmony's archiving directory requirements for third-party software introduction. - If you don't have a really good reason to store it elsewhere and under one of the permitted licenses belongs in third_party. - - For the dedicated third-party software introduction which belongs to the specail devboard, and is is not suitable introduced into the OpenHarmony platform, you could apply to store it in the following locations, Naming it in the format of **softwareName**, where **softwareName** must be an official name, and create README.OpenSource description file in the corresponding directory; Creating BUILD.gn to build it independently to support the automatic collection of open source obligation declaration. + - For the dedicated third-party software introduction which belongs to the special devboard, and is not suitable introduced into the OpenHarmony platform, you could apply to store it in the following locations, Naming it in the format of **softwareName**, where **softwareName** must be an official name, and create the **README.OpenSource** description file in the corresponding directory; Creating **BUILD.gn** to build it independently to support the automatic collection of open source obligation declaration. ``` device/soc/$(SOC_COMPANY)/third_party @@ -51,11 +51,11 @@ For easier maintenance and evolution, comply with the following principles when ``` 14. Precompiled binary or toolchain used in the OpenHarmony, the following information needs to be provided. - - The source code corresponding to the pre-compiled binary or toolchain, which needs to store the corresponding source code in the OpenHarmony community, and provide the corresponding build guide, and provide open source obligation statement guide; + - The source code corresponding to the precompiled binary or toolchain, which needs to store the corresponding source code in the OpenHarmony community, and provide the corresponding build guide, and provide open source obligation statement guide; - Third-party software introduction for precompiled binary or toolchain, need to meet the principles 1 ~ 13; - The [prebuilt toolchain's description documentation](./prebuilts-readme-template.md): including source code acquisition address, build instructions, update methods, archived in the toolchain root directory with the toolchain build; - - The root directory corresponding to the pre-compiled binary or toolchain needs to provide notice file of the full open source obligation statement; - - If the precompiled binary files come from upstream service platform (e.g. npm packages, etc.). We need to provide the following information in the place where the binary is archived, first we need to provide a general description with the name **README**, include the following information: background description of the introduction and official website; next we need to provide a opensource obligation statement file with the name **NOTICE**, include the following information: software name, version, copyrights, and license information of every third-party open-source software. + - The root directory corresponding to the precompiled binary or toolchain needs to provide notice file of the full open source obligation statement; + - If the precompiled binary files come from upstream service platform (e.g. npm packages, etc.). We need to provide the following information in the place where the binary is archived, first we need to provide a general description with the name **README**, include the following information: background description of the introduction and official website; next we need to provide an open-source obligation statement file with the name **NOTICE**, include the following information: software name, version, copyrights, and license information of every third-party open-source software. ### Software Introduction Process diff --git a/en/contribute/license-and-copyright-specifications.md b/en/contribute/license-and-copyright-specifications.md index cfe5a427372577ef902a5604a714d9123320ed9e..169ecc44406694d1412b2b57d18618243bf51cf6 100644 --- a/en/contribute/license-and-copyright-specifications.md +++ b/en/contribute/license-and-copyright-specifications.md @@ -28,56 +28,59 @@ This document applies only to the OpenHarmony community. It is not applicable to ## Copyright and License Header 1. In principle, all files in the open-source repository must contain appropriate copyright and license header statements, except in the following scenarios: -* Adding the copyright and license header statement affects the functions of the file. For example, JSON files do not support comments, and therefore you should not add the copyright and license header to a JSON file. -* A file that is generated by the tool and contains the description indicating the automatic generation. -* A brief description file for users to read. Adding the copyright and license header affects the readability of the file, for example, **README**. - + * Adding the copyright and license header statement affects the functions of the file. For example, JSON files do not support comments, and therefore you should not add the copyright and license header to a JSON file. + * A file that is generated by the tool and contains the description indicating the automatic generation. + * A brief description file for users to read. Adding the copyright and license header affects the readability of the file, for example, **README**. 2. The format of the copyright and license header is as follows: -``` -Copyright (C) [Year of the first release]-[Year of the current release] [Copyright holder] - -The license header is subject to the specific license content. Example: - -Apache License Version 2.0 license header: -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -BSD 3-Clause license header: -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: + ``` + Copyright (C) [Year of the first release]-[Year of the current release] [Copyright holder] + + The license header is subject to the specific license content. Example: + + Apache License Version 2.0 license header: + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + BSD 3-Clause license header: + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other materials + provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors may be used + to endorse or promote products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ``` -1. Redistributions of source code must retain the above copyright notice, this list of - conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list - of conditions and the following disclaimer in the documentation and/or other materials - provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors may be used - to endorse or promote products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; -OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR -OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -``` 3. The year in the copyright header indicates the year when the work is released. If this is the first release, enter [Year of the first release]. If this is not the first release, enter [Year of the first release]-[Year of the current release]. + 4. The copyright holder is a legal entity, which can be an individual or a company. If the copyright holder contributes code on behalf of a company, enter the legal entity of the company. + 5. The license header information must be consistent with the license information of the open-source repository. If a file is a dual license, the license header must clearly describe the application conditions of each license and include the license header description defined by each license. diff --git a/en/contribute/prebuilts-readme-template.md b/en/contribute/prebuilts-readme-template.md index d106f08a850bc065e5be5d2c597058d82996fc22..41cf5c40377d63290703eae2b5fa48d886a5d6ca 100644 --- a/en/contribute/prebuilts-readme-template.md +++ b/en/contribute/prebuilts-readme-template.md @@ -1,10 +1,10 @@ -Prebuilts for Clang/LLVM-based tools used in OpenHarmony +Prebuilts for Clang/LLVM-based Tools Used in OpenHarmony ==================================================== 1. For the latest version of this doc, please make sure to visit: [OpenHarmony Clang/LLVM-based Tools Readme Doc](https://gitee.com/openharmony/third_party_llvm-project/blob/master/llvm-build/README.md) -2. Build Instructions +2. Build instructions ------------------ ``` @@ -19,9 +19,9 @@ cp -r toolchain/llvm-project/llvm-build toolchain python3 ./toolchain/llvm-build/build.py ``` -3. Update Prebuilts +3. Update prebuilts ---------------- -From an OpenHarmony project run: +From an OpenHarmony project, run: ``` $ ./build/prebuilts_download.sh diff --git a/en/contribute/writing-instructions.md b/en/contribute/writing-instructions.md index b4d2adcd9d09a5a521b835aac4c17eb667b42d4f..f1ff49c6bd1e3e066a5883c5d65e2e0aad7a7dbf 100755 --- a/en/contribute/writing-instructions.md +++ b/en/contribute/writing-instructions.md @@ -52,11 +52,13 @@ The following shows the structure of an **operation document** for porting. **Pictures** -Pictures are stored in the **pic-en** folder in the directory where the document is stored. For example, +Pictures are stored in the **images** folder in the directory where the document is stored. For example, -Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/write-standard.md** are stored in the following directory: +Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/writing-instructions.md** are stored in the following directory: -**OpenHarmony\_DOCUMENTS/docs/quick-start/pic**. Use relative paths to reference pictures in the document. +**OpenHarmony\_DOCUMENTS/docs/quick-start/images** + +Use relative paths to reference pictures in the document. >![](public_sys-resources/icon-caution.gif) **CAUTION:** >Use the original pictures to avoid intellectual property infringement risks. @@ -73,9 +75,9 @@ Pictures used in **OpenHarmony\_DOCUMENTS/docs/quick-start/write-standard.md** If a self-made picture is used, refer to the following figure to configure the color. The format can be **png**, **jpg**, **gif**, and so on. -**Figure 1** Example +**Figure 1** Color example -![](figures/example.png "example") +![](figures/color.png "color example") For screenshots, see the requirements below. If you need to highlight key information in the figure, add a red box or text remarks. @@ -89,9 +91,6 @@ English font: Arial Font size: 10 pt -**Figure 2** - - **Table** You can insert a table in **.md** documents in the following format: diff --git a/en/device-dev/driver/driver-peripherals-external-des.md b/en/device-dev/driver/driver-peripherals-external-des.md index 8c17105189ef7fef5ad99f01fa8222ea95570b80..efaf1d14e916222840d56537b48e2e19b83fb844 100644 --- a/en/device-dev/driver/driver-peripherals-external-des.md +++ b/en/device-dev/driver/driver-peripherals-external-des.md @@ -5,7 +5,7 @@ ### WLAN -The Wireless Local Area Network (WLAN) Driver module in OpenHarmony is developed based on the Hardware Driver Foundation (HDF). It features cross-OS porting, self-adaptation to component differences, and modular assembly and build. +The Wireless Local Area Network (WLAN) Driver module in OpenHarmony is developed based on the Hardware Driver Foundation (HDF). It provides cross-OS porting, self-adaptation to component differences, and module assembly and building. ### Working Principles @@ -44,7 +44,7 @@ The WLAN driver consists of the following modules: 8. NetBuf: encapsulates the unified data structure of the Linux or LiteOS native network data buffer and the operation interfaces for network data. -9. FlowCtl: performs flow control. +9. FlowCtl: processes data based on the priority when the data volume is too large. 10. HCC-CFG: configures WLAN parameters, including the board configuration, driver configuration, and module configuration. @@ -74,20 +74,10 @@ The WLAN module provides the following types of APIs: ![image](figures/WLAN_driver_APIs.png "WLAN Driver APIs") -- The WLAN module provides HDI APIs for upper-layer services (applicable to the standard system). **Table 1** describes the major APIs. - - **Table 1** IWlanInterface.idl - - | API| Description| - | -------- | -------- | - | CreateFeature([in] int type, [out] struct HdfFeatureInfo ifeature);| Creates an **ifeature** instance.| - | DestroyFeature([in] struct HdfFeatureInfo ifeature);| Destroys an **ifeature** instance.| - | GetPowerMode([in] struct HdfFeatureInfo ifeature, [out] unsigned char mode);| Obtains the power mode.| - | SetPowerMode([in] struct HdfFeatureInfo ifeature, [in] unsigned char mode);| Sets the power mode.| - The WLAN module provides HAL APIs for upper-layer services (applicable to small and mini systems). **Table 2** and **Table 3** describe some APIs. - **Table 2** wifi_hal.h + **Table 1** wifi_hal.h | API| Description| | -------- | -------- | @@ -96,7 +86,7 @@ The WLAN module provides the following types of APIs: | int32_t (\*start)(struct IWiFi \*)| Creates a channel between the HAL and the driver and obtains the NICs supported by the driver.| | int32_t (\*stop)(struct IWiFi \*)| Stops the channel between the HAL and the driver.| - **Table 3** wifi_hal_base_feature.h + **Table 2** wifi_hal_base_feature.h | API| Description| | -------- | -------- | @@ -107,387 +97,370 @@ The WLAN module provides the following types of APIs: - The WLAN Driver module also provides APIs that you need to fill in the implementation. **Table 4** describes some APIs. - **Table 4** net_device.h + **Table 3** net_device.h | API| Description| | -------- | -------- | - | int32_t (\*init)(struct NetDevice \*netDev) | Initializes a network device.| - | struct NetDevStats \*(\*getStats)(struct NetDevice \*netDev) | Obtains the state of a network device.| - | int32_t (\*setMacAddr)(struct NetDevice \*netDev, void \*addr) | Sets the MAC address.| - | void (\*deInit)(struct NetDevice \*netDev) | Deinitializes a network device.| - | int32_t (\*open)(struct NetDevice \*netDev) | Opens a network device.| - | int32_t (\*stop)(struct NetDevice \*netDev) | Stops a network device.| + | int32_t (\*init)(struct NetDevice \*netDev)| Initializes a network device.| + | struct NetDevStats \*(\*getStats)(struct NetDevice \*netDev)| Obtains the state of a network device.| + | int32_t (\*setMacAddr)(struct NetDevice \*netDev, void \*addr)| Sets the MAC address.| + | void (\*deInit)(struct NetDevice \*netDev)| Deinitializes a network device.| + | int32_t (\*open)(struct NetDevice \*netDev)| Opens a network device.| + | int32_t (\*stop)(struct NetDevice \*netDev)| Stops a network device.| - The WLAN Driver module provides APIs that you can directly use to create or release a **WifiModule**, connect to or disconnect from a WLAN hotspot, request or release a **NetBuf**, and convert between the **pbuf** structure of Lightweight IP (lwIP) and a **NetBuf**. Tables 5 to 7 describe the APIs. - **Table 5** wifi_module.h + **Table 4** wifi_module.h | API| Description| | -------- | -------- | - | struct WifiModule \*WifiModuleCreate(const struct HdfConfigWifiModuleConfig \*config) | Creates a **WifiModule**.| - | void WifiModuleDelete(struct WifiModule \*module) | Deletes a **WifiModule** and releases its data.| - | int32_t DelFeature(struct WifiModule \*module, uint16_t featureType) | Deletes a feature from a **WifiModule**.| - | int32_t AddFeature(struct WifiModule \*module, uint16_t featureType, struct WifiFeature \*featureData) | Adds a feature to a **WifiModule**.| + | struct WifiModule \*WifiModuleCreate(const struct HdfConfigWifiModuleConfig \*config)| Creates a **WifiModule**.| + | void WifiModuleDelete(struct WifiModule \*module)| Deletes a **WifiModule** and releases its data.| + | int32_t DelFeature(struct WifiModule \*module, uint16_t featureType)| Deletes a feature from a **WifiModule**.| + | int32_t AddFeature(struct WifiModule \*module, uint16_t featureType, struct WifiFeature \*featureData)| Adds a feature to a **WifiModule**.| - **Table 6** wifi_mac80211_ops.h + **Table 5** wifi_mac80211_ops.h | API| Description| | -------- | -------- | - | int32_t (\*startAp)(NetDevice \*netDev) | Starts an AP.| - | int32_t (\*stopAp)(NetDevice \*netDev) | Stops an AP.| - | int32_t (\*connect)(NetDevice \*netDev, WifiConnectParams \*param) | Connects to a hotspot.| - | int32_t (\*disconnect)(NetDevice \*netDev, uint16_t reasonCode) | Disconnects from a hotspot.| + | int32_t (\*startAp)(NetDevice \*netDev)| Starts an AP.| + | int32_t (\*stopAp)(NetDevice \*netDev)| Stops an AP.| + | int32_t (\*connect)(NetDevice \*netDev, WifiConnectParams \*param)| Connects to a hotspot.| + | int32_t (\*disconnect)(NetDevice \*netDev, uint16_t reasonCode)| Disconnects from a hotspot.| - **Table 7** hdf_netbuf.h + **Table 6** hdf_netbuf.h | API| Description| | -------- | -------- | - | static inline void NetBufQueueInit(struct NetBufQueue \*q) | Initializes a **NetBuf** queue.| - | struct NetBuf \*NetBufAlloc(uint32_t size) | Allocates a **NetBuf**.| + | static inline void NetBufQueueInit(struct NetBufQueue \*q)| Initializes a **NetBuf** queue.| + | struct NetBuf \*NetBufAlloc(uint32_t size)| Allocates a **NetBuf**.| | void NetBufFree(struct NetBuf \*nb) | Releases a **NetBuf**.| - | struct NetBuf \*Pbuf2NetBuf(const struct NetDevice \*netdev, struct pbuf \*lwipBuf) | Converts the **pbuf** structure of lwIP to a **NetBuf**.| - | struct pbuf \*NetBuf2Pbuf(const struct NetBuf \*nb) | Converts a **NetBuf** to the **pbuf** structure of lwIP.| + | struct NetBuf \*Pbuf2NetBuf(const struct NetDevice \*netdev, struct pbuf \*lwipBuf)| Converts the **pbuf** structure of lwIP to a **NetBuf**.| + | struct pbuf \*NetBuf2Pbuf(const struct NetBuf \*nb)| Converts a **NetBuf** to the **pbuf** structure of lwIP.| ### How to Develop +#### WLAN Framework Adaptation -The WLAN driver module developed based on the HDF and Platform frameworks provides a unified driver model for WLAN modules of different vendors regardless of the OS and system on a chip (SoC). +The WLAN driver framework developed based on the HDF and Platform framework provides a unified driver model regardless of the OS and system on a chip (SoC). When developing your WLAN driver, you need to configure data based on the WLAN driver framework. +**Development Procedure** - 1. Configure hardware (such as modules and chips) parameters in the **wlan_platform.hcs** file. This file can be parsed by the APIs in the HDF to generate structure objects with full configuration. +1. Configure hardware (such as modules and chips) parameters in the **wlan_platform.hcs** file. The HDF parses the file to generate structure objects with full configuration. - 2. Implement initialization and deinitialization of the WLAN module (such as initialize and deinitialize the WLAN chip and WLAN chip driver). +2. Implement initialization and deinitialization of the WLAN module (such as initialize and deinitialize the WLAN chip and WLAN chip driver). - 3. Implement the delivery of control flow commands. +3. Implement the delivery of control flow commands. - 4. Implement event reporting. +4. Implement event reporting. -### Development Example +**Development Example** The following uses the Hi3881 WLAN chip as an example to describe how to initialize a WLAN module. -1. Configure hardware parameters. - - ```text - /* Configure parameters in wlan_platform.hcs based on the hardware you use. The following is an example of WLAN platform configuration. */ - hisi :& deviceList { - device0 :: deviceInst { - deviceInstId = 0; - powers { - power0 { - powerSeqDelay = 0; /* Power sequence delay. */ - powerType = 1; /* Power supply type. The value 0 indicates that the device is always on. The value 1 indicates power supply through GPIO. */ - gpioId = 1; /* GPIO pin number. */ - activeLevel=1; /* Active level. The value 0 indicates low level, and 1 indicates high level. */ +1. Configure the HDF configuration source (HCS) for the driver. + + The HCS includes device configuration and component configuration. + + - Device configuration + + The configuration file contains the power supply, reset, and bus configuration. + + Configuration file path: **vendor///hdf_config/khdf/wifi** + + Configure device parameters in **wlan_platform.hcs** based on the device you use. The following is an example of WLAN platform configuration. + ```text + hisi :& deviceList { + device0 :: deviceInst { + deviceInstId = 0; + powers { + power0 { + powerSeqDelay = 0; /* Power sequence delay. */ + powerType = 1; /* Power supply type. The value 0 indicates that the device is always on. The value 1 indicates power supply through GPIO. */ + gpioId = 1; /* GPIO pin number. */ + activeLevel=1; /* Active level. The value 0 indicates low level, and 1 indicates high level. */ + } + power1 { + powerSeqDelay = 0; /* Power sequence delay. */ + powerType = 0; /* Power supply type. The value 0 indicates that the device is always on. The value 1 indicates power supply through GPIO. */ + } } - power1 { - powerSeqDelay = 0; /* Power sequence delay. */ - powerType = 0; /* Power supply type. The value 0 indicates that the device is always on. The value 1 indicates power supply through GPIO. */ + reset { + resetType = 0; /* Reset type. The value 0 indicates that reset is dynamically determined, and 1 indicates reset through GPIO. */ + gpioId = 2; /* GPIO pin number. */ + activeLevel=1; /* Active level. The value 0 indicates low level, and 1 indicates high level. */ + resetHoldTime = 30; /* Hold time (ms) after a reset. */ + } + bootUpTimeout = 30; /* Boot timeout duration (ms). */ + bus { + busEnable = 1; /* Whether to initialize the bus. The value 1 means to initialize the bus; the value 0 means the opposite. */ + busType = 0; /* Bus type. The value 0 indicates SDIO. */ + busId = 2; /* Bus number. */ + funcNum = [1]; /* SDIO function number. */ + timeout = 1000; /* Timeout duration for data read/write. */ + blockSize = 512; /* Size of the data block to read or write. */ } - } - reset { - resetType = 0; /* Reset type. The value 0 indicates that reset is dynamically determined, and 1 indicates reset through GPIO. */ - gpioId = 2; /* GPIO pin number. */ - activeLevel=1; /* Active level. The value 0 indicates low level, and 1 indicates high level. */ - resetHoldTime = 30; /* Hold time (ms) after a reset. */ - } - bootUpTimeout = 30; /* Boot timeout duration (ms). */ - bus { - busEnable = 1; /* Whether to initialize the bus. The value 1 means to initialize the bus; the value 0 means the opposite. */ - busType = 0; /* Bus type. The value 0 indicates SDIO. */ - busId = 2; /* Bus number. */ - funcNum = [1]; /* SDIO function number. */ - timeout = 1000; /* Timeout duration for data read/write. */ - blockSize = 512; /* Size of the data block to read or write. */ } } - } - /* Add the configuration file wlan_chip_.hcs (for example, wlan_chip_hi3881.hcs) for each chip and set parameters. The following uses the Hi3881 chip as an example. */ - root { - wlan_config { - hi3881 :& chipList { - chipHi3881 :: chipInst { - match_attr = "hdf_wlan_chips_hi3881"; /* Attribute used to match the chip. */ - chipName = "hi3881"; /* WLAN chip name. */ - bus { - vendorId = 0x0296; /* Vendor ID. */ - deviceId = [0x5347]; /* Device ID. */ + ``` + - Component configuration + + Add a configuration file **wlan_chip_.hcs** for each chip, for example, **wlan_chip_hi3881.hcs**, and configure related parameters. The following is a configuration example of hi3881. + ```text + root { + wlan_config { + hi3881 :& chipList { + chipHi3881 :: chipInst { + match_attr = "hdf_wlan_chips_hi3881"; /* Attribute used to match the chip. */ + chipName = "hi3881"; /* WLAN chip name. */ + bus { + vendorId = 0x0296; /* Vendor ID. */ + deviceId = [0x5347]; /* Device ID. */ + } } } } } - } - ``` + ``` 2. Hook the **init** and **deinit** functions of the WLAN chip and WLAN chip driver. + - Implementing the driver adaptation entry function - ```c - #include "hdf_device_desc.h" - #include "hdf_wifi_product.h" - #include "hdf_log.h" - #include "osal_mem.h" - #include "hdf_wlan_chipdriver_manager.h" - #include "securec.h" - #include "wifi_module.h" - #include "hi_wifi_api.h" - #include "hi_types_base.h" - - #define HDF_LOG_TAG Hi3881Driver - - /* Functions for initializing and deinitializing a WLAN chip. */ - int32_t InitHi3881Chip(struct HdfWlanDevice *device); - int32_t DeinitHi3881Chip(struct HdfWlanDevice *device); - /* Functions for initializing and deinitializing a WLAN chip driver. */ - int32_t Hi3881Deinit(struct HdfChipDriver* chipDriver, struct NetDevice *netDevice); - int32_t Hi3881Init(struct HdfChipDriver* chipDriver, struct NetDevice *netDevice); - - /* Initialize mac80211 by hooking the functions of the chip. */ - hi_void HiMac80211Init(struct HdfChipDriver *chipDriver); - - static const char* const HI3881_DRIVER_NAME = "hisi"; - - /* Hook the functions of the WLAN chip driver, mac80211, and chip. */ - static struct HdfChipDriver *BuildHi3881Driver(struct HdfWlanDevice *device, uint8_t ifIndex) - { - struct HdfChipDriver *specificDriver = NULL; - if (device == NULL) { - HDF_LOGE("%s fail: channel is NULL!", __func__); - return NULL; - } - (void)ifIndex; - specificDriver = (struct HdfChipDriver *)OsalMemCalloc(sizeof(struct HdfChipDriver)); - if (specificDriver == NULL) { - HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); - return NULL; - } - if (memset_s(specificDriver, sizeof(struct HdfChipDriver), 0, sizeof(struct HdfChipDriver)) != EOK) { - HDF_LOGE("%s fail: memset_s fail!", __func__); - OsalMemFree(specificDriver); - return NULL; - } - - if (strcpy_s(specificDriver->name, MAX_WIFI_COMPONENT_NAME_LEN, HI3881_DRIVER_NAME) != EOK) { - HDF_LOGE("%s fail: strcpy_s fail!", __func__); - OsalMemFree(specificDriver); - return NULL; - } - specificDriver->init = Hi3881Init; - specificDriver->deinit = Hi3881Deinit; - - HiMac80211Init(specificDriver); - - return specificDriver; - } - - /* Release the WLAN chip driver. */ - static void ReleaseHi3881Driver(struct HdfChipDriver *chipDriver) - { - if (chipDriver == NULL) { - return; - } - if (strcmp(chipDriver->name, HI3881_DRIVER_NAME) != 0) { - HDF_LOGE("%s:Not my driver!", __func__); - return; - } - OsalMemFree(chipDriver); - } - - static uint8_t GetHi3881GetMaxIFCount(struct HdfChipDriverFactory *factory) { - (void)factory; - return 1; - } - - /* Register WLAN chip functions. */ - static int32_t HDFWlanRegHisiDriverFactory(void) - { - static struct HdfChipDriverFactory tmpFactory = { 0 }; - struct HdfChipDriverManager *driverMgr = NULL; - driverMgr = HdfWlanGetChipDriverMgr(); - if (driverMgr == NULL) { - HDF_LOGE("%s fail: driverMgr is NULL!", __func__); - return HDF_FAILURE; - } - tmpFactory.driverName = HI3881_DRIVER_NAME; - tmpFactory.GetMaxIFCount = GetHi3881GetMaxIFCount; - tmpFactory.InitChip = InitHi3881Chip; - tmpFactory.DeinitChip = DeinitHi3881Chip; - tmpFactory.Build = BuildHi3881Driver; - tmpFactory.Release = ReleaseHi3881Driver; - tmpFactory.ReleaseFactory = NULL; - if (driverMgr->RegChipDriver(&tmpFactory) != HDF_SUCCESS) { - HDF_LOGE("%s fail: driverMgr is NULL!", __func__); - return HDF_FAILURE; - } - - return HDF_SUCCESS; - } - - static int32_t HdfWlanHisiChipDriverInit(struct HdfDeviceObject *device) - { - (void)device; - return HDFWlanRegHisiDriverFactory(); - } - - struct HdfDriverEntry g_hdfHisiChipEntry = { + Define a variable of the HdfDriverEntry type based on the chip to hook functions of **Bind()**, **Init()**, and **Release()**. Call **HDF_INIT** to register the driver entry with the HDF. During driver loading, the HDF calls the **Bind** function and then the **Init** function to load the driver. If **Init()** fails to be called, the HDF calls **Release()** to release driver resources. + ```c + struct HdfDriverEntry g_hdfHisiChipEntry = { .moduleVersion = 1, .Bind = HdfWlanHisiDriverBind, .Init = HdfWlanHisiChipDriverInit, .Release = HdfWlanHisiChipRelease, .moduleName = "HDF_WLAN_CHIPS" - }; - - HDF_INIT(g_hdfHisiChipEntry); - ``` - - For details about initialization of the chip and chip driver, see hdfinit_3881.c. The functions are as follows: - - ```c - #include "hdf_wifi_product.h" - #include "hi_wifi_api.h" - #if (_PRE_OS_VERSION_LINUX == _PRE_OS_VERSION) - #include "oal_thread.h" - #include "osal_time.h" - #endif - #include "wifi_mac80211_ops.h" - #include "wal_cfg80211.h" - #include "net_adapter.h" - #include "hdf_wlan_utils.h" - - #define HDF_LOG_TAG Hi3881Driver - - /* Initialize the WLAN chip. */ - int32_t InitHi3881Chip(struct HdfWlanDevice *device) - { - uint8_t maxPortCount = 3; - int32_t ret = HI_SUCCESS; - uint8_t maxRetryCount = 3; - if (device == NULL || device->bus == NULL) { - HDF_LOGE("%s:NULL ptr!", __func__); - return HI_FAIL; - } - - do { - if (ret != HI_SUCCESS) { - if (device->reset != NULL && device->reset->Reset != NULL) { - device->reset->Reset(device->reset); - } - HDF_LOGE("%s:Retry init hi3881!last ret=%d", __func__, ret); - } - ret = hi_wifi_init(maxPortCount, device->bus); - } while (ret != 0 && --maxRetryCount > 0); - - if (ret != 0) { - HDF_LOGE("%s:Init hi3881 driver failed!", __func__); - return ret; - } - return HI_SUCCESS; - } - - /* Deinitializing the WLAN chip. */ - int32_t DeinitHi3881Chip(struct HdfWlanDevice *device) - { - (void)device; - int32_t ret = hi_wifi_deinit(); - if (ret != 0) { - HDF_LOGE("%s:Deinit failed!ret=%d", __func__, ret); - } - return ret; - } - - /* Initializing the WLAN chip driver. */ - int32_t Hi3881Init(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) - { - hi_u16 mode; - int32_t ret; - nl80211_iftype_uint8 type; - (void)chipDriver; - HDF_LOGI("%s: start...", __func__); - mode = wal_get_vap_mode(); - if (mode >= WAL_WIFI_MODE_BUTT) { - oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); - return HI_FAIL; - } - if (mode == WAL_WIFI_MODE_STA) { - type = NL80211_IFTYPE_STATION; - #ifdef _PRE_WLAN_FEATURE_P2P - if (InitNetdev(netDevice, NL80211_IFTYPE_P2P_DEVICE) != HI_SUCCESS) { - return HI_FAIL; - } - #endif - } else if (mode == WAL_WIFI_MODE_AP) { - type = NL80211_IFTYPE_AP; - } else { - oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); - return HI_FAIL; - } - ret = wal_init_drv_wlan_netdev(type, WAL_PHY_MODE_11N, netDevice); - if (ret != HI_SUCCESS) { - oam_error_log2(0, OAM_SF_ANY, "wal_init_drv_netdev %s failed.l_return:%d\n", netDevice->name, ret); - } - return ret; - } - - /* Deinitializing the WLAN chip driver. */ - int32_t Hi3881Deinit(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) - { - int32_t ret; - (void)chipDriver; - ret = DeinitNetdev(NL80211_IFTYPE_P2P_DEVICE); - if (ret != HI_SUCCESS) { - oam_error_log1(0, OAM_SF_ANY, "Hi3881Deinit: DeinitNetdev p2p device fail, ret = %d\n", ret); - return ret; - } - return wal_deinit_drv_wlan_netdev(netDevice); - } - - ``` - - During the chip initialization process, call **NetDeviceInit()** to initialize a network device, call **NetDeviceAdd()** to add the network device to a protocol stack, and hook function pointers of **netdev**. - - ```c - hi_s32 wal_init_drv_wlan_netdev(nl80211_iftype_uint8 type, wal_phy_mode mode, oal_net_device_stru *netdev) - { - hi_char *ac_mode_str = NULL; - hi_s32 ret; - if (oal_unlikely(netdev == HI_NULL)) { - oam_error_log0(0, OAM_SF_ANY, "{netdev is null!}"); - return HI_ERR_CODE_PTR_NULL; - } - - do { - /* Initialize the network device. */ - ret = wal_init_netdev(type, netdev); - if (ret != HI_SUCCESS) { - break; - } - - ret = wal_init_netif(type, netdev); - if (ret != HI_SUCCESS) { - break; - } - ac_mode_str = "11bgn"; - if (mode == WAL_PHY_MODE_11G) { - ac_mode_str = "11bg"; - } else if (mode == WAL_PHY_MODE_11B) { - ac_mode_str = "11b"; - } - - ret = wal_ioctl_set_mode(netdev, ac_mode_str); - } while (false); - - if (ret != HI_SUCCESS) { - wal_deinit_wlan_vap(netdev); - oal_net_unregister_netdev(netdev); - oal_net_clear_netdev(netdev); - return HI_FAIL; - } - - return HI_SUCCESS; - } - - /* Hook function pointers of netdev. For details, see NetDeviceInterFace. */ - oal_net_device_ops_stru g_wal_net_dev_ops = - { + }; + + HDF_INIT(g_hdfHisiChipEntry); + ``` + + - Registering the functions for initializing the chip and chip driver + + Hook the chip initialization function to **InitChip()** and the chip deinitialization function to **DeinitChip()**. + + Hook the chip driver initialization function to **Build()** and the chip driver deinitialization function to **Release()**. + + ```c + /* Register WLAN chip functions. */ + static int32_t HDFWlanRegHisiDriverFactory(void) + { + static struct HdfChipDriverFactory tmpFactory = { 0 }; + struct HdfChipDriverManager *driverMgr = NULL; + driverMgr = HdfWlanGetChipDriverMgr(); + if (driverMgr == NULL) { + HDF_LOGE("%s fail: driverMgr is NULL!", __func__); + return HDF_FAILURE; + } + tmpFactory.driverName = HI3881_DRIVER_NAME; + tmpFactory.GetMaxIFCount = GetHi3881GetMaxIFCount; + tmpFactory.InitChip = InitHi3881Chip; + tmpFactory.DeinitChip = DeinitHi3881Chip; + tmpFactory.Build = BuildHi3881Driver; + tmpFactory.Release = ReleaseHi3881Driver; + tmpFactory.ReleaseFactory = NULL; + if (driverMgr->RegChipDriver(&tmpFactory) != HDF_SUCCESS) { + HDF_LOGE("%s fail: driverMgr is NULL!", __func__); + return HDF_FAILURE; + } + + return HDF_SUCCESS; + } + + static int32_t HdfWlanHisiChipDriverInit(struct HdfDeviceObject *device) + { + (void)device; + return HDFWlanRegHisiDriverFactory(); + } + ``` + + - Initializing and deinitializing the chip + ```c + /* Function for initializing the WLAN chip. */ + int32_t InitHi3881Chip(struct HdfWlanDevice *device) + { + uint8_t maxPortCount = 3; + int32_t ret = HI_SUCCESS; + uint8_t maxRetryCount = 3; + if (device == NULL || device->bus == NULL) { + HDF_LOGE("%s:NULL ptr!", __func__); + return HI_FAIL; + } + + do { + if (ret != HI_SUCCESS) { + if (device->reset != NULL && device->reset->Reset != NULL) { + device->reset->Reset(device->reset); + } + HDF_LOGE("%s:Retry init hi3881!last ret=%d", __func__, ret); + } + ret = hi_wifi_init(maxPortCount, device->bus); + } while (ret != 0 && --maxRetryCount > 0); + + if (ret != 0) { + HDF_LOGE("%s:Init hi3881 driver failed!", __func__); + return ret; + } + return HI_SUCCESS; + } + + /* Function for deinitializing the WLAN chip. */ + int32_t DeinitHi3881Chip(struct HdfWlanDevice *device) + { + (void)device; + int32_t ret = hi_wifi_deinit(); + if (ret != 0) { + HDF_LOGE("%s:Deinit failed!ret=%d", __func__, ret); + } + return ret; + } + ``` + - Initializing and deinitializing the chip driver + ```c + /* Hook the functions of the WLAN chip driver, mac80211, and chip. */ + static struct HdfChipDriver *BuildHi3881Driver(struct HdfWlanDevice *device, uint8_t ifIndex) + { + struct HdfChipDriver *specificDriver = NULL; + if (device == NULL) { + HDF_LOGE("%s fail: channel is NULL!", __func__); + return NULL; + } + (void)ifIndex; + specificDriver = (struct HdfChipDriver *)OsalMemCalloc(sizeof(struct HdfChipDriver)); + if (specificDriver == NULL) { + HDF_LOGE("%s fail: OsalMemCalloc fail!", __func__); + return NULL; + } + if (memset_s(specificDriver, sizeof(struct HdfChipDriver), 0, sizeof(struct HdfChipDriver)) != EOK) { + HDF_LOGE("%s fail: memset_s fail!", __func__); + OsalMemFree(specificDriver); + return NULL; + } + + if (strcpy_s(specificDriver->name, MAX_WIFI_COMPONENT_NAME_LEN, HI3881_DRIVER_NAME) != EOK) { + HDF_LOGE("%s fail: strcpy_s fail!", __func__); + OsalMemFree(specificDriver); + return NULL; + } + specificDriver->init = Hi3881Init; + specificDriver->deinit = Hi3881Deinit; + + HiMac80211Init(specificDriver); + + return specificDriver; + } + + /* Release the WLAN chip driver. */ + static void ReleaseHi3881Driver(struct HdfChipDriver *chipDriver) + { + if (chipDriver == NULL) { + return; + } + if (strcmp(chipDriver->name, HI3881_DRIVER_NAME) != 0) { + HDF_LOGE("%s:Not my driver!", __func__); + return; + } + OsalMemFree(chipDriver); + } + + /* Function for initializing the WLAN chip driver. */ + int32_t Hi3881Init(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) + { + hi_u16 mode; + int32_t ret; + nl80211_iftype_uint8 type; + (void)chipDriver; + HDF_LOGI("%s: start...", __func__); + mode = wal_get_vap_mode(); + if (mode >= WAL_WIFI_MODE_BUTT) { + oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); + return HI_FAIL; + } + if (mode == WAL_WIFI_MODE_STA) { + type = NL80211_IFTYPE_STATION; + #ifdef _PRE_WLAN_FEATURE_P2P + if (InitNetdev(netDevice, NL80211_IFTYPE_P2P_DEVICE) != HI_SUCCESS) { + return HI_FAIL; + } + #endif + } else if (mode == WAL_WIFI_MODE_AP) { + type = NL80211_IFTYPE_AP; + } else { + oam_error_log1(0, 0, "wal_init_drv_netdev:: invalid mode[%d]", mode); + return HI_FAIL; + } + ret = wal_init_drv_wlan_netdev(type, WAL_PHY_MODE_11N, netDevice); + if (ret != HI_SUCCESS) { + oam_error_log2(0, OAM_SF_ANY, "wal_init_drv_netdev %s failed.l_return:%d\n", netDevice->name, ret); + } + return ret; + } + + /* Function for deinitializing the WLAN chip driver. */ + int32_t Hi3881Deinit(struct HdfChipDriver *chipDriver, struct NetDevice *netDevice) + { + int32_t ret; + (void)chipDriver; + ret = DeinitNetdev(NL80211_IFTYPE_P2P_DEVICE); + if (ret != HI_SUCCESS) { + oam_error_log1(0, OAM_SF_ANY, "Hi3881Deinit: DeinitNetdev p2p device fail, ret = %d\n", ret); + return ret; + } + return wal_deinit_drv_wlan_netdev(netDevice); + } + + ``` + + During the chip initialization process, call **NetDeviceInit()** to initialize a network device, call **NetDeviceAdd()** to add the network device to a protocol stack, and hook function pointers of **netdev**. + + ```c + hi_s32 wal_init_drv_wlan_netdev(nl80211_iftype_uint8 type, wal_phy_mode mode, oal_net_device_stru *netdev) + { + hi_char *ac_mode_str = NULL; + hi_s32 ret; + if (oal_unlikely(netdev == HI_NULL)) { + oam_error_log0(0, OAM_SF_ANY, "{netdev is null!}"); + return HI_ERR_CODE_PTR_NULL; + } + + do { + /* Initialize the network device. */ + ret = wal_init_netdev(type, netdev); + if (ret != HI_SUCCESS) { + break; + } + + ret = wal_init_netif(type, netdev); + if (ret != HI_SUCCESS) { + break; + } + ac_mode_str = "11bgn"; + if (mode == WAL_PHY_MODE_11G) { + ac_mode_str = "11bg"; + } else if (mode == WAL_PHY_MODE_11B) { + ac_mode_str = "11b"; + } + + ret = wal_ioctl_set_mode(netdev, ac_mode_str); + } while (false); + + if (ret != HI_SUCCESS) { + wal_deinit_wlan_vap(netdev); + oal_net_unregister_netdev(netdev); + oal_net_clear_netdev(netdev); + return HI_FAIL; + } + + return HI_SUCCESS; + } + + /* Hook function pointers of netdev. For details, see NetDeviceInterFace. */ + oal_net_device_ops_stru g_wal_net_dev_ops = + { .getStats = wal_netdev_get_stats, .open = wal_netdev_open, .stop = wal_netdev_stop, @@ -496,26 +469,21 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial .changeMtu = oal_net_device_change_mtu, .init = oal_net_device_init, .deInit = oal_net_free_netdev, - #if (defined(_PRE_WLAN_FEATURE_FLOWCTL) || defined(_PRE_WLAN_FEATURE_OFFLOAD_FLOWCTL)) - .selectQueue = wal_netdev_select_queue, - #endif - .setMacAddr = wal_netdev_set_mac_addr, - #if (_PRE_OS_VERSION_LITEOS == _PRE_OS_VERSION) - .netifNotify = HI_NULL, - #endif - .specialEtherTypeProcess = SpecialEtherTypeProcess, - }; + + ... - hi_s32 wal_init_netif(nl80211_iftype_uint8 type, oal_net_device_stru *netdev, const oal_wireless_dev *wdev) - { - /* Add the network device to the protocol stack. */ - hi_u32 ret = NetDeviceAdd(netdev, (Protocol80211IfType)type); + }; - ... + hi_s32 wal_init_netif(nl80211_iftype_uint8 type, oal_net_device_stru *netdev, const oal_wireless_dev *wdev) + { + /* Add the network device to the protocol stack. */ + hi_u32 ret = NetDeviceAdd(netdev, (Protocol80211IfType)type); - return HI_SUCCESS; - } - ``` + ... + + return HI_SUCCESS; + } + ``` 3. Bind the commands to be delivered, including setting the MAC address and transmit power, implement STA connection and scan, start APs, and setting the country code. @@ -580,8 +548,10 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial 4. Invoke the event reporting APIs. - The WLAN framework provides the event reporting APIs. For details, see hdf_wifi_event.c. For example, call **HdfWiFiEventNewSta AP** to report information about the newly associated STA. - + The WLAN framework provides the event reporting APIs. For details, see **hdf_wifi_event.c**. + + For example, call **HdfWiFiEventNewSta AP** to report information about the newly associated STA. + ```c hi_u32 oal_cfg80211_new_sta(oal_net_device_stru *net_device, const hi_u8 *mac_addr, hi_u8 addr_len, oal_station_info_stru *station_info, oal_gfp_enum_uint8 en_gfp) @@ -595,13 +565,15 @@ The following uses the Hi3881 WLAN chip as an example to describe how to initial info.assocReqIesLen = station_info->assoc_req_ies_len; HdfWifiEventNewSta(net_device, mac_addr, WLAN_MAC_ADDR_LEN, &info); hi_unref_param(en_gfp); - hi_unref_param(addr_len); + hi_unref_param(addr_len); #endif return HI_SUCCESS; } ``` -## Verification + + +**Verification** Develop test cases in the WLAN module unit test to verify the basic features of the WLAN module. The following uses Hi3516D V300 standard system as an example. @@ -678,7 +650,7 @@ Develop test cases in the WLAN module unit test to verify the basic features of exit 0 ``` - - Create a **udhcpd.conf** file (used to start the **udhcpd**) and copy the following content to the file. In the following, **opt dns** *x.x.x.x* *x.x.x.x* indicates two DNS servers configured. You can configure DNS servers as required. + - Create a **udhcpd.conf** file (used to start the **udhcpd**) and copy the following content to the file. In the following, **opt dns** *x.x.x.x* *x.x.x.x* indicates two DNS servers configured. You can configure DNS servers as required. ```text start 192.168.12.2 @@ -737,45 +709,55 @@ Develop test cases in the WLAN module unit test to verify the basic features of The network name and password are configured in the **hostapd.conf** file. You can see that network name in the connected Wi-Fi list if the connection is successful. 5. Ping the test terminal from the development board. - + ```shell busybox ping xxx.xxx.xxx.xxx ``` In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. - - Verify basic STA features. + - 1. Start the STA on the development board, and enable the hotspot on the test terminal. (The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**.) + - Verify basic STA features. + 1. Start the STA on the development board, and enable the hotspot on the test terminal. + + The hotspot name and password are configured in the **hostapd.conf** file. The hotspot name is **test**, and the password is **12345678**. + 2. Run the following command in the **cmd** window: - + ```shell hdc shell wpa_supplicant -i wlan0 -d -c wpa_supplicant.conf ``` - + + + 3. Run the following commands in another **cmd** window: - + ```shell hdc shell mount -o rw,remount / mount -o rw,remount /vendor busybox udhcpc -i wlan0 -s system/lib/dhcpc.sh ``` + The IP addresses of the board and test terminal are displayed if the command is successful. - + 4. Ping the test terminal from the development board. - + ```shell busybox ping xxx.xxx.xxx.xxx ``` + + In the command, *xxx.xxx.xxx.xxx* indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. + - In the command, xxx.xxx.xxx.xxx indicates the IP address of the test terminal. If the test terminal can be pinged, the WLAN driver provides basic features normally. - -3. Verify the unit test cases. +#### **API Invocation** +The WLAN driver module provides two types of capability interfaces for the upper layer: HDI interface and HAL interface. +- HDI API invocation - To test a specified interface of the HDI module, perform the following steps: + The following uses **GetSupportFeature** as an example to describe the development procedure: 1. Call **WlanInterfaceGetInstance()** to obtain a WLAN service instance. @@ -788,23 +770,22 @@ Develop test cases in the WLAN module unit test to verify the basic features of 5. Call **WlanInterfaceRelease()** to destroy the WLAN service instance. The sample code is as follows: - - ```c - #include "v1_0/iwlan_interface.h" - #include "wlan_callback_impl.h" - #include "wlan_impl.h" + ```c + #include "v1_0/iwlan_interface.h" + #include "wlan_callback_impl.h" + #include "wlan_impl.h" - #define PROTOCOL_80211_IFTYPE_NUM 11; - #define HDF_SUCCESS 0 - #define HDF_FAILURE (-1) - - static int32_t hdi_main() - { - int32_t rc; - const char *WLAN_SERVICE_NAME = "wlan_hal_c_service"; - static struct IWlanInterface *g_wlanObj = NULL; - uint8_t supType[PROTOCOL_80211_IFTYPE_NUM + 1] = {0}; - uint32_t supTypeLen = PROTOCOL_80211_IFTYPE_NUM + 1; + #define PROTOCOL_80211_IFTYPE_NUM 11 + #define HDF_SUCCESS 0 + #define HDF_FAILURE (-1) + + static int32_t hdi_main() + { + int32_t rc; + const char *WLAN_SERVICE_NAME = "wlan_hal_c_service"; + static struct IWlanInterface *g_wlanObj = NULL; + uint8_t supType[PROTOCOL_80211_IFTYPE_NUM + 1] = {0}; + uint32_t supTypeLen = PROTOCOL_80211_IFTYPE_NUM + 1; /* Obtain the WLAN service instance. */ g_wlanObj = WlanInterfaceGetInstance(WLAN_SERVICE_NAME); @@ -842,7 +823,30 @@ Develop test cases in the WLAN module unit test to verify the basic features of } return rc; } - ``` + + ``` + + Building: + + 1. Add the dependent library file to the build script. + + ```text + deps = [ + "//drivers/peripheral/wlan/hdi_service:hdi_wlan_service", + ] + ``` + 2. Add the dependent header files to the build script. + ```text + include_dirs = [ + "//drivers/peripheral/wlan/interfaces/include", + "//drivers/peripheral/wlan/hdi_service", + "//drivers/peripheral/wlan/client/include", + "//drivers/peripheral/wlan/hal/include", + ] + ``` + 3. Run the build script and check whether the build is successful. + +- HAL API invocation To test a specified interface of the HAL module, perform the following steps: @@ -856,67 +860,65 @@ Develop test cases in the WLAN module unit test to verify the basic features of 5. Call **destroyFeature()** to destroy the **apFeature** instance. - 6. Call **stop()** to destroy the channel between the HAL and the driver. + 6. Call **Stop()** to destroy the channel between the HAL and the driver. 7. Call **WifiDestruct()** to destroy the **IWiFi** instance. The sample code is as follows: - ```c + ```c #include "wifi_hal.h" #include "wifi_hal_sta_feature.h" #include "wifi_hal_ap_feature.h" #include "wifi_hal_cmd.h" - #include "wifi_hal_event.h" #define MAC_LEN 6 #define HDF_SUCCESS 0 #define HDF_FAILURE (-1) - ``` - static int32_t hal_main() { int32_t ret; struct IWiFi *wifi; + struct IWiFiAp *apFeature; /* Create an IWiFi instance. */ ret = WifiConstruct(&wifi); if (ret != HDF_SUCCESS || wifi == NULL) { return HDF_FAILURE; } - + /* Create a channel between the HAL and the driver and obtain the driver NIC information. */ ret = wifi->start(wifi); if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - + /* Create an apFeature instance. */ ret = wifi->createFeature(PROTOCOL_80211_IFTYPE_AP, (struct IWiFiBaseFeature **)&apFeature); if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - + /* Obtain the MAC address of the device. */ unsigned char mac[MAC_LEN] = {0}; ret = apFeature->baseFeature.getDeviceMacAddress((struct IWiFiBaseFeature *)apFeature, mac, MAC_LEN); if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - + /* Destroy the apFeature instance. */ ret = wifi->destroyFeature((struct IWiFiBaseFeature *)apFeature); if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - + /* Destroy the channel between the HAL and the driver. */ ret = wifi->stop(wifi); if (ret != HDF_SUCCESS) { return HDF_FAILURE; } - + /* Destroy the IWiFi instance. */ ret = WifiDestruct(&wifi); if (ret != HDF_SUCCESS) { @@ -924,31 +926,30 @@ Develop test cases in the WLAN module unit test to verify the basic features of } return ret; } - ``` - -4. Verify the test cases. - 1. Push the test cases to the development board. - - ```shell - hdc file send /xxx /data - ``` - - In the command, xxx indicates the path of the test cases of the development board. - - 2. Modify the permissions on the test cases and execute the test cases. - - ```shell - hdc shell - cd data - chmod 777 Test_case_name - ./ Test case name. - ``` - - - - 3. Check the test case execution result. + ``` + Building: + 1. Add the dependent library file to the build script. + + ```text + deps = [ + "//drivers/peripheral/wlan/client:wifi_driver_client", + "//drivers/peripheral/wlan/hal:wifi_hal", + ] + ``` + + 2. Add the dependent header files to the build script. + ```text + include_dirs = [ + "//drivers/peripheral/wlan/interfaces/include", + "//drivers/peripheral/wlan/hdi_service", + "//drivers/peripheral/wlan/client/include", + "//drivers/peripheral/wlan/hal/include", + ] + ``` + 3. Run the build script and check whether the build is successful. + - + ## Reference @@ -962,34 +963,19 @@ Develop test cases in the WLAN module unit test to verify the basic features of - Code paths: - - Adaptation of WLAN FlowCtl component on LiteOS: - - **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi** - - - Adaptation of HDF network model on LiteOS: - - **//drivers/hdf_core/adapter/khdf/liteos/model/network** - - - Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: - - **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi** - - - Core code for implementing the WLAN module: - - **//drivers/hdf_core/framework/model/network/wifi** - - - External APIs of the WLAN module: + - Adaptation of WLAN FlowCtl component on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network/wifi** + - Adaptation of HDF network model on LiteOS: **//drivers/hdf_core/adapter/khdf/liteos/model/network** + + - Adaptation of WLAN FlowCtl component on Linux, build of the HDF WLAN model, and build of the vendor's WLAN driver: **//drivers/hdf_core/adapter/khdf/linux/model/network/wifi** + - Core code for implementing the WLAN module: **//drivers/hdf_core/framework/model/network/wifi** + - External APIs of the WLAN module: **//drivers/hdf_core/framework/include/wifi** + - HDF network model APIs: **//drivers/hdf_core/framework/include/net** + - WLAN HDI server implementation: **//drivers/peripheral/wlan** - **//drivers/hdf_core/framework/include/wifi** - - HDF network model APIs: - **//drivers/hdf_core/framework/include/net** - - WLAN HDI server implementation: - **//drivers/peripheral/wlan** - - External APIs of the WLAN HDI: - **//out/{product_name}/gen/drivers/interface/wlan/v1_0** + diff --git a/en/device-dev/faqs/figures/en-us_image_0000001251196005.png b/en/device-dev/faqs/figures/en-us_image_0000001251196005.png deleted file mode 100644 index 527fe8b9836daf35c8300e0e84bdb2ca390f85a5..0000000000000000000000000000000000000000 Binary files a/en/device-dev/faqs/figures/en-us_image_0000001251196005.png and /dev/null differ diff --git a/en/device-dev/get-code/sourcecode-acquire.md b/en/device-dev/get-code/sourcecode-acquire.md index b244824c3be958bf35bbf78f6d2f689d2e931a6a..08809554460c986eae58f3d0a0ece2b6bb58904d 100644 --- a/en/device-dev/get-code/sourcecode-acquire.md +++ b/en/device-dev/get-code/sourcecode-acquire.md @@ -180,14 +180,14 @@ The table below provides only the sites for downloading the latest OpenHarmony L | Hi3518 solution (binary)| 3.0 | [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_aries.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_aries.tar.gz.sha256)| | Hi3516 solution-LiteOS (binary)| 3.0 | [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus.tar.gz)| | Hi3516 solution-Linux (binary)| 3.0 | [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus_linux.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.0/hispark_taurus_linux.tar.gz.sha256) | -| RELEASE-NOTES | 3.0 | [Download](https://gitee.com/openharmony/docs/blob/OpenHarmony-3.0-LTS/en/release-notes/OpenHarmony-v3.0-LTS.md)| - | +| Release Notes | 3.0 | [Download](https://gitee.com/openharmony/docs/blob/OpenHarmony-3.0-LTS/en/release-notes/OpenHarmony-v3.0-LTS.md)| - | | **Source code of the Latest Release**| **Version Information**| **Site**| **SHA-256 Verification Code**| -| Full code base (for mini, small, and standard systems)| 3.2 Beta2 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/code-v3.2-Beta2.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/code-v3.2-Beta2.tar.gz.sha256)| -| RK3568 standard system solution (binary)| 3.2 Beta2 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/standard_rk3568.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/standard_rk3568.tar.gz.sha256)| -| Hi3861 solution (binary)| 3.2 Beta2 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/hispark_pegasus.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/hispark_pegasus.tar.gz.sha256) | -| Hi3516 solution-LiteOS (binary)| 3.2 Beta2 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/hispark_taurus.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta2/hispark_taurus_LiteOS.tar.gz.sha256)| -| Hi3516 solution-Linux (binary)| 3.2 Beta2 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta2/hispark_taurus_linux.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta2/hispark_taurus_Linux.tar.gz.sha256)| -| RELEASE-NOTES | 3.2 Beta2 | [Download](../../release-notes/OpenHarmony-v3.2-beta2.md)| - | +| Full code base (for mini, small, and standard systems)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/code-v3.2-Beta3.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/code-v3.2-Beta3.tar.gz.sha256)| +| RK3568 standard system solution (binary)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/standard_rk3568.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.1.1/standard_rk3568.tar.gz.sha256)| +| Hi3861 solution (binary)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_pegasus.tar.gz)| [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_pegasus.tar.gz.sha256) | +| Hi3516 solution-LiteOS (binary)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/hispark_taurus_LiteOS.tar.gz.sha256)| +| Hi3516 solution-Linux (binary)| 3.2 Beta3 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Beta3/hispark_taurus_linux.tar.gz)| [Download](https://repo.huaweicloud.com/harmonyos/os/3.2-Beta3/hispark_taurus_Linux.tar.gz.sha256)| +| Release Notes | 3.2 Beta3 | [Download](../../release-notes/OpenHarmony-v3.2-beta3.md)| - | | **Compiler Toolchain**| **Version Information**| **Site**| **SHA-256 Verification Code**| | Compiler toolchain| - | [Download](https://repo.huaweicloud.com/openharmony/os/2.0/tool_chain/)| - | diff --git a/en/device-dev/kernel/figures/overall-file-system-architecture.png b/en/device-dev/kernel/figures/overall-file-system-architecture.png deleted file mode 100644 index 07ca835af056e96dbbf0f08f9015eb2ea1c45380..0000000000000000000000000000000000000000 Binary files a/en/device-dev/kernel/figures/overall-file-system-architecture.png and /dev/null differ diff --git a/en/device-dev/porting/porting-chip-board.md b/en/device-dev/porting/porting-chip-board.md deleted file mode 100644 index 3776faeedf617c422ac7974c728af8f62a34e470..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-chip-board.md +++ /dev/null @@ -1,17 +0,0 @@ -# Board-Level OS Porting - -- **[Porting Overview](porting-chip-board-overview.md)** - -- **[Board-Level Driver Adaptation](porting-chip-board-driver.md)** - -- **[Implementation of APIs at the HAL](porting-chip-board-hal.md)** - -- **[System Modules](porting-chip-board-component.md)** - -- **[lwIP Module Adaptation](porting-chip-board-lwip.md)** - -- **[Third-party Module Adaptation](porting-chip-board-bundle.md)** - -- **[XTS](porting-chip-board-xts.md)** - - diff --git a/en/device-dev/porting/porting-chip-kernel.md b/en/device-dev/porting/porting-chip-kernel.md deleted file mode 100644 index 7b2a628f3481ac80a59be513df869d91e9acb298..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-chip-kernel.md +++ /dev/null @@ -1,9 +0,0 @@ -# Kernel Porting - -- **[Porting Overview](porting-chip-kernel-overview.md)** - -- **[Basic Kernel Adaptation](porting-chip-kernel-adjustment.md)** - -- **[Kernel Porting Verification](porting-chip-kernel-verify.md)** - - diff --git a/en/device-dev/porting/porting-chip-prepare.md b/en/device-dev/porting/porting-chip-prepare.md deleted file mode 100644 index 44cb5673ddc7e7f7a2df08defe0c70b0d9ee2277..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-chip-prepare.md +++ /dev/null @@ -1,7 +0,0 @@ -# Porting Preparations - -- **[Before You Start](porting-chip-prepare-knows.md)** - -- **[Building Adaptation Process](porting-chip-prepare-process.md)** - - diff --git a/en/device-dev/porting/porting-minichip-cases.md b/en/device-dev/porting/porting-minichip-cases.md deleted file mode 100644 index 1b550e80b5b3864eaf47157b8306d64086411d0e..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-minichip-cases.md +++ /dev/null @@ -1,4 +0,0 @@ -# Mini System SoC Porting Cases - -- **[Mini-System Devices with Screens — Bestechnic SoC Porting Case](porting-bes2600w-on-minisystem-display-demo.md)** -- **[Combo Solution – ASR Chip Porting Case](porting-asr582x-combo-demo.md)** diff --git a/en/device-dev/porting/porting-smallchip-driver.md b/en/device-dev/porting/porting-smallchip-driver.md deleted file mode 100644 index 04eea1a6abd5ad0f7dcb8a54c96cd156fc8946a1..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-smallchip-driver.md +++ /dev/null @@ -1,9 +0,0 @@ -# Driver Porting - -- **[Porting Overview](porting-smallchip-driver-overview.md)** - -- **[Platform Driver Porting](porting-smallchip-driver-plat.md)** - -- **[Device Driver Porting](porting-smallchip-driver-oom.md)** - - diff --git a/en/device-dev/porting/porting-smallchip-kernel.md b/en/device-dev/porting/porting-smallchip-kernel.md deleted file mode 100644 index 6dc319b5e1d3e370e6aa5a328766ed8eefed79e9..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-smallchip-kernel.md +++ /dev/null @@ -1,7 +0,0 @@ -# Kernel Porting - -- **[LiteOS Cortex-A](porting-smallchip-kernel-a.md)** - -- **[Linux Kernel](porting-smallchip-kernel-linux.md)** - - diff --git a/en/device-dev/porting/porting-smallchip-prepare.md b/en/device-dev/porting/porting-smallchip-prepare.md deleted file mode 100644 index 29017d1e3985912cf68e7a30c96c6f99ad8edc88..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-smallchip-prepare.md +++ /dev/null @@ -1,7 +0,0 @@ -# Porting Preparations - -- **[Before You Start](porting-smallchip-prepare-needs.md)** - -- **[Compilation and Building](porting-smallchip-prepare-building.md)** - - diff --git a/en/device-dev/porting/porting-smallchip.md b/en/device-dev/porting/porting-smallchip.md deleted file mode 100644 index bfbe8b6af1bb60858013d9b7a4cf6600846a955e..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-smallchip.md +++ /dev/null @@ -1,9 +0,0 @@ -# Small System SoC Porting Guide - -- **[Porting Preparations](porting-smallchip-prepare.md)** - -- **[Kernel Porting](porting-smallchip-kernel.md)** - -- **[Driver Porting](porting-smallchip-driver.md)** - - diff --git a/en/device-dev/porting/porting-standardchip.md b/en/device-dev/porting/porting-standardchip.md deleted file mode 100644 index 3fe4b8e441c3784cd94134c2f28617b1cafda279..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-standardchip.md +++ /dev/null @@ -1,7 +0,0 @@ -# Standard System SoC Porting Guide - - - -- **[Standard System Porting Guide](standard-system-porting-guide.md)** - -- **[A Method for Rapidly Porting the OpenHarmony Linux Kernel](porting-linux-kernel.md)** \ No newline at end of file diff --git a/en/device-dev/porting/porting-thirdparty.md b/en/device-dev/porting/porting-thirdparty.md deleted file mode 100644 index e85e40325130aa7608c6f1db6fea86879cdf8d86..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting-thirdparty.md +++ /dev/null @@ -1,9 +0,0 @@ -# Third-Party Library Porting Guide for Mini and Small Systems - -- **[Overview](porting-thirdparty-overview.md)** - -- **[Porting a Library Built Using CMake](porting-thirdparty-cmake.md)** - -- **[Porting a Library Built Using Makefile](porting-thirdparty-makefile.md)** - - diff --git a/en/device-dev/porting/porting.md b/en/device-dev/porting/porting.md deleted file mode 100644 index 3e5a13a8b792dd17e16dd6dda9d957dc043c767f..0000000000000000000000000000000000000000 --- a/en/device-dev/porting/porting.md +++ /dev/null @@ -1,8 +0,0 @@ -# Porting - -- **[Mini System SoC Porting Guide](porting-minichip.md)** -- **[Small System SoC Porting Guide](porting-smallchip.md)** -- **[Standard System Porting Guide](standard-system-porting-guide.md)** -- **[Third-Party Library Porting Guide for Mini and Small Systems](porting-thirdparty.md)** - - diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index 610803fa36a0371bf293a995027c5be363736202..3717b07752437e19084032e1d78af9696615e3ce 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -39,7 +39,7 @@ - [Utils Overview](subsys-utils-overview.md) - [Utils Development](subsys-utils-guide.md) - [Utils FAQ](subsys-utils-faqs.md) -- [AI Framework](subsys-ai-aiframework-devguide.md) +- [AI Framework Development](subsys-ai-aiframework-devguide.md) - Data Management - RDB - [RDB Overview](subsys-data-relational-database-overview.md) @@ -71,6 +71,8 @@ - [Development on IPC Authentication](subsys-security-communicationverify.md) - [Development on Device Security Level Management](subsys-security-devicesecuritylevel.md) - [Development on HUKS](subsys-security-huks-guide.md) + - [Application Privilege Configuration Guide](subsys-app-privilege-config-guide.md) + - [Preset Application Configuration Guide](subsys-preinstall-app-config-guide.md) - Startup - [Startup](subsys-boot-overview.md) - init Module @@ -92,7 +94,6 @@ - [HiTraceChain Development](subsys-dfx-hitracechain.md) - [HiCollie Development](subsys-dfx-hicollie.md) - HiSysEvent Development - - [HiSysEvent Overview](subsys-dfx-hisysevent-overview.md) - [HiSysEvent Logging Configuration](subsys-dfx-hisysevent-logging-config.md) - [HiSysEvent Logging](subsys-dfx-hisysevent-logging.md) - [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md) diff --git a/en/device-dev/subsystems/subsys-app-privilege-config-guide.md b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..c795eb7d773cc6b37fed2dbf01582247e52e92be --- /dev/null +++ b/en/device-dev/subsystems/subsys-app-privilege-config-guide.md @@ -0,0 +1,160 @@ +# Application Privilege Configuration Guide + +Application privileges are high-level capabilities of an application, for example, restricting an application from being uninstalled or restricting application data from being deleted. + +OpenHarmony provides both general and device-specific application privileges. The latter can be configured by device vendors for applications on different devices. + +Note: To avoid user dissatisfaction or even infringement, do not abuse application privileges. + +## General Application Privileges + +### Introduction + +General application privileges are privileges available to applications on all types of devices. The general application privileges include the following: + +| Privilege| Description | +| ---------------- | ------------------------------------------------------------ | +| AllowAppDataNotCleared | Allows application data not to be deleted.| +| AllowAppMultiProcess | Allows the application to run on multiple processes.| +| AllowAppDesktopIconHide | Allows the application icon to be hidden from the home screen.| +| AllowAbilityPriorityQueried | Allows an ability to configure and query the priority. | +| AllowAbilityExcludeFromMissions | Allows an ability to be hidden in the mission stack.| +| AllowAppUsePrivilegeExtension | Allows the application to use Service Extension and Data Extension abilities.| +| AllowFormVisibleNotify | Allows a widget to be visible on the home screen.| + +### Configuration + +1. In the [HarmonyAppProvision file](https://gitee.com/openharmony/docs/blob/master/en/application-dev/quick-start/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. +2. Use the signing tool hapsigner to sign the HarmonyAppProvision file and generate a **.p7b** file. +3. Use the **.p7b** file to sign the HAP. + +Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#README.md) + +### Example + +``` +{ + "version-name": "1.0.0", + ... + "bundle-info": { + "developer-id": "OpenHarmony", + ... + }, + "issuer": "pki_internal", + "app-privilege-capabilities": ["AllowAppDataNotCleared", "AllowAppDesktopIconHide"] // The application data cannot be deleted, and icons can be hidden on the home screen. +} +``` + + + +## Device-specific Application Privileges + +### Introduction + +In addition to general application privileges, device vendors can define device-specific privileges for an application. The table below describes the device-specific privileges. + +| Privilege | Type | Default Value| Description | +| --------------------- | -------- | ------ | ------------------------------------------------- | +| removable | bool | true | Allows the application to be uninstalled. This privilege takes effect only for preset applications. | +| keepAlive | bool | false | Allows the application to keep running in the background. | +| singleton | bool | false | Allows the application to be installed for a single user (U0). | +| allowCommonEvent | string[] | - | Allows the application to be started by a static broadcast. | +| associatedWakeUp | bool | false | Allows the application in the FA model to be woken up by an associated application. | +| runningResourcesApply | bool | false | Allows the application to request running resources, such as the CPU, event notifications, and Bluetooth.| + +### Configuration + +Configure the required privileges in [configuration files](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568/preinstall-config). + +### Example + +#### Configuration in **install_list_capability.json** + +``` +{ + "install_list": [ + { + "bundleName": "com.example.kikakeyboard", + "singleton": true, // The application is installed for a single user. + "keepAlive": true, // The application is running in the background. + "runningResourcesApply": true, // The application can apply for running resources such as the CPU, event notifications, and Bluetooth. + "associatedWakeUp": true, // The application in the FA model can be woken up by an associated application. + "app_signature": ["8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC"], // The settings take effect only when the configured certificate fingerprint is the same as the HAP certificate fingerprint. + "allowCommonEvent": ["usual.event.SCREEN_ON", "usual.event.THERMAL_LEVEL_CHANGED"] + }, +} +``` + +**Obtaining the Certificate Fingerprint** + +1. Create the **profile.cer** file, and copy the certificate content under the **distribution-certificate** field of the HarmonyAppProvision file to the **profile.cer** file. + + Example: + + ``` + { + ... + "bundle-info": { + "distribution-certificate": "-----BEGIN CERTIFICATE----\nMIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMk..." / Certificate content. + ... + } + ... + } + ``` + + + +2. Apply line breaks in the **profile.cer** content and remove the newline characters. + + Example: + + ``` + -----BEGIN CERTIFICATE----- + MIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO + MRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh + bTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjEwMjAy + MTIxOTMxWhcNNDkxMjMxMTIxOTMxWjBoMQswCQYDVQQGEwJDTjEUMBIGA1UEChML + T3Blbkhhcm1vbnkxGTAXBgNVBAsTEE9wZW5IYXJtb255IFRlYW0xKDAmBgNVBAMT + H09wZW5IYXJtb255IEFwcGxpY2F0aW9uIFJlbGVhc2UwWTATBgcqhkjOPQIBBggq + hkjOPQMBBwNCAATbYOCQQpW5fdkYHN45v0X3AHax12jPBdEDosFRIZ1eXmxOYzSG + JwMfsHhUU90E8lI0TXYZnNmgM1sovubeQqATo1IwUDAfBgNVHSMEGDAWgBTbhrci + FtULoUu33SV7ufEFfaItRzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFPtxruhl + cRBQsJdwcZqLu9oNUVgaMAwGCCqGSM49BAMDBQADaAAwZQIxAJta0PQ2p4DIu/ps + LMdLCDgQ5UH1l0B4PGhBlMgdi2zf8nk9spazEQI/0XNwpft8QAIwHSuA2WelVi/o + zAlF08DnbJrOOtOnQq5wHOPlDYB4OtUzOYJk9scotrEnJxJzGsh/ + -----END CERTIFICATE----- + ``` + + + +3. Use keytool to print the certificate fingerprint. + + Example: + + ``` + keytool -printcert -file profile.cer + result: + Issued To: CN=OpenHarmony Application Release, OU=OpenHarmony Team, O=OpenHarmony, C=CN + Issued By: CN=OpenHarmony Application CA, OU=OpenHarmony Team, O=OpenHarmony, C=CN + SN: 68e0bfcc + Valid From: Tue Feb 02 20:19:31 CST 2021, Valid To: Fri Dec 31 20:19:31 CST 2049 + Fingerprints: + SHA1 fingerprint: E3:E8:7C:65:B8:1D:02:52:24:6A:06:A4:3C:4A:02:39:19:92:D1:F5 + SHA256 fingerprint: 8E:93:86:3F:C3:2E:E2:38:06:0B:F6:9A:9B:37:E2:60:8F:FF:B2:1F:93:C8:62:DD:51:1C:BA:C9:F3:00:24:B5 // After the colons are removed, the fingerprint is 8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC9F30024B5. + ... + ``` + + + +#### Configuration in **install_list.json** + +``` +{ + "install_list" : [ + { + "app_dir" : "/system/app/com.ohos.launcher", + "removable": true // The application can be uninstalled. + } + ] +} +``` diff --git a/en/device-dev/subsystems/subsys-preinstall-app-config-guide.md b/en/device-dev/subsystems/subsys-preinstall-app-config-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..e7f7ad33c0da91c8f41fd4f334c4f4baf0b8f122 --- /dev/null +++ b/en/device-dev/subsystems/subsys-preinstall-app-config-guide.md @@ -0,0 +1,56 @@ +# Preset Application Configuration Guide + +OpenHarmony supports differentiated configuration of preset applications on different devices. + +In addition, OpenHarmony provides **GetCfgDirList** for your application to obtain the preset directories, such as **system**, **chipset**, **sys_prod**, and **chip_prod**, in ascending order of priority. For example, the priority of **chip_prod** is higher than that of **system**. + +## Configuring the Preset Applications to Be Installed + +### Procedure + +1. Add the application name in the preset directory as the application directory. +2. Preset the application in the application directory, for example, **/system/app/Hiworld/entry.hap**. +3. Add the application directory to [install_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list.json) and configure **removable** as required. + +### Example + +``` +{ + "install_list" : [ + { + "app_dir" : "/system/app/Hiworld", + "removable": false // The application cannot be uninstalled. + } + ] +} +``` + +## Configuring the Preset Applications Not to Be Installed + +The configuration priority of [**uninstall_list.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/uninstall_list.json) is higher than that of **install_list.json**. The applications added to **uninstall_list.json** will not be installed. + +### Example 1: + +``` +/system/etc/app/uninstall_list.json +{ + "uninstall_list": ["/system/app/Hiworld"], // Hiworld will not be installed. + "recover_list" : [] +} +``` + +### Example 2: + +``` +/system/etc/app/uninstall_list.json +{ + "uninstall_list" : ["/system/app/Hiworld"], + "recover_list" : [] +} + +/chipset/etc/app/uninstall_list.json +{ + "uninstall_list" : [], + "recover_list": ["/system/app/Hiworld"] // Hiworld will be installed. +} +``` diff --git a/en/device-dev/website.md b/en/device-dev/website.md index 6cfcbb65bcd6cf29218f11a58f8f67667d061f9c..9463578e645cb0c4aa816dac2bd47ef8d3faf5c2 100644 --- a/en/device-dev/website.md +++ b/en/device-dev/website.md @@ -197,10 +197,28 @@ - [Overall Description of Compilation Form Factors](quick-start/quickstart-build.md) - [Obtaining Source Code](get-code/sourcecode-acquire.md) +- Privacy and Security - [Privacy Protection](security/security-privacy-protection.md) - [Security Guidelines](security/security-guidelines-overall.md) - Porting + - Mini System SoC Porting Guide + - Porting Preparations + - [Before You Start](porting/porting-chip-prepare-knows.md) + - [Building Adaptation Process](porting/porting-chip-prepare-process.md) + - Kernel Porting + - [Overview](porting/porting-chip-kernel-overview.md) + - [Basic Kernel Adaptation](porting/porting-chip-kernel-adjustment.md) + - [Kernel Porting Verification](porting/porting-chip-kernel-verify.md) + - Board-Level OS Porting + - [Overview](porting/porting-chip-board-overview.md) + - [Board-Level Driver Adaptation](porting/porting-chip-board-driver.md) + - [Implementation of APIs at the HAL](porting/porting-chip-board-hal.md) + - [System Modules](porting/porting-chip-board-component.md) + - [lwIP Module Adaptation](porting/porting-chip-board-lwip.md) + - [Third-party Module Adaptation](porting/porting-chip-board-bundle.md) + - [XTS](porting/porting-chip-board-xts.md) + - [FAQs](porting/porting-chip-faqs.md) - Small System SoC Porting Guide - Porting Preparations @@ -469,18 +487,18 @@ - [Build System Coding Specifications and Best Practices](subsystems/subsys-build-gn-coding-style-and-best-practice.md) - [Building the Kconfig Visual Configuration](subsystems/subsys-build-gn-kconfig-visual-config-guide.md) - References - - [Subsystem Configuration Rules](subsystems/subsys-build-subsystem.md#configuration-rules) - - [Product Configuration Rules](subsystems/subsys-build-product.md#configuration-rules) - - [Subsystem Configuration Rules](subsystems/subsys-build-subsystem.md#configuration-rules) - - [Component Configuration Rules](subsystems/subsys-build-component.md#configuration-rules) - - [Module Configuration Rules](subsystems/subsys-build-module.md#configuration-rules) - - [Chipset Solution Configuration Rules](subsystems/subsys-build-chip_solution.md#configuration-rules) - - [Feature Configuration Rules](subsystems/subsys-build-feature.md#configuration-rules) - - [System Capabilities Configuration Rules](subsystems/subsys-build-syscap.md#configuring-system-capabilities-for-a-component) - - [deps and external_deps](subsystems/subsys-build-reference.md#deps-and-external_deps) - - [Information Collected by the Open Source Software Notice](subsystems/subsys-build-reference.md#information-collected-by-the-open-source-software-notice) - - [Parameters for Accelerating Local Build](subsystems/subsys-build-reference.md#parameters-for-accelerating-local-build) - - [Viewing Ninja Build Information](subsystems/subsys-build-reference.md#viewing-ninja-build-information) + - [Subsystem Configuration Rules](subsystems/subsys-build-subsystem.md + - [Product Configuration Rules](subsystems/subsys-build-product.md) + - [Subsystem Configuration Rules](subsystems/subsys-build-subsystem.md) + - [Component Configuration Rules](subsystems/subsys-build-component.md) + - [Module Configuration Rules](subsystems/subsys-build-module.md) + - [Chipset Solution Configuration Rules](subsystems/subsys-build-chip_solution.md) + - [Feature Configuration Rules](subsystems/subsys-build-feature.md) + - [System Capabilities Configuration Rules](subsystems/subsys-build-syscap.md) + - [deps and external_deps](subsystems/subsys-build-reference.md) + - [Information Collected by the Open Source Software Notice](subsystems/subsys-build-reference.md) + - [Parameters for Accelerating Local Build](subsystems/subsys-build-reference.md) + - [Viewing Ninja Build Information](subsystems/subsys-build-reference.md) - [HAP Build Guide](subsystems/subsys-build-gn-hap-compilation-guide.md) - [FAQs](subsystems/subsys-build-FAQ.md) - [Distributed Remote Startup](subsystems/subsys-remote-start.md) diff --git a/en/readme.md b/en/readme.md index e220bd152b32ff7cdf34c000d283acfab619fcba..fddc5fa5dd6cdd9498a8c6bfcf9d701a520a6d73 100644 --- a/en/readme.md +++ b/en/readme.md @@ -8,6 +8,6 @@ This repository stores a complete range of OpenHarmony documentation. The conten - [Release Notes](release-notes/Readme.md) - [Subsystems](./readme) - OpenHarmony Contribution - - [Contribution Guide](contribute/contribution-guide.md) + - [Contribution Guide](contribute/Readme-EN.md) - [OpenHarmony Part and API Design Reference](./design) diff --git a/en/readme/account.md b/en/readme/account.md index 604106428bc13c2fc74f6383ec47f659bc34b550..bda9addb1394b0cbfec6be7dc0ac4853cc967c7b 100755 --- a/en/readme/account.md +++ b/en/readme/account.md @@ -1,39 +1,86 @@ -# Account +# Account -## Introduction +## Introduction -In a standard system, the Account subsystem supports login status management of distributed cloud accounts, interconnection with vendors' cloud account apps on the device side, and query and update of the cloud account login status. +In the standard system, the Account subsystem provides basic capabilities such as OS account lifecycle management, distributed account login status management, and app account information management. -## Architecture +## Architecture -**Figure 1** Account subsystem architecture +**Figure 1** Account subsystem architecture -![](figures/en-us_image_0000001079026550.png) +![](figures/en_image_account_struct.png) -## Directory Structure +## Directory Structure ``` -/base/account -└── os_account # OS account module - ├── common # Common basic code - ├── interfaces # APIs exposed externally - ├── kits # Development framework - ├── sa_profile # SA profile - ├── services # Service code - └── test # Test code - └── resource # Test resources +/base/account/os_account +├── dfx +│ ├── hidumper_adapter # Code of the adapter for exporting system service information +│ ├── hisysevent_adapter # Code of the system event logging adapter +├── figures # Figures +├── frameworks # Code of the account subsystem +│ ├── account_iam # Internal API code for account identity authentication and access management +│ │ └── src # Code for implementing internal APIs for account identity authentication and access management +│ ├── appaccount # Internal API code of the app account module +│ │ └── native # Code for implementing the internal APIs of the app account module +│ ├── common # Code of the common module +│ │ ├── account_error # Error codes +│ │ ├── database # Database code +│ │ ├── file_operator # File operator code +│ │ ├── log # Code for printing logs +│ │ ├── perf_stat # Code for performance statistics +│ │ └── test # Test code for the common module +│ ├── ohosaccount # Internal API code of the distributed account module +│ │ ├── native # Code for implementing the internal APIs of the distributed account module +│ │ └── test # Test code for the distributed account internal APIs +│ └── osaccount # Internal API code of the OS account module +│ ├── core # OS account IPC +│ └── native # Code for implementing the internal APIs of the OS account module +├── interfaces # Account subsystem APIs exposed externally +│ ├── innerkits # Internal API header files +│ │ ├── account_iam # Account identity authentication and access management +│ │ ├── appaccount # Header files of the app account internal APIs +│ │ ├── ohosaccount # Header files of the distributed account internal APIs +│ │ └── osaccount # Header files of the OS account internal APIs +│ └── kits # Encapsulation of external APIs +│ └── napi # External API encapsulation code of the account subsystem +├── sa_profile # SA profile directory of the account subsystem +├── services # accountmgr service code +│ └── accountmgr # Account subsystem service code +│ ├── include # Service code header files +│ ├── src # Source code of the account subsystem service code +│ └── test # Test of the account subsystem service code +├── test # Test code +│ ├── fuzztest # Fuzzy test code +│ ├── resource # Test resource files +│ └── systemtest # System test code +└── tools # Tool code + ├── acm # acm tool code + │ ├── include # acm header files + │ └── src # acm source file + └── test # acm test code ``` -## Usage Guidelines +## Description -Using the available classes for managing distributed accounts, you can query and update the account login status, including login, logout, unregistration, and token expiration. +### Modules -To query and update the login status of a distributed account, you must obtain the required system permission. These APIs are supported only by system apps. +| Module | Description | +| ---------- | ------------------------------------------------------------ | +| OS account | Provides APIs for adding, deleting, querying, modifying, and starting OS accounts and subscribing to OS account information. | +| Distributed account| Provides APIs for managing distributed account login status, supports interactions with cloud account applications on devices, and provides capabilities for querying and updating cloud account login status.| +| App account | Provides APIs for adding, deleting, querying, modifying, and authenticating app accounts. | -## Repositories Involved -**Account subsystem** +### How to Use -[account_os_account](https://gitee.com/openharmony/account_os_account) +- [OS Account Management](../application-dev/reference/apis/js-apis-osAccount.md) +- [Distributed Account Management](../application-dev/reference/apis/js-apis-distributed-account.md) +- [App Account Management](../application-dev/reference/apis/js-apis-appAccount.md) +## Repositories Involved + +**Account Subsystem** + +[account_os_account](https://gitee.com/openharmony/account_os_account) \ No newline at end of file diff --git a/en/readme/figures/en_image_account_struct.png b/en/readme/figures/en_image_account_struct.png new file mode 100644 index 0000000000000000000000000000000000000000..db5671e5fde629b5cdf57e2a8974b87f44455707 Binary files /dev/null and b/en/readme/figures/en_image_account_struct.png differ diff --git a/en/readme/location.md b/en/readme/location.md index e1ffba36672d0470e45a38331c33b11991811d0d..035cec4b31d6ddb0b432b7de28bd5a8367c0c002 100644 --- a/en/readme/location.md +++ b/en/readme/location.md @@ -28,9 +28,8 @@ Location awareness helps determine where a mobile device locates. The system ide WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points (APs) and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network. -**Figure 1** ** Location subsystem architecture** +**Figure 1** Location subsystem architecture** -![](figures/location_En-1.png) ![](figures/location_En-1.png) ## Directory Structure @@ -116,27 +115,7 @@ The following table describes APIs available for obtaining device location infor If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information even when your application moves to the background. - To allow your application to access device location information, you can declare the required permissions in the **config.json** file of your application. The sample code is as follows: - - - ``` - { - "module": { - "reqPermissions": [{ - "name": "ohos.permission.LOCATION", - "reason": "$string:reason_description", - "usedScene": { - "ability": ["com.myapplication.LocationAbility"], - "when": "inuse" - }, { - ... - } - ] - } - } - ``` - - For details about the configuration fields, see [Application Package Structure Configuration File](../application-dev/quick-start/stage-structure.md). + You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../application-dev/security/accesstoken-guidelines.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. diff --git a/en/release-notes/api-change/v3.1-Release/Readme-EN.md b/en/release-notes/api-change/v3.1-Release/Readme-EN.md index d84adb9e93c862893399d0c1276a2cde150a44fb..e7465982e34f079913c30cf77dd1865e5f85a3e2 100644 --- a/en/release-notes/api-change/v3.1-Release/Readme-EN.md +++ b/en/release-notes/api-change/v3.1-Release/Readme-EN.md @@ -4,3 +4,4 @@ This directory records the API changes in OpenHarmony 3.1 Release over OpenHarmo - [JS API Differences](js-apidiff-v3.1-release.md) - [Native API Differences](native-apidiff-v3.1-release.md) +- [Updates (OpenHarmony 3.1 Beta -> OpenHarmony 3.1 Release)](changelog-v3.1-release.md) diff --git a/en/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md b/en/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md new file mode 100644 index 0000000000000000000000000000000000000000..597bda22e9a8564f20be1ca5dfa4d1b8d25f023c --- /dev/null +++ b/en/release-notes/api-change/v3.1-Release/changelog-v3.1-release.md @@ -0,0 +1,56 @@ +# Updates (OpenHarmony 3.1 Beta -> OpenHarmony 3.1 Release) + +### Added Validity Verification for Color Values in Color.json + +Validity verification is added for color values in the **color.json** file. The verification rules are as follows: + +- The hexadecimal color code is used in any of the following formats: + - #rgb: red(0-f) green(0-f) blue(0-f) + - #argb: transparency(0-f) red(0-f) green(0-f) blue(0-f) + - #rrggbb: red(00-ff) green(00-ff) blue(00-ff) + - #aarrggbb: transparency(00-ff) red(00-ff) green(00-ff) blue(00-ff) +- The dollar sign ($) is used to reference resources defined in the application. The format is as follows: + - $color:xxx + +**Change Impacts** + +If the verification rules are not met, an error is reported during compilation. + +**Key API/Component Changes** + +None + +### Restrictions on Declaring Multiple Data Types of State Variables + +If a **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variable supports multiple data types, they must be all simple data types or references at one time. + +Example: + +```ts +@Entry +@Component +struct Index { + // Incorrect: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**Change Impacts** + +When the defined state variable type contains both the simple data types and references, an error is reported during compilation. + +**Key API/Component Changes** + +If the defined state variable type contains both the simple data types and references, change the type to one of them, as shown in the preceding sample code. diff --git a/en/release-notes/api-change/v3.2-beta2/Readme-EN.md b/en/release-notes/api-change/v3.2-beta2/Readme-EN.md index 21548e70cc7276031e010cd063888682d7d79cb9..9c0ced90f4aaeb828bdc7aeffe8d52204cfd1f67 100644 --- a/en/release-notes/api-change/v3.2-beta2/Readme-EN.md +++ b/en/release-notes/api-change/v3.2-beta2/Readme-EN.md @@ -31,5 +31,6 @@ This directory records the API changes in OpenHarmony 3.2 Beta2 over OpenHarmony - [Web subsystem](js-apidiff-web.md) - [Window manager subsystem](js-apidiff-window.md) - ChangeLog - - [Updates Between OpenHarmony 3.2 Beta2 and OpenHarmony 3.2 Beta1](changelog-v3.2-beta2.md) + - [Updates (OpenHarmony 3.2 Beta1 -> OpenHarmony 3.2 Beta2)](changelog-v3.2-beta2.md) - [Adaptation Guide for the Application Sandbox](application-sandbox-adaptation-guide.md) + diff --git a/en/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md b/en/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md index 418b75ae1af0a1dba20d7dabe86a06243e956e46..087c63757f0fc93730cb637b15df1d5e7c1e8d3e 100644 --- a/en/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md +++ b/en/release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md @@ -1,4 +1,4 @@ -# Updates Between OpenHarmony 3.2 Beta2 and OpenHarmony 3.2 Beta1 +# Updates (OpenHarmony 3.2 Beta1 -> OpenHarmony 3.2 Beta2) ## Introduced Application Sandbox diff --git a/en/release-notes/api-change/v3.2-beta3/Readme-EN.md b/en/release-notes/api-change/v3.2-beta3/Readme-EN.md index af4d7cc1dd326b2a086cacd23eebeb5f49bb1b78..816c48c5c111e2d70682fd7125cae3563cc33a0a 100644 --- a/en/release-notes/api-change/v3.2-beta3/Readme-EN.md +++ b/en/release-notes/api-change/v3.2-beta3/Readme-EN.md @@ -30,3 +30,4 @@ This directory records the API changes in OpenHarmony 3.2 Beta3 over OpenHarmony - [Update subsystem](js-apidiff-update.md) - [Web subsystem](js-apidiff-web.md) - [Window manager subsystem](js-apidiff-window.md) +- [Updates (OpenHarmony 3.2 Beta2 -> OpenHarmony 3.2 Beta3)](changelog-v3.2-beta3.md) diff --git a/en/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md b/en/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md new file mode 100644 index 0000000000000000000000000000000000000000..0070fc5fd80a26c7d2611af75272011357b5727a --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md @@ -0,0 +1,234 @@ +# Updates (OpenHarmony 3.2 Beta2 -> OpenHarmony 3.2 Beta3) + +## Bundle Management Framework + +The privilege control capability is added for preset applications. The capability can be divided into two parts: permission control for preset applications and configuration of preset applications. +Application privileges are high-level capabilities of an application, for example, restricting an application from being uninstalled or restricting application data from being deleted. +OpenHarmony provides both general and device-specific application privileges. The latter can be configured by device vendors for applications on different devices. OpenHarmony supports differentiated configuration of preset applications on different devices. In addition, OpenHarmony provides **GetCfgDirList** for your application to obtain the preset directories, such as **system**, **chipset**, **sys_prod**, and **chip_prod**, in ascending order of priority. For example, the priority of **chip_prod** is higher than that of **system**. + +### Changed Installation Mode for Preset Applications + +In earlier versions, preset applications are installed by automatically scanning and installing HAP files in the **/system/app** directory. From this version, preset applications are configured based on the trustlist. Specifically, only the HAP file configured with **app-dir** in the **install_list.json** file can be automatically installed as a preset application. + +**Change Impacts** + +JS and native APIs are not involved, and application development is not affected. + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +Configure related fields in the [/system/etc/app/install_list.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list.json) file. The **app_dir** field specifies the directory where the HAP file is located, and **removable** specifies whether the HAP file can be uninstalled after being installed. + +Example: + +```json +{ + "install_list" : [ + { + "app_dir" : "/system/app/com.ohos.systemui", + "removable" : false + }, + { + "app_dir" : "/system/app/demo.hap", + "removable" : true + } + ] +} +``` + +### Changes in General Application Privilege Control + +For a specific application, the general application privileges remain unchanged on all types of devices. The general application privileges are as follows: +| Permission| Description | +| ---------------- | ------------------------------------------------------------ | +| AllowAppDataNotCleared | Allows application data to be deleted.| +| AllowAppMultiProcess | Allows the application to run on multiple processes.| +| AllowAppDesktopIconHide | Allows the application icon to be hidden from the home screen.| +| AllowAbilityPriorityQueried | Allows an ability to configure and query the priority. | +| AllowAbilityExcludeFromMissions | Allows an ability to be hidden in the mission stack.| +| AllowAppUsePrivilegeExtension | Allows the application to use Service Extension and Data Extension abilities.| +| AllowFormVisibleNotify | Allows a widget to be visible on the home screen.| + +In earlier versions, these privileges are configured in the **config.json** or **module.json** file and distinguished based on the application type (preset or system application). From this version, the privileges are configured based on the signing certificate and preset trustlist. + +**Change Impacts** + +JS and native APIs are not involved. If your application needs to use any of these privileges, apply for it. For details about how to apply for and configure the privileges, see [Application Privilege Configuration](../device-dev/subsystems/subsys-app-privilege-config-guide.md). + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +See [Application Privilege Configuration](../device-dev/subsystems/subsys-app-privilege-config-guide.md). + +```json +{ + "version-name": "1.0.0", + ... + "bundle-info": { + "developer-id": "OpenHarmony", + ... + }, + "issuer": "pki_internal", + "app-privilege-capabilities": ["AllowAppDataNotCleared", "AllowAppDesktopIconHide"] // The application data cannot be deleted, and the icon can be hidden on the home screen. +} +``` + +### Changes in Device-specific Application Privilege Control +In addition to general application privileges, device vendors can define device-specific privileges for an application, as described in the table below. + +| Permission | Type | Default Value| Description | +| --------------------- | -------- | ------ | ------------------------------------------------- | +| removable | bool | true | Allows the application to be uninstalled. This permission takes effect only for preset applications. | +| keepAlive | bool | false | Allows the application to remain resident in the background. | +| singleton | bool | false | Allows the application to be installed for a single user (User 0). | +| allowCommonEvent | string[] | - | Allows the application to be started by a static broadcast. | +| associatedWakeUp | bool | false | Allows the application in the FA model to be woken up by an associated application. | +| runningResourcesApply | bool | false | Allows the application to request running resources, such as CPU, event notifications, and Bluetooth.| + +In earlier versions, these privileges are configured in the **config.json** or **module.json** file and distinguished based on the application type (preset or system application). From this version, the privileges can be configured based on the preset trustlist. For details, see [install_list_capability.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_capability.json). + +**Change Impacts** + +JS and native APIs are not involved. If your application needs to use any of these privileges, apply for it. For details, see [Configuration Mode](../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-mode). + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +See [Configuration Mode](../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-mode). + +```json +{ + "install_list": [ + { + "bundleName": "com.example.kikakeyboard", + "singleton": true, // The application is installed for a single user. + "keepAlive": true, // The application remains resident in the background. + "runningResourcesApply": true, // The application can apply for running resources such as CPU, event notifications, and Bluetooth. + "associatedWakeUp": true, // The application in the FA model can be woken up by an associated application. + "app_signature": ["8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC"], // The setting takes effect only when the configured certificate fingerprint is the same as the HAP certificate fingerprint. + "allowCommonEvent": ["usual.event.SCREEN_ON", "usual.event.THERMAL_LEVEL_CHANGED"] + } +} +``` + +### Fingerprint Verification for Pre-authorization Trustlist + +The pre-authorization file [install_list_permissions.json](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) is moved from **system/etc/permission** to **system/etc/app/** on the development board. The **app_signature** field is added to specify the fingerprint of the HAP file. Multiple fingerprints can be configured. Authorization can be performed only when the fingerprint is matched. + +**Change Impacts** + +JS and native APIs are not involved. If your application uses pre-authorization, add the fingerprint to the pre-authorization file. + +**Key API/Component Changes** + +N/A + +**Adaptation Guide** + +Refer to the following code: + +```json +{ +[ + { + "bundleName" : "com.ohos.screenshot", + "app_signature" : ["8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC9F30024B5"], + "permissions" : [ + { + "name" : "ohos.permission.MEDIA_LOCATION", + "userCancellable" : true + }, + { + "name" : "ohos.permission.READ_MEDIA", + "userCancellable" : true + }, + { + "name" : "ohos.permission.WRITE_MEDIA", + "userCancellable" : true + } + ] + } +} +``` + +## ArkUI Development Framework + +### Rectified Variable Sharing Issue of the Common Module in Release HAP Mode During Building in the FA Model + +Assume that two pages depend on the same object (foodData) of a file. If page A modifies the object, page B obtains the new value when reading the object. This implements object sharing for the common module. + +**Change Impacts** + +Application compilation is not affected, and no interface adaptation is required. + +**Key API/Component Changes** + +N/A + +### Restrictions on Declaring Multiple Data Types of State Variables + +If a **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variable supports multiple data types, they must be all simple data types or references at one time. + +Example: + +```ts +@Entry +@Component +struct Index { + // Incorrect: @State message: string | Resource = 'Hello World' + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(`${ this.message }`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + } + .width('100%') + } + .height('100%') + } +} +``` + +**Change Impacts** + +When the defined state variable type contains both the simple data types and references, an error is reported during compilation. + +**Key API/Component Changes** + +If the defined state variable type contains both the simple data types and references, change the type to one of them, as shown in the preceding sample code. + +## Globalization Subsystem + +### Added Validity Verification for Color Values in Color.json + +Validity verification is added for color values in the **color.json** file. The verification rules are as follows: + +- The hexadecimal color code is used in any of the following formats: + - #rgb: red(0-f) green(0-f) blue(0-f) + - #argb: transparency(0-f) red(0-f) green(0-f) blue(0-f) + - #rrggbb: red(00-ff) green(00-ff) blue(00-ff) + - #aarrggbb: transparency(00-ff) red(00-ff) green(00-ff) blue(00-ff) +- The dollar sign ($) is used to reference resources defined in the application. The format is as follows: + - $color:xxx + +**Change Impacts** + +If the verification rules are not met, an error is reported during compilation. + +**Key API/Component Changes** + +N/A + + \ No newline at end of file diff --git a/en/website.md b/en/website.md index dcd1bc06fea931fb3fe160b92f1333ba2f416981..4165d8468ba31e9d420f14dfec9fb3fefa5199d6 100644 --- a/en/website.md +++ b/en/website.md @@ -58,6 +58,7 @@ - [Update subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-update.md) - [Web subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-web.md) - [Window manager subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-window.md) + - [Updates (OpenHarmony 3.2 Beta2 -> OpenHarmony 3.2 Beta3)](release-notes/api-change/v3.2-beta3/changelog-v3.2-beta3.md) - OpenHarmony 3.2 Beta2 - JS API Differences - [Ability framework](release-notes/api-change/v3.2-beta2/js-apidiff-ability.md) @@ -88,7 +89,7 @@ - [Web subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-web.md) - [Window manager subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-window.md) - ChangeLog - - [Updates Between OpenHarmony 3.2 Beta2 and OpenHarmony 3.2 Beta1](release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md) + - [Updates (OpenHarmony 3.2 Beta1 -> OpenHarmony 3.2 Beta2)](release-notes/api-change/v3.2-beta2/changelog-v3.2-beta2.md) - [Adaptation Guide for the Application Sandbox](release-notes/api-change/v3.2-beta2/application-sandbox-adaptation-guide.md) - OpenHarmony 3.2 Beta1 - JS API Differences @@ -143,10 +144,11 @@ - [User IAM subsystem](release-notes/api-change/v3.1-Release/js-apidiff-user-authentication.md) - [Window manager subsystem](release-notes/api-change/v3.1-Release/js-apidiff-window.md) - [Native API Differences](release-notes/api-change/v3.1-Release/native-apidiff-v3.1-release.md) + - [Updates (OpenHarmony 3.1 Beta -> OpenHarmony 3.1 Release)](release-notes/api-change/v3.1-Release/changelog-v3.1-release.md) - OpenHarmony 3.1 Beta - [JS API Differences](release-notes/api-change/v3.1-beta/js-apidiff-v3.1-beta.md) - [Native API Differences](release-notes/api-change/v3.1-beta/native-apidiff-v3.1-beta.md) - - [Updates Between OpenHarmony 3.1 Beta and OpenHarmony 3.0](release-notes/api-change/v3.1-beta/changelog-v3.1-beta.md) + - [Updates (OpenHarmony 3.0 -> OpenHarmony 3.1 Beta)](release-notes/api-change/v3.1-beta/changelog-v3.1-beta.md) - OpenHarmony 3.0 LTS - [JS API Differences](release-notes/api-change/v3.0-LTS/js-apidiff-v3.0-lts.md) - OpenHarmony v2.2 Beta2 diff --git a/zh-cn/OpenHarmony-Overview_zh.md b/zh-cn/OpenHarmony-Overview_zh.md index 14634f537ded05f47c83f59e063732217cf860d2..2ba0d3ac1c331a3973cd907f39d04a0e6c5c6b81 100644 --- a/zh-cn/OpenHarmony-Overview_zh.md +++ b/zh-cn/OpenHarmony-Overview_zh.md @@ -146,7 +146,7 @@ OpenHarmony支持如下几种系统类型: ## 支持的开发板 -当前OpenHarmony社区支持17款开发板,下表介绍3款(此处选择三种系统类型首款进入OpenHarmony主干的开发板),更多开发板信息,请参考[社区支持的开发板清单](device-dev/dev-board-on-the-master.md),社区每日构建版本获取地址请参考http://ci.openharmony.cn/dailys/dailybuilds +当前OpenHarmony社区支持22款开发板,下表介绍3款(此处选择三种系统类型首款进入OpenHarmony主干的开发板),更多开发板信息,请参考[社区支持的开发板清单](device-dev/dev-board-on-the-master.md),社区每日构建版本获取地址请参考http://ci.openharmony.cn/dailys/dailybuilds |系统类型 | 开发板型号| 芯片型号 | 主要能力及适配案例 | 典型应用场景 | 开发板代码仓| |-------- | --------| --------| --------| -------- | -------- | diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index b46bb3d89e7ffb99bde5bda90c7e2664e7547cdf..90378b11ecb5a1b4f9c490cef182bd55c9ce0be7 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -15,7 +15,6 @@ - [应用包结构说明(FA模型)](quick-start/package-structure.md) - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) - [资源分类与访问](quick-start/resource-categories-and-access.md) - 学习ArkTS语言 - [初识ArkTS语言](quick-start/arkts-get-started.md) diff --git a/zh-cn/application-dev/ability/ability-brief.md b/zh-cn/application-dev/ability/ability-brief.md index 149bd6429f51455539145b3e1fef2e59b38e8882..f7a4e18664f1c9bc0b0dd5d7478b2a3f40bea66c 100644 --- a/zh-cn/application-dev/ability/ability-brief.md +++ b/zh-cn/application-dev/ability/ability-brief.md @@ -1,22 +1,26 @@ # Ability框架概述 -Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件。一个应用可以包含一个或多个Ability。 +Ability是OpenHarmony系统对应用的基本抽象。 + +每个Ability是完成独立业务的应用组件,是系统调度应用的最小单元。一个应用可以包含一个或多个Ability。 Ability框架模型具有两种形态: -- 第一种形态为FA模型。API 8及其更早版本的应用程序只能使用FA模型进行开发。FA模型将Ability分为FA(Feature Ability)和PA(Particle Ability)两种类型,其中FA支持Page Ability,PA支持Service Ability、Data Ability、以及FormAbility。 -- 第二种形态为Stage模型。从API 9开始,Ability框架引入了Stage模型作为第二种应用框架形态,Stage模型将Ability分为PageAbility和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等一系列ExtensionAbility,以便满足更多的使用场景。 +- 第一种形态称为FA模型。API 8及其更早版本的应用只能使用FA模型。FA模型将Ability分为Page Ability、Service Ability以及Data Ability几种类型。 +- 第二种形态称为Stage模型,这是自API 9新增的模型。Stage模型将Ability分为UIAbility和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等一系列ExtensionAbility,以便满足更多的使用场景。 + +自API 9开始,Stage模型是主推的开发模型。 Stage模型的设计,主要是为了开发者更加方便地开发出分布式环境下的复杂应用。下表给出了两种模型在设计上的差异: | 对比 | FA模型 | Stage模型 | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | -| 开发方式 | 提供类Web的API,UI开发与Stage模型一致。 | 提供面向对象的开发方式,UI开发与FA模型一致。 | -| 引擎实例 | 每个进程内的每个Ability实例独享一个JS VM引擎实例。 | 每个进程内的多个Ability实例共享一个JS VM引擎实例。 | +| 应用组件开发方式 | 类Web的开发方式。 | 面向对象的开发方式。 | +| 引擎实例 | 每个Ability实例独占一个虚拟机实例。 | 多个Ability实例可以共享同一个虚拟机实例。 | | 进程内对象共享 | 不支持。 | 支持。 | -| 包描述文件 | 使用config.json描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用module.json5描述HAP包和组件信息,可以指定入口文件名。 | -| 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享)以及FormAbility(卡片)。 | 提供Ability(页面展示)、Extension(基于场景的服务扩展)。 | - +| 包描述文件 | 使用`config.json`描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用`module.json5`描述HAP包和组件信息,可以指定入口文件名。 | +| 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享)以及FormAbility(卡片)。 | 提供UIAbility(页面展示)、Extension(基于场景的服务扩展)。 | + 除了上述设计上的差异外,对于开发者而言,两种模型的主要区别在于: * Ability类型存在差异; @@ -29,7 +33,15 @@ Stage模型的设计,主要是为了开发者更加方便地开发出分布式 两种模型的基本介绍,详见[FA模型综述](fa-brief.md)及[Stage模型综述](stage-brief.md)。 -## 相关实例 -针对Ability开发,有以下相关实例可供参考: +## 相关实例 + +### FA 模型 + +- [Page内和Page间导航跳转(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) + +### Stage 模型 -- [Page内和Page间导航跳转(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility) \ No newline at end of file +- [Stage模型介绍(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageModel) +- [窗口扩展(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/WindowExtAbility) +- [系统任务管理(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/MissionManager) +- [仿桌面应用(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/Launcher) diff --git a/zh-cn/application-dev/ability/fa-brief.md b/zh-cn/application-dev/ability/fa-brief.md index 3d8989bc1f7c56a6e9b614b3a6cfb7647d21f865..a752d73dd3918bba9fb1a09489f06b18d1952661 100644 --- a/zh-cn/application-dev/ability/fa-brief.md +++ b/zh-cn/application-dev/ability/fa-brief.md @@ -1,29 +1,36 @@ # FA模型综述 ## 整体架构 -OpenHarmony用户程序的开发本质上就是开发Ability。OpenHarmony系统是通过对Ability调度,结合系统提供的一致性调度契约对Ability进行生命周期管理,从而实现对用户程序的调度。 -Ability框架在API 8及更早版本使用FA模型。FA模型中Ability分为PageAbility、ServiceAbility、DataAbility、FormAbility几种类型。其中: -- PageAbility是具备ArkUI实现的Ability,是用户具体可见并可以交互的Ability实例。 -- ServiceAbility也是Ability一种,但是没有UI,提供其他Ability调用自定义的服务,在后台运行。 -- DataAbility也是没有UI的Ability,提供其他Ability进行数据的增删查服务,在后台运行。 -- FormAbility是卡片Ability,是一种界面展示形式。 +OpenHarmony应用的开发,是以Ability为入口展开的。 + +对于Ability的开发,通常是以生命周期的回调处理为中心。 + +Ability框架在API 8及更早版本仅支持FA模型。FA模型中Ability分为PageAbility、ServiceAbility、DataAbility、FormAbility几种类型。其中: +- PageAbility使用ArkUI实现用户界面,是用户可见并可以交互的Ability实例。 +- ServiceAbility也是Ability一种,但是没有用户界面。它提供了其他Ability调用的自定义服务,ServiceAbility在后台运行。 +- DataAbility也是没有界面的Ability,提供其他Ability进行数据的增删查服务,它同样在后台运行。 +- FormAbility是实现卡片的Ability,卡片是OpenHarmomny系统上的一种界面展示形式。 + +> 注:自API 9开始,Stage模型是主推的开发模型。 ## 生命周期 -在所有Ability中,PageAbility因为具有界面,也是应用的交互入口,因此生命周期更加复杂。 +在所有Ability中,PageAbility因为具有界面,也是应用的交互入口,因此其生命周期更加复杂。 **PageAbility生命周期回调如下图所示:** ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) -其他类型Ability的生命周期可参考PageAbility生命周期去除前后台切换以及`onShow`的部分进行理解。 -开发者可以在 `app.js/app.ets` 中重写生命周期函数,在对应的生命周期函数内处理应用相应逻辑。 - -目前`app.js`环境中仅支持onCreate和onDestroy回调,`app.ets`环境支持全量生命周期回调。 +其他类型Ability的生命周期可参考PageAbility生命周期去除前后台切换以及`onShow`及`onHide`的部分来理解。 +开发者可以在 `app.js/app.ets` 中重写生命周期函数,在对应的生命周期回调内处理应用的相应逻辑。 +目前`app.js`仅支持`onCreate`和`onDestroy`回调,但`app.ets`支持全量生命周期回调。 ## 进程线程模型 -应用独享独立进程,Ability独享独立线程,应用进程在Ability第一次启动时创建,并为启动的Ability创建线程,应用启动后再启动应用内其他Ability,会为每一个Ability创建相应的线程。每个Ability绑定一个独立的JSRuntime实例,因此Ability之间是隔离的。 + +每个应用运行在不同的进程中,在FA模型中,每个Ability运行在独立的虚拟机中。 + +应用进程在Ability启动时创建,此时会为Ability创建相应的线程。当一个应用有多个Ability时,每一个Ability在独立线程中运行。在FA模型中,每个Ability绑定一个独立的虚拟机实例,因此Ability之间是隔离的。 ![fa-threading-model](figures/fa-threading-model.png) diff --git a/zh-cn/application-dev/ability/stage-ability.md b/zh-cn/application-dev/ability/stage-ability.md index 31e252617d90c4a0576761a7224f0ff8e968d007..ff7bdf0619c22796bf19e8f4f2f3eeefb0808ff2 100644 --- a/zh-cn/application-dev/ability/stage-ability.md +++ b/zh-cn/application-dev/ability/stage-ability.md @@ -315,13 +315,9 @@ struct Index { console.info('Index onPageShow') let newWant = globalThis.newWant if (newWant.hasOwnProperty("uri")) { - router.push({ uri: newWant.uri }); + router.push({ url: newWant.uri }); globalThis.newWant = undefined } } } -``` - -## 相关实例 -针对Stage模型Ability开发,有以下相关示例可供参考: -- [`StageCallAbility`:StageCallAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) +``` \ No newline at end of file diff --git a/zh-cn/application-dev/ability/stage-brief.md b/zh-cn/application-dev/ability/stage-brief.md index 5adca9fd9cd56566346a079a5ecc3aee9b0fda47..3c8b11d15187935da2f5f06539e569d9e01631de 100644 --- a/zh-cn/application-dev/ability/stage-brief.md +++ b/zh-cn/application-dev/ability/stage-brief.md @@ -2,93 +2,98 @@ ## 设计思想 -​ Stage模型的设计,主要是为了解决FA模型无法解决的开发场景问题,方便开发者更加方便地开发出分布式环境下的复杂应用。 +​Stage模型的设计,是为了提供给开发者一个更好的开发方式,更好的适用于多设备、分布式场景。 -​ Stage模型的设计思想如下图所示。 +​Stage模型的设计思想如下图所示。 ![stagedesign](figures/stagedesign.png) -​ Stage模型的设计基于如下三个出发点: +​Stage模型的设计基于如下三个出发点: -- **应用的能力与系统总体功能和功耗的平衡** +- **应用进程的有序管理** - ​ 在系统运行过程中,前台应用的资源占用会被优先保障,与此同时由于应用能力不同而产生的功耗,也需要符合系统整体功耗的要求。Stage模型通过Ability与UI分离、严格的后台管控、基于场景的服务机制及单进程模型来达成这种应用能力与整体系统功耗的平衡。 +随着设备的内存越来越大,系统中同时运行的进程数量也越来越多。当数百个进程同时运行时,如果没有有效的管理措施,则系统整体的功耗和性能将无法得到保证。Stage模型中,通过短时任务、长时任务、托管任务和延迟任务四种方法对后台进程做了有序约束。这样做使得前台进程的资源得以保障,最终能获得更好的用户体验。 -- **原生支持组件级的迁移和协同** +- **原生支持跨端迁移和多端协同** - ​ OpenHarmony是原生支持分布式的操作系统,应用框架需要从架构设计上使得组件更易于实现迁移和协同。Stage模型通过Ability与UI分离及UI展示与服务能力合一等模型特性,实现这一设计目标。 +OpenHarmony是原生分布式的操作系统,应用框架需要从架构设计上使得组件更易于实现跨端迁移和多端协同。Stage模型通过Ability与UI分离及UI展示与服务能力合一等模型特性,实现这一设计目标。 -- **支持多设备和多窗口形态的特点** - - ​ 为了支持多种设备形态和更易于实现多种不同的窗口形态,需要组件管理服务和窗口管理服务在架构层面上是解耦的,从而方便裁剪,更有利于定制不同的窗口形态。Stage模型通过重新定义了Ability生命周期定义和设计组件管理服务和窗口管理服务的单向依赖解决这一问题。 +- **支持多种设备的不同窗口形态** +Stage模型重新定义了Ability的生命周期。系统在架构上,将应用组件管理服务和窗口管理服务进行了彼此解耦,这样做可以方便的针对特定设备进行适配,以实现出不同的窗口形态。 ## 基本概念 -​ 下图展示了Stage模型中的基本概念。 +下图展示了Stage模型中的基本概念。 ![stageconcept](figures/stageconcept.png) -- **HAP**:即HarmonyAbilityPackage,OpenHarmony应用编译、分发、加载的基本单位,也称为module,每个HAP都有一个应用内唯一的名称,称为moduleName; +- **HAP**:OpenHarmony应用编译、分发、加载的基本单位。与开发态的module一一对应。在应用内,moduleName是其唯一标识; - **Bundle**:通过appid标识的OpenHarmony应用,Bundle可以包含多个HAP,每个应用都有一个bundleName,但是bundleName并不能唯一标识一个应用,appid中包含bundleName以及其他的更多信息,能够唯一标识一个应用; -- **AbilityStage**:对应HAP的运行期类,在HAP首次加载到进程中时创建,运行期开发者可见; -- **Application**:对应Bundle的运行期类,运行期开发者不可见; -- **Context**:提供运行期开发者可以调用的各种能力,Ability组件和各种ExtensionAbility都有各自不同的context类,他们都继承自基类Context,基类提供包名、moduleName、路径等信息; -- **Ability**:提供生命周期回调,持有AbilityContext,支持组件迁移/协同; -- **ExtensionAbility**:基于场景的服务扩展能力统称,系统定义了多种基于场景的ExtensionAbility类,它们持有各自的ExtensionContext; +- **AbilityStage**:对应HAP的运行期对象,在HAP首次加载到进程中时创建,运行期开发者可见; +- **Application**:对应Bundle的运行期对象,运行期开发者不可见; +- **Context**:提供运行期开发者可以调用的各种能力,Ability组件和各种ExtensionAbility都有各自不同的Context类,他们都继承自基类Context,基类提供包名、moduleName、路径等信息; +- **Ability**:提供生命周期回调,持有AbilityContext,支持组件的跨端迁移和多端协同; +- **ExtensionAbility**:基于场景的扩展能力统称,系统定义了多种场景的ExtensionAbility类,它们持有各自的ExtensionContext; - **WindowStage**:本地窗口管理器; -- **Window**:窗口 管理器管理的基本单元,持有一个ArkUI引擎实例; -- **ArkUI Page**:方舟开发框架页面。 +- **Window**:应用窗口,持有一个ArkUI引擎实例; +- **ArkUI Page**:基于ArkUI开发的用户界面。 ## 生命周期 -​ Ability及AbilityStage的生命周期是应用的基本流程中最重要的概念。在[Ability框架概述](ability-brief.md)中,给出了FA模型与Stage模型的生命周期对比,这里重点对Ability生命周期切换以及和AbilityStage、WindowStage之间的调度关系进行介绍。 +AbilityStage及Ability是关于应用生命周期的关键对象。 + +在[Ability框架概述](ability-brief.md)中,给出了FA模型与Stage模型的生命周期对比,因此这里仅对Ability生命周期切换以及和AbilityStage、WindowStage之间的调度关系进行介绍。 ![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png) -​ 为了实现多设备形态上的裁剪和多窗口的可扩展性,OpenHarmony对组件管理和窗口管理进行了解耦。Stage模型定义Ability组件的生命周期,只包含创建、销毁、前后台等状态,而将与界面相关内容强相关的获焦、失焦状态放在WindowStage之中,从而实现Ability与窗口之间的弱耦合;在服务侧,窗口管理服务依赖于组件管理服务,前者通知后者前后台变化,这样组件管理服务仅感知前后台变化,不感知焦点变化。 +为了实现多设备形态上的适配和多窗口的扩展,OpenHarmony对组件管理和窗口管理进行了解耦。 + +Stage模型定义Ability组件的生命周期,只包含创建、销毁、前后台等状态,而将与界面强相关的获焦、失焦状态都放在WindowStage之中,从而实现Ability与窗口之间的弱耦合;在服务侧,窗口管理服务依赖于组件管理服务,前者通知后者前后台变化,这样组件管理服务仅感知前后台变化,不感知焦点变化。 -​ 需要注意的是,在Ability中存在两个与WindowStage相关的生命周期状态onWindowStageCreate和onWindowStageDestroy,这两个生命周期状态的变化仅存在于具有窗口显示能力的设备中。前者表示WindowStage已经创建完成,开发者可以通过执行loadContent的操作设置Ability需要加载的页面;后者在WindowStage销毁后调用,从而便于开发者对资源进行释放。 +需要注意的是,在Ability中存在两个与WindowStage相关的生命周期状态onWindowStageCreate和onWindowStageDestroy,这两个生命周期状态的变化仅存在于具有显示能力的设备中。前者表示WindowStage已经创建完成,开发者可以通过执行loadContent的操作设置Ability需要加载的页面;后者在WindowStage销毁后调用,以便开发者对资源进行释放。 ## Ability组件实例与任务 -​ Ability组件有三种启动类型: - -+ **Singleton**:应用进程中只存在一个该类型的Ability实例,如下图Ability1; - -+ **Standard**:每次startAbility调用,都会在应用进程中创建一个该类型的实例,如下图Ability2的两个实例; +Ability组件有三种启动类型: -+ **Specified**:允许开发者在系统创建Ability实例之前,为该实例创建一个key,后续每次创建该类型的Ability实例都会询问应用使用哪个key对应的Ability实例,来响应startAbility请求,如下图Ability3。 +* **Singleton**:应用进程中只存在一个该类型的Ability实例,如下图Ability1; +* **Standard**:每次startAbility调用,都会在应用进程中创建一个该类型的实例,如下图Ability2的两个实例; +* **Specified**:允许开发者在系统创建Ability实例之前,为该实例创建一个key,后续每次创建该类型的Ability实例都会询问应用使用哪个key对应的Ability实例,来响应startAbility请求,如下图Ability3。 -​ 每个Ability实例都对应了一个Launcher Recent中看到的Mission(任务)。 +每个Ability实例都对应了一个近期任务中的Mission(任务)。 -​ 每个Ability实例对应的Mission都留有该Ability实例的快照,Ability实例销毁后,Mission中的会保留Ability的类的信息和快照,直到用户删除,或者超过存储上限。 +每个Ability实例对应的Mission都留有该Ability实例的快照,Ability实例销毁后,Mission中会继续保留Ability的类的信息和快照,直到用户删除,或者超过存储上限。 ![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png) ## ExtensionAbility机制 -​ 不同于用于页面展示的Ability,ExtensionAbility提供的是一种受限的服务运行环境。ExtensionAbility具有如下特点: +不同于页面展示的Ability,ExtensionAbility提供的是一种受限的运行环境。 + +ExtensionAbility组件具有如下特点: -- 独立于主进程的单独进程运行,与主进程无IPC,共享一个存储沙箱; +- 运行在独立于主进程的单独进程中,与主进程无IPC,但共享一个存储沙箱; -- 独立的Context提供基于业务场景的api能力; +- 独立的Context提供基于相应业务场景的API能力; - 由系统触发创建,应用不能直接创建; - ExtensionAbility和进程的生命周期受系统管理。 -​ 下图以卡片服务使用场景为例进行展示,系统提供了FormExtensionAbility基类,开发者通过派生提供卡片的具体信息。FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由系统服务FormManagerService进行管理。 +下图以卡片使用场景为例进行展示。系统提供了FormExtensionAbility基类,开发者通过派生提供卡片的具体信息。FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由系统服务FormManagerService进行管理。 ![ExtensionAbility](figures/ExtensionAbility.png) ## 进程模型 -​ OpenHarmony系统中的应用均满足单进程模型。所谓的单进程模型,是指不允许应用配置多进程,应用中所有的进程都是由系统创建和管理的。每个应用至多并存三类进程: +OpenHarmony系统对于应用进程是有强管控策略的。对于开发者来说,没有自行配置多进程的能力。应用的所有进程都是由系统创建和管理的。 + +每个应用的进程可以分为三类: -- 主进程:运行所有的Ability组件、页面和业务逻辑; +- 主进程:运行UIAbility组件、页面和业务逻辑; - Extension进程:运行应用中的ExtensionAbility派生类,该进程由系统中的特定场景的服务管理其生命周期; diff --git a/zh-cn/application-dev/ability/stage-call.md b/zh-cn/application-dev/ability/stage-call.md index 7aa9769c0a56c39bc9d93772c5a1e0cd7d4ba2f3..a1f9a5d5d54e54dfec706dcd4823d8384a5b8641 100644 --- a/zh-cn/application-dev/ability/stage-call.md +++ b/zh-cn/application-dev/ability/stage-call.md @@ -40,14 +40,13 @@ Caller及Callee功能如下:具体的API详见[接口文档](../reference/apis |call(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据。| |callWithResult(method: string, data: rpc.Sequenceable): Promise\|向通用组件Callee发送约定序列化数据, 并将Callee返回的约定序列化数据带回。| |release(): void|释放通用组件的Caller通信接口。| -|onRelease(callback: OnReleaseCallBack): void|注册通用组件通信断开监听通知。| +|on(type: "release", callback: OnReleaseCallback): void|注册通用组件通信断开监听通知。| ## 开发步骤 Call调用的开发步骤: - 创建Callee被调用端。 - 访问Callee被调用端。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 开发步骤章节中的示例代码片段是开发过程的步骤化展示,部分代码可能无法单独运行,完整工程代码请参考[相关实例](#相关实例)。 + ### 创建Callee被调用端 Callee被调用端,需要实现指定方法的数据接收回调函数、数据的序列化及反序列化方法。在需要接收数据期间,通过on接口注册监听,无需接收数据时通过off接口解除监听。 **1. 配置Ability的启动模式** @@ -72,7 +71,7 @@ Ability配置标签示例如下: ``` **2. 导入Ability模块** ```ts -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.UIAbility' ``` **3. 定义约定的序列化数据** @@ -142,7 +141,7 @@ export default class CalleeAbility extends Ability { ### 访问Callee被调用端 **1. 导入Ability模块** ```ts -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.UIAbility' ``` **2. 获取Caller通信接口** @@ -151,7 +150,7 @@ import Ability from '@ohos.application.Ability' // 注册caller的release监听 private regOnRelease(caller) { try { - caller.onRelease((msg) => { + caller.on("release", (msg) => { console.log(`caller onRelease is called ${msg}`) }) console.log('caller register OnRelease succeed') @@ -192,7 +191,7 @@ async onButtonGetRemoteCaller() { caller = data console.log('get remote caller success') // 注册caller的release监听 - caller.onRelease((msg) => { + caller.on("release", (msg) => { console.log(`remote caller onRelease is called ${msg}`) }) console.log('remote caller register OnRelease succeed') @@ -280,8 +279,4 @@ releaseCall() { console.log(`caller release failed with ${error}`) } } -``` - -## 相关实例 -针对Stage模型本地Call功能开发,有以下相关实例可供参考: -- [`StageCallAbility`:StageCallAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) +``` \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index 3a89466da4747b55dae10e73bc1d17c1b2730ce4..5414bdccc785edac63a96ae75a2b0b2676bdc0c3 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -114,7 +114,10 @@ ### 设置分布式列表 ->**注意:** 在使用RdbStore的setDistributedTables、obtainDistributedTableName、sync、on、off接口时,需要请求相应的权限:ohos.permission.DISTRIBUTED_DATASYNC。 +> **说明:** +> +> - 在使用RdbStore的setDistributedTables、obtainDistributedTableName、sync、on、off接口时,需要请求相应的权限:ohos.permission.DISTRIBUTED_DATASYNC。 +> - 使用分布式列表前,需要先建立设备间组网,具体接口及使用可见[设备管理](../reference/apis/js-apis-device-manager.md)。 **设置分布式列表** diff --git a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md index 68fdf02768765624b98daf60e2b431bd3af11bf8..8df6e2ee0c5a87b0b400cc85ced09eeccc5fb6d8 100644 --- a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md +++ b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @@ -277,7 +277,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message); } - // 无maNum参数异步方法promise方式 + // 无maxNum参数异步方法promise方式 try{ usageStatistics.queryModuleUsageRecords().then( res => { console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise succeeded'); @@ -309,7 +309,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message); } - // 无maNum参数异步方法callback方式 + // 无maxNum参数异步方法callback方式 try{ usageStatistics.queryModuleUsageRecords((err, res) => { if(err) { diff --git a/zh-cn/application-dev/device/Readme-CN.md b/zh-cn/application-dev/device/Readme-CN.md index e104eb19bee15a03d98dfcc88c52fd908648dfd0..9d211b929513eb5638f71e1ff0a98a115c8bb727 100644 --- a/zh-cn/application-dev/device/Readme-CN.md +++ b/zh-cn/application-dev/device/Readme-CN.md @@ -13,6 +13,9 @@ - 振动 - [振动开发概述](vibrator-overview.md) - [振动开发指导](vibrator-guidelines.md) +- 设备管理 + - [输入设备开发指导](inputdevice-guidelines.md) + - [鼠标光标开发指导](pointerstyle-guidelines.md) - 升级服务 - [示例服务器开发概述](sample-server-overview.md) - [示例服务器开发指导](sample-server-guidelines.md) diff --git a/zh-cn/application-dev/device/inputdevice-guidelines.md b/zh-cn/application-dev/device/inputdevice-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..166f085cc394b7f20c6773ec9c6f8ec2b80ad5c6 --- /dev/null +++ b/zh-cn/application-dev/device/inputdevice-guidelines.md @@ -0,0 +1,70 @@ +# 输入设备开发指导 + +## 场景介绍 + +输入设备管理提供设备热插拔监听、查询指定设备的键盘类型等能力。使用场景例如:当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔判断是否有物理键盘插入。 + +## 导入模块 + +```js +import inputDevice from '@ohos.multimodalInput.inputDevice'; +``` + +## 接口说明 + +输入设备管理常用接口如下表所示,接口详细介绍请参考[ohos.multimodalInput.inputDevice文档](../reference/apis/js-apis-inputdevice.md)。 + +| 实例名 | 接口名 | 说明 | +| ----------- | ------------------------------------------------------------ | -------------------------- | +| inputDevice | **function** getDeviceList(callback: AsyncCallback>): **void**; | 获取输入设备列表。 | +| inputDevice | **function** getKeyboardType(deviceId: **number**, callback: AsyncCallback): **void**; | 获取输入设备的键盘类型。 | +| inputDevice | **function** on(**type**: "change", listener: Callback): **void**; | 监听输入设备的热插拔事件。 | +| inputDevice | **function** off(**type**: "change", listener?: Callback): **void**; | 取消监听输入设备的热插拔事件。 | + +## 虚拟键盘弹出检测 + +当用户需要输入文本时,输入法会根据当前是否插入了物理键盘来决定是否弹出虚拟键盘,开发者可以通过监听设备热插拔,判断是否有物理键盘插入。 + +## 开发步骤 + +1. 调用getDeviceList方法查询所有连接的输入设备,调用getKeyboardType方法遍历所有连接的设备,判断是否有物理键盘,若有则标记已有物理键盘连接,该步骤确保监听设备热插拔之前,检测所有插入的输入设备。 +2. 调用on接口监听输入设备热插拔事件,若监听到有物理键盘插入,则标记已有物理键盘连接;若监听到有物理键盘拔掉,则标记没有物理键盘连接。 +3. 文本框进行输入时,判断是否有物理键盘连接,如果有物理键盘则不弹出虚拟键盘,如果没有物理键盘则弹出虚拟键盘。 + + +```js +import inputDevice from '@ohos.multimodalInput.inputDevice'; + +let isPhysicalKeyboardExist = true; +try { + // 1.获取设备列表,判断是否有物理键盘连接 + inputDevice.getDeviceList().then(data => { + for (let i = 0; i < data.length; ++i) { + inputDevice.getKeyboardType(data[i]).then(res => { + if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) { + // 物理键盘已连接 + isPhysicalKeyboardExist = true; + } + }); + } + }); + // 2.监听设备热插拔 + inputDevice.on("change", (data) => { + console.log(`Device event info: ${JSON.stringify(data)}`); + inputDevice.getKeyboardType(data.deviceId, (error, type) => { + console.log("The keyboard type is: " + type); + if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') { + // 物理键盘已插入 + isPhysicalKeyboardExist = true; + } else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') { + // 物理键盘已拔掉 + isPhysicalKeyboardExist = false; + } + }); + }); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} + // 3.根据isPhysicalKeyboardExist的值决定虚拟键盘是否弹出 + // TODO +``` diff --git a/zh-cn/application-dev/device/pointerstyle-guidelines.md b/zh-cn/application-dev/device/pointerstyle-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..a2bf27e017bab128a56cb2f1af4213490e0e6c63 --- /dev/null +++ b/zh-cn/application-dev/device/pointerstyle-guidelines.md @@ -0,0 +1,119 @@ +# 鼠标光标开发指导 + +## 场景介绍 + +鼠标光标控制提供对鼠标光标显示隐藏、光标样式查询设置的能力。使用场景例如:用户在全屏观看视频时,开发者可以控制鼠标光标的显示隐藏;当用户执行取色时,开发者可以将鼠标光标样式切换为取色器样式。 + +## 导入模块 + +```js +import inputDevice from '@ohos.multimodalInput.pointer'; +``` + +## 接口说明 + +鼠标光标控制常用接口如下表所示,接口详细介绍请参见[ohos.multimodalInput.pointer文档](../reference/apis/js-apis-pointer.md) + +| 实例名 | 接口名 | 说明 | +| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| pointer | **function** isPointerVisible(callback: AsyncCallback): **void**; | 获取鼠标指针显示或隐藏状态。 | +| pointer | **function** setPointerVisible(visible: boolean, callback: AsyncCallback<**void**>): **void**; | 设置鼠标指针显示或隐藏状态,改接口会影响全局鼠标光标的显示状态。 | +| pointer | **function** setPointerStyle(windowId: **number**, pointerStyle: PointerStyle, callback: AsyncCallback<**void**>): **void**; | 设置鼠标光标样式,改接口会影响指定窗口鼠标光标样式。 | +| pointer | **function** getPointerStyle(windowId: **number**, callback: AsyncCallback): **void**; | 查询鼠标光标样式。 | + +## 设置鼠标光标隐藏 + +用户在全屏观看视频时,可以调用鼠标光标的隐藏接口设置鼠标光标不可见,提升用户体验。 + +## 开发步骤 + +1. 应用切换到全屏播放。 +2. 在应用中调用鼠标光标隐藏接口隐藏光标。 +3. 应用退出全屏播放。 +4. 在应用中调用鼠标光标显示接口显示光标。 + +```js +import pointer from '@ohos.multimodalInput.pointer'; + +// 1.应用切换到全屏播放 +// 2.调用鼠标光标隐藏接口隐藏光标 +try { + pointer.setPointerVisible(false, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer visible success.`); + }); +} catch (error) { + console.log(`The mouse pointer hide attributes is failed. ${JSON.stringify(error, [`code`, `message`])}`); +} + +// 3.应用退出全屏播放 +// 4.调用鼠标光标显示接口显示光标 +try { + pointer.setPointerVisible(true, (error) => { + if (error) { + console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Set pointer visible success.`); + }); +} catch (error) { + console.log(`Set pointer visible failed, ${JSON.stringify(error, [`code`, `message`])}`); +} +``` + +## 设置鼠标光标样式 + +当开发者设计取色器特性时,可以将鼠标光标样式切换为取色器样式,完成取色后,设置鼠标光标样式为默认样式,该接口设置和查询当前应用内指定窗口的光标样式,总共可设置39种光标样式,具体参考[光标样式](../reference/apis/js-apis-pointer.md#pointerstyle9)。 + +### 开发步骤 + +1. 开发者使能取色功能。 +2. 调用窗口实例获取对应的窗口id。 +3. 设置鼠标光标样式为取色器样式。 +4. 取色结束。 +5. 设置鼠标光标样式为默认样式。 + +```js +import window from '@ohos.window'; + +// 1.开发者使能取色功能 +// 2.调用窗口实例获取对应的窗口id +window.getTopWindow((error, windowClass) => { + windowClass.getProperties((error, data) => { + var windowId = data.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 3.设置鼠标光标样式为取色器样式 + pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); + } + }); +}); +// 4.取色结束 +window.getTopWindow((error, windowClass) => { + windowClass.getProperties((error, data) => { + var windowId = data.id; + if (windowId < 0) { + console.log(`Invalid windowId`); + return; + } + try { + // 5.设置鼠标光标样式为默认样式 + pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => { + console.log(`Successfully set mouse pointer style`); + }); + } catch (error) { + console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`); + } + }); +}); +``` diff --git a/zh-cn/application-dev/faqs/faqs-ability.md b/zh-cn/application-dev/faqs/faqs-ability.md index de4a7106e7f80f5ea921ae7263bbb7ddcfd6eba7..e47016338696cda908002b817ed81ef2a2732f2d 100644 --- a/zh-cn/application-dev/faqs/faqs-ability.md +++ b/zh-cn/application-dev/faqs/faqs-ability.md @@ -91,7 +91,7 @@ Ability配置中缺少startWindowIcon属性配置,需要在module.json5中abil 不推荐,Stage模型使用globalThis去获取Context是错误的使用方式。在Stage模型中,整个应用进程共用一个js虚拟机实例,其中可以运行多个Ability实例,共用一个global对象。在同一个js虚拟机内的不同的Ability中使用globalThis获取Context,存在被覆盖从而发生错误的风险。 -推荐使用方式参考:[Stage模型和Context详细介绍](../ability/context-userguide.md#stage%E6%A8%A1%E5%9E%8B%E5%92%8Ccontext%E8%AF%A6%E7%BB%86%E4%BB%8B%E7%BB%8D)。 +推荐使用方式参考:[Stage模型的Context详细介绍](../ability/context-userguide.md#stage模型的context详细介绍)。 ## 如何在应用A中去获取应用B的Hap包的安装路径 @@ -145,13 +145,12 @@ Full SDK : 面向OEM厂商提供,包含了需要使用系统权限的系统接 可以通过点击卡片拉起响应的Ability后,通过Ability来实现业务登录场景。 -## 如何跳转到设置中应用详情页面。 +## 如何跳转到设置中应用详情页面 使用于:OpenHarmony SDK 3.2.6.5版本 参考如下代码实现,示例: - ``` this.context.startAbility( { @@ -166,7 +165,6 @@ this.context.startAbility( 参考如下代码实现,示例: - ``` let listener = mediaquery.matchMediaSync('(orientation: landscape)') onPortrait(mediaQueryResult) { @@ -216,5 +214,3 @@ listener.on('change', onPortrait) 1. router.disableAlertBeforeBackPage和router.enableAlertBeforeBackPage类似一个开关,disableAlertBeforeBackPage是返回上一级页面时关闭弹窗提示,enableAlertBeforeBackPage是打开弹窗提示,默认是关闭的,当你需要使用时,首先要在一个函数里面开启功能,然后再执行跳转 2. 必须要使用系统的返回按键才能触发效果。 - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-bundle.md b/zh-cn/application-dev/faqs/faqs-bundle.md index 1a6dd935511aa94a8ce19e937584ce0cd9ac3eb2..2a3672e8ccb4a50f9a99d7ec669d5bb04bbb8bf7 100644 --- a/zh-cn/application-dev/faqs/faqs-bundle.md +++ b/zh-cn/application-dev/faqs/faqs-bundle.md @@ -14,7 +14,7 @@ 通过可以context.abilityInfo.bundleName获取。 -参考文档:[AbilityContext](../reference/apis/js-apis-ability-context.md#%E5%B1%9E%E6%80%A7)、[AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) +参考文档:[AbilityContext](../reference/apis/js-apis-ability-context.md)、[AbilityInfo](../reference/apis/js-apis-bundle-AbilityInfo.md) ## 如何获取应用图标 @@ -29,5 +29,3 @@ 使用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 使用bundle模块的getApplicationInfo接口获取待检验的应用的ApplicaitonInfo,根据ApplicaitonInfo中systemApp字段判断,若为true,则是系统应用,否则为非系统应用。 - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-connectivity.md b/zh-cn/application-dev/faqs/faqs-connectivity.md index 70ae807faed016ac0758f9d847d1763469295a2f..c50e44cc0fae760cb9f2b3cc6cba87d541dece44 100644 --- a/zh-cn/application-dev/faqs/faqs-connectivity.md +++ b/zh-cn/application-dev/faqs/faqs-connectivity.md @@ -18,7 +18,7 @@ extraData代表发送请求的额外数据,支持如下数据: 错误码28代表CURLE_OPERATION_TIMEDOUT,操作超时。网络请求底层使用libcurl库,更多错误码可以查看相应文档。 -参考文档:[开发指南](../reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) +参考文档:[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)和[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) ## \@ohos.net.http.d.ts的response错误码返回6是什么意思? @@ -26,7 +26,7 @@ extraData代表发送请求的额外数据,支持如下数据: 6表示地址无法解析主机,可以尝试ping一下request中的url,确认是否可以ping通。 -更多错误码参考[Response常用错误码](../reference/apis/js-apis-http.md#response%E5%B8%B8%E7%94%A8%E9%94%99%E8%AF%AF%E7%A0%81)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) +更多错误码参考[Response常用错误码](../reference/apis/js-apis-http.md#response常用错误码)或者[Curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) ## 调用camera拍摄的照片怎么上传到服务器 @@ -102,5 +102,3 @@ connection.hasDefaultNet().then((has)=> { console.log("hasDefaultNet " + JSON.stringify(has)) }) ``` - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-data-management.md b/zh-cn/application-dev/faqs/faqs-data-management.md index 34cbf014a6c03b27112f004bfb62a76fbb08f74f..fe93fd317d45da13a673fc7ea798f604ecf59ba6 100644 --- a/zh-cn/application-dev/faqs/faqs-data-management.md +++ b/zh-cn/application-dev/faqs/faqs-data-management.md @@ -71,5 +71,3 @@ PixelMap应该被转换成相应的ArrayBuffer再放进数据库。 Stage模型DataShare不可与FA模型DataAbility混用,连接的服务端应用需使用DataShareExtensionAbility实现。 参考文档:[数据共享开发指导](../database/database-datashare-guidelines.md) - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-development-board.md b/zh-cn/application-dev/faqs/faqs-development-board.md index 9cb08327acb47e58f2c5172b4c7abc9fddc92da1..d6965edfbca602392190f3518925b9eb2238fc08 100644 --- a/zh-cn/application-dev/faqs/faqs-development-board.md +++ b/zh-cn/application-dev/faqs/faqs-development-board.md @@ -1,6 +1,4 @@ -# 开发板 - - +# 开发板使用常见问题 ## 如何获取开发板上截屏图片? @@ -50,4 +48,3 @@ 连接需要认证的网络后,用浏览器打开任意网址就可以进入认证页面。 如果开发板上没有浏览器,可以安装[浏览器Sample应用](https://gitee.com/openharmony/app_samples/tree/master/device/Browser)。 - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-device-management.md b/zh-cn/application-dev/faqs/faqs-device-management.md index bf7e0c554ff06ce77f78ccde357af7a589266e62..bb4bb7d211450089c05f9bb09d6669b0c6fe5747 100644 --- a/zh-cn/application-dev/faqs/faqs-device-management.md +++ b/zh-cn/application-dev/faqs/faqs-device-management.md @@ -48,4 +48,3 @@ display.getDefaultDisplay((err, data) => { 适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 快捷键功能开发请使用组合按键api,具体可参考[组合按键(InputConsumer)](../reference/apis/js-apis-inputconsumer.md) - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-dfx.md b/zh-cn/application-dev/faqs/faqs-dfx.md index 7a61473320168cb5b17a6c2854ff6c1e907a1b2f..a3554754afbb91ddd6a4acaaf094eae06105375e 100644 --- a/zh-cn/application-dev/faqs/faqs-dfx.md +++ b/zh-cn/application-dev/faqs/faqs-dfx.md @@ -52,4 +52,3 @@ 适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 使用命令:hdc_std shell hilog -p off - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-event-notification.md b/zh-cn/application-dev/faqs/faqs-event-notification.md index 3a24c9932f390125c1f72fad4841485da0ffc1cc..a035a5890812c27cd910dd44cea913b3f7abc0c2 100644 --- a/zh-cn/application-dev/faqs/faqs-event-notification.md +++ b/zh-cn/application-dev/faqs/faqs-event-notification.md @@ -46,4 +46,3 @@ async function publishNotification() { prompt.showToast({ message: "发送成功" }) } ``` - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-file-management.md b/zh-cn/application-dev/faqs/faqs-file-management.md index 3f96dd3a98da89cf07518a831e4d6bc6184c49ef..67e62ffbed453a16247afdc5314a979764f278ba 100644 --- a/zh-cn/application-dev/faqs/faqs-file-management.md +++ b/zh-cn/application-dev/faqs/faqs-file-management.md @@ -109,5 +109,3 @@ Stage模型下,获取媒体库实例应该调用mediaLibrary.getMediaLibrary(c 适用于:OpenHarmonySDK 3.2.5.5版本,API9 Stage模型 通过[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)对象参数里面的order属性进行排序。 - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-graphics.md b/zh-cn/application-dev/faqs/faqs-graphics.md index e477c759a33339ba7c66c4602a135247e16fe679..61d9981d2befa6ee795700da926e13a84cdec0a6 100644 --- a/zh-cn/application-dev/faqs/faqs-graphics.md +++ b/zh-cn/application-dev/faqs/faqs-graphics.md @@ -1,6 +1,6 @@ # 图形图像开发常见问题 -## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 +## 调用window实例的setSystemBarProperties接口时,设置isStatusBarLightIcon和isNavigationBarLightIcon属性不生效 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -12,7 +12,7 @@ 导入\@ohos.window模块,开发者可以使用window.setSystemBarProperties()接口设置状态栏样式属性,达到自定义样式的效果。 -## 如何隐藏状态栏,实现沉浸式效果。 +## 如何隐藏状态栏,实现沉浸式效果 适用于:OpenHarmony SDK 3.2.6.3版本,API9 Stage模型 @@ -88,4 +88,3 @@ window.getTopWindow(globalThis.mainContext).then(win => { INDEX_LOGGER.info(`get top window failed:${err}`) }) ``` - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-hdc-std.md b/zh-cn/application-dev/faqs/faqs-hdc-std.md index cc59cedda4c59675291082d4bf347907d19a5442..3690a4d9c69c27514f233c00d8bd62640241d563 100644 --- a/zh-cn/application-dev/faqs/faqs-hdc-std.md +++ b/zh-cn/application-dev/faqs/faqs-hdc-std.md @@ -1,6 +1,6 @@ # hdc_std命令使用常见问题 -## 日志的常用命令 +## 日志的常用命令 适用于:OpenHarmony SDK 3.2.2.5版本 @@ -10,7 +10,7 @@ 抓取日志:hdc_std shell hilog > log.txt -## 日志限流怎么规避 +## 日志限流怎么规避 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -30,7 +30,7 @@ 请检查sdk和开发板烧录的系统版本是否一致,推荐取同一天的sdk和系统版本。 -## 如何通过hdc命令上传文件 +## 如何通过hdc命令上传文件 适用于:OpenHarmony SDK 3.2.2.5版本 @@ -85,4 +85,3 @@ 2. 输入 aa dump -a 找到abilityID。 3. aa dump -i [abilityID] -c -render 查看组件树。 - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-ide.md b/zh-cn/application-dev/faqs/faqs-ide.md index ae44f51ed4cc29b12acac31e812683678ef8be52..9d2cd9b7db09275aeedd988525bf663e7440d6b0 100644 --- a/zh-cn/application-dev/faqs/faqs-ide.md +++ b/zh-cn/application-dev/faqs/faqs-ide.md @@ -8,7 +8,7 @@ 2. 在Dev Eco Studio terminal中执行npm install。 -## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ArkTS-loader\node_modules\webpack\bin\webpack.js'” +## 手工更新DevEco的SDK后,编译HAP报错“Cannot find module 'xxx\ets\x.x.x.x\build-tools\ArkTS-loader\node_modules\webpack\bin\webpack.js'” 适用于:OpenHarmony SDK 3.2.5.3版本,API9 Stage模型 @@ -78,4 +78,3 @@ hdc 和 hdcd版本不匹配 ,请更新IDE至Dev Eco 3.0.1.993及以上版本 适用于:OpenHarmony SDK 3.2.7.5版本 参考文档[full-SDK替换指南](../quick-start/full-sdk-switch-guide.md) - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-international.md b/zh-cn/application-dev/faqs/faqs-international.md index 7b7cb4d62b7119e5bf998c85d30485543164b9c6..bbef24399ad9dfd0c33389edf7b4a66827b87b60 100644 --- a/zh-cn/application-dev/faqs/faqs-international.md +++ b/zh-cn/application-dev/faqs/faqs-international.md @@ -12,9 +12,8 @@ Resource为string支持限定词目录使用this.context.resourceManager.getStringSync(\\$r('app.string.test').id),可以同步转换,不支持\$r('app.string.test', 2)方式。更多用法请参考[ResourceManager(资源管理)](../reference/apis/js-apis-resource-manager.md#getstringsync9) -## form_config.json文件中使用$引用常量为什么不生效 +## form_config.json文件中使用$引用常量为什么不生效 适用于:OpenHarmony SDK 3.2.6.5, API9 Stage模型 form_config.json文件中不支持使用$引用常量。 - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-language.md b/zh-cn/application-dev/faqs/faqs-language.md index 80ebc349c6d1cbf5e93bad3d130332fa5e31fc7f..bbbdae095eea938dc6fc139263fda25b5545c940 100644 --- a/zh-cn/application-dev/faqs/faqs-language.md +++ b/zh-cn/application-dev/faqs/faqs-language.md @@ -86,7 +86,7 @@ resourceManager.getRawFile(path, (error, value) => { Page和Ability打包后会对import的对象分别形成两个不同的闭包,即打包出两个Global对象。因此,所引用的静态变量并不是同一对象,所以无法通过class静态变量方式定义全局变量。建议使用AppStorage进行全局变量管理。 -参考文档:[应用程序的数据存储](../ui/ts-application-states-appstorage.md) +参考文档:[应用程序的数据存储](../quick-start/arkts-state-mgmt-application-level.md) ## Stage模型下如何获取资源 @@ -107,7 +107,7 @@ context }) ``` -## 如何实现页面加载前从接口获取数据 +## 如何实现页面加载前从接口获取数据 适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 @@ -248,7 +248,7 @@ OpenHarmony推荐使用worker来处理多线程场景。 通过\@Observed配合\@ObjectLink装饰符实现。 -参考文档:[Observed和ObjectLink数据管理](../ui/ts-other-states-observed-objectlink.md) +参考文档:[Observed和ObjectLink数据管理](../quick-start/arkts-state-mgmt-page-level.md#observed和objectlink数据管理) ## 如何实现字符串编解码 @@ -285,4 +285,3 @@ OpenHarmony推荐使用worker来处理多线程场景。 适用于:OpenHarmony SDK 3.2.5.5版本, API9 Stage模型 不支持。 - diff --git a/zh-cn/application-dev/faqs/faqs-media.md b/zh-cn/application-dev/faqs/faqs-media.md index 7067465b3a6806fe302aa743985cf548df415e4a..7ced8a1d5ab3c80f6a9401565c410e84f18ad5d6 100644 --- a/zh-cn/application-dev/faqs/faqs-media.md +++ b/zh-cn/application-dev/faqs/faqs-media.md @@ -8,7 +8,7 @@ 2. 根据相机位置和类型创建CameraInput实例 -参考文档:[相机管理](../reference/apis/js-apis-camera.md#%E7%9B%B8%E6%9C%BA%E7%AE%A1%E7%90%86) +参考文档:[相机管理](../reference/apis/js-apis-camera.md) 示例: @@ -126,5 +126,3 @@ cameraInput = await this.cameraManager.createCameraInput(cameraId)熊文帅 适用于:OpenHarmonySDK 3.2.7.5版本,API9 Stage模型 当前限制最多创建13个媒体播放实例。 - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-native.md b/zh-cn/application-dev/faqs/faqs-native.md index dd433fa987244614294652e0ed41f4fc68f877ae..c0a05db2c35d6b5a4bfb885715def72b0b204edf 100644 --- a/zh-cn/application-dev/faqs/faqs-native.md +++ b/zh-cn/application-dev/faqs/faqs-native.md @@ -77,5 +77,3 @@ static napi_value Add(napi_env env, napi_callback_info info) 适用于:OpenHarmony SDK 3.2版本以上,API9 Stage模型 使用Native API中的OH_ResourceManager_OpenRawDir()方法获取到rawfile的根目录,然后对其进行遍历。可参考文档:[Native开发指导](../reference/native-apis/rawfile.md) - - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-third-party-library.md b/zh-cn/application-dev/faqs/faqs-third-party-library.md index 5397dc2a81320f16c23a95050855832d6aed7eb3..a15136dfb734e626c50c6fb7875c842a3f9d0764 100644 --- a/zh-cn/application-dev/faqs/faqs-third-party-library.md +++ b/zh-cn/application-dev/faqs/faqs-third-party-library.md @@ -72,4 +72,3 @@ ``` import dayjs from 'dayjs'; ``` - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-ui-ets.md b/zh-cn/application-dev/faqs/faqs-ui-ets.md index 14ed099e0a8f705ab2c574bddd8f10d283e5c108..b4645777a29e8e4e89935dce05a29c3f8cf3aaa8 100644 --- a/zh-cn/application-dev/faqs/faqs-ui-ets.md +++ b/zh-cn/application-dev/faqs/faqs-ui-ets.md @@ -141,7 +141,7 @@ struct DialogTest { GridContainer内子组件默认水平左对齐,居中显示可以参考以下处理方式: -内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](../ui/ui-ts-layout-grid-container.md)文档。 +内部嵌套布局组件Row,设置Row属性justifyContent(FlexAlign.Center),内部嵌套子组件可保持居中显示,参考[栅格布局](../reference/arkui-ts/ts-container-gridcontainer.md)文档。 示例: @@ -276,7 +276,7 @@ private value: string = router.getParams()['value']; 适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 -1. 参考[页面间转场示例](../reference/arkui-ts/ts-page-transition-animation.md/#%E7%A4%BA%E4%BE%8B)在当前页面和目标页面中定义pageTransition方法。 +1. 参考[页面间转场示例](../reference/arkui-ts/ts-page-transition-animation.md#示例)在当前页面和目标页面中定义pageTransition方法。 2. 将页面入场组件PageTransitionEnter和页面退场组件PageTransitionExit的动效参数duration都设置为0。 @@ -306,7 +306,7 @@ fontColor( '#7F000000' ) 适用于:OpenHarmony SDK 3.2.5.5版本,API9 Stage模型 -在Page页面返回时,系统会调用\@Entry修饰的自定义组件的onBackPress()回调,可以在回调函数中实现相关业务诉求。参考[自定义组件生命周期回调函数](../ui/ts-custom-component-lifecycle-callbacks.md) +在Page页面返回时,系统会调用\@Entry修饰的自定义组件的onBackPress()回调,可以在回调函数中实现相关业务诉求。参考[自定义组件生命周期回调函数](../ui/ui-ts-custom-component-lifecycle-callbacks.md) ## TextInput组件密码模式下,右边的眼睛图标是否支持自定义? @@ -344,12 +344,6 @@ constraintSize约束组件尺寸时,子组件内设置百分比宽度,例如 Scroll组件在未设置高度情况下,默认为窗口高度,当滚动区域外存在其他组件时,滚动底部区域会出现遮挡,需要设置Scroll高度,或者使用Flex布局限制Scroll高度 -## backgroundImage设置CenterCrop - -适用于:OpenHarmony SDK3.0, API9 Stage模型 - -CenterCrop是android中imageView,scaletype的设置,主要保证图片等比缩放裁剪,位置保持居中,可以使用通用属性backgroundImageSize(ImageSize.cover)和backgroundImagePosition(Alignment.Center)达到使用效果 - ## 输入框组件TextInput回车事件onSubmit使用 适用于:OpenHarmony SDK3.0, API9 Stage模型 @@ -366,7 +360,7 @@ onSubmit事件在回车键或软键盘回车触发该回调,参数为当前软 适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 -支持使用[条件渲染](../ui/ts-rending-control-syntax-if-else.md)和[循环渲染](../ui/ts-rending-control-syntax-foreach.md)等方式进行动态创建组件。 +支持使用[条件渲染](../quick-start/arkts-rendering-control.md#条件渲染)和[循环渲染](../quick-start/arkts-rendering-control.md#循环渲染)等方式进行动态创建组件。 ## 页面路由携带PixelMap对象参数,跳转页面无法获取 @@ -596,15 +590,7 @@ RichText底层是web,可以参考html的语法,在div上加上的overflow: 可以通过onScrollBegin事件和scrollBy方法实现容器嵌套滚动。 -参考:[容器嵌套滚动样例](../reference/arkui-ts/ts-container-scroll.md#%E7%A4%BA%E4%BE%8B2) - -## 鸿蒙的list组件怎么实现类似安卓sticky header的效果? - -适用于:OpenHarmony SDK 3.2.6.5版本,API9 Stage模型 - -可以使用ListItemGroup组件来实现。 - -参考:[ListItemGroup](../reference/arkui-ts/ts-container-listitemgroup.md) +参考:[容器嵌套滚动样例](../reference/arkui-ts/ts-container-scroll.md#示例2) ## 能否去除自定义弹窗组件的白色背景 @@ -624,6 +610,39 @@ RichText底层是web,可以参考html的语法,在div上加上的overflow: 自定义弹窗组件中参数alignment可以指定弹窗的位置。比如设置弹窗在底部:alignment : DialogAlignment.Bottom。 -参考文档:[自定义弹窗](../arkui-ts/ts-methods-custom-dialog-box.md) +参考文档:[自定义弹窗](../reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## scroller如何判断回弹动画的结束误差 + +适用于:OpenHarmony SDK 3.2.5.3版本,API8 FA模型 + +目前可以在触摸结束之后,计算同方向的变化,如果变化方向相反,说明出现回弹了,就规避不处理了。 + + +## 如何实现应用数据持久化存储 - \ No newline at end of file +通过PersistentStorage类实现管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据。 + +参考文档:[持久化数据管理](../quick-start/arkts-state-mgmt-application-level.md#persistentstorage) + +示例: + + +``` +AppStorage.Link('varA') +PersistentStorage.PersistProp("varA", "111"); +@Entry +@Componentstruct Index { + @StorageLink('varA') varA: string = '' + build() { + Column() { + Text('varA: ' + this.varA).fontSize(20) + Button('Set').width(100).height(100).onClick(() => { + this.varA += '333' + }) + } + .width('100%') + .height('100%') + } +} +``` diff --git a/zh-cn/application-dev/faqs/faqs-ui-js.md b/zh-cn/application-dev/faqs/faqs-ui-js.md index afe4133d3825eeae618ef107457a11d36c60e948..f2e540c747a7ccecfd7623469beec8a87205875a 100644 --- a/zh-cn/application-dev/faqs/faqs-ui-js.md +++ b/zh-cn/application-dev/faqs/faqs-ui-js.md @@ -93,38 +93,3 @@ export default class DateTimeUtil{ ``` -## scroller如何判断回弹动画的结束误差 - -适用于:OpenHarmony SDK 3.2.5.3版本,API8 FA模型 - -目前可以在触摸结束之后,计算同方向的变化,如果变化方向相反,说明出现回弹了,就规避不处理了。 - - -## 如何实现应用数据持久化存储 - -通过PersistentStorage类实现管理应用持久化数据,可以将特定标记的持久化数据链接到AppStorage中,并由AppStorage接口访问对应持久化数据。 - -参考文档:[持久化数据管理](../ui/ts-application-states-apis-persistentstorage.md) - -示例: - - -``` -AppStorage.Link('varA') -PersistentStorage.PersistProp("varA", "111"); -@Entry -@Componentstruct Index { - @StorageLink('varA') varA: string = '' - build() { - Column() { - Text('varA: ' + this.varA).fontSize(20) - Button('Set').width(100).height(100).onClick(() => { - this.varA += '333' - }) - } - .width('100%') - .height('100%') - } -} -``` - \ No newline at end of file diff --git a/zh-cn/application-dev/faqs/faqs-web-arkts.md b/zh-cn/application-dev/faqs/faqs-web-arkts.md index 78a123e45d698948dfca66a0044123c3217a5721..c423c07b5eb713b3455d90b29f5d5ae59633525f 100644 --- a/zh-cn/application-dev/faqs/faqs-web-arkts.md +++ b/zh-cn/application-dev/faqs/faqs-web-arkts.md @@ -78,5 +78,3 @@ onAppear方法只是定位完Canvas的位置,onReady方法才是测量完成 4. 使用应用侧的端口0给HTML侧消息端口1发送消息。 使用参考:[Web组件](../reference/arkui-ts/ts-basic-components-web.md#postmessage9) - - \ No newline at end of file diff --git a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md index 4265b41dd33be1e9155b605f38ad76a3dfc17970..75dd58ee4dd5edfe5da10b99f274c24f0bd8832c 100644 --- a/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md +++ b/zh-cn/application-dev/file-management/medialibrary-album-guidelines.md @@ -12,9 +12,9 @@ mediaLibrary提供相册相关的接口,供开发者创建、删除相册, 获取相册中的图片、视频有两种方式: -一是通过[MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1)指定相册以获取媒体资源,参考[获取指定相册的媒体资源](medialibrary-resource-guidelines#指定相册); +一是通过[MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1)指定相册以获取媒体资源,参考[获取指定相册的媒体资源](medialibrary-resource-guidelines.md#指定相册); -二是通过[Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3)使用相册Album实例获取媒体资源,参考[获取相册中的图片或视频](medialibrary-resource-guidelines#获取相册中的图片或视频)。 +二是通过[Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3)使用相册Album实例获取媒体资源,参考[获取相册中的图片或视频](medialibrary-resource-guidelines.md#获取相册中的图片或视频)。 ## 创建相册 diff --git a/zh-cn/application-dev/internationalization/intl-guidelines.md b/zh-cn/application-dev/internationalization/intl-guidelines.md index 585764dac20d89d1e7d5691bfa0a0e240c945f57..f1062d33423467bebafb95bfb218d21135d8e17d 100644 --- a/zh-cn/application-dev/internationalization/intl-guidelines.md +++ b/zh-cn/application-dev/internationalization/intl-guidelines.md @@ -41,7 +41,7 @@ ```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); ``` @@ -324,4 +324,4 @@ -[`International`:国际化(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) --[`International`:国际化(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) \ No newline at end of file +-[`International`:国际化(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266934142.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266934142.png index 9d0e3aefa778fef8bb9237aeea3ecb3ef4bba01a..5c0064c082c774564b2f016810b73cba3bc4de31 100644 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266934142.png and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001266934142.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001267573986.png b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001267573986.png index 1f8cfba17f6a99750d26bc8a4446fb6a1681c4e7..f07433811690c6949a3310d1c0cea6f0b58d8e30 100644 Binary files a/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001267573986.png and b/zh-cn/application-dev/key-features/multi-device-app-dev/figures/zh-cn_image_0000001267573986.png differ diff --git a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md index d7416c1fb2ed844a5887f2efa642a65cbc549639..ec3fd3dbca88638bddc82cddfdacf92fa2348f78 100644 --- a/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md +++ b/zh-cn/application-dev/key-features/multi-device-app-dev/start-with-a-example.md @@ -50,7 +50,7 @@ 如此,既在各设备上体现了UX的一致性,也在各设备上体现了UX的差异性,从而既可以保障各设备上应用界面的体验,也可以最大程度复用界面代码。 -在本文[应用UX设计章节](ux-design.md)中,将详细介绍应用的UX设计规则。 +在本文[应用UX设计章节](design-principles.md)中,将详细介绍应用的UX设计规则。 ## 工程管理及调试 @@ -271,3 +271,5 @@ struct Home { - 在使用特定系统能力前,通过canIUse接口判断系统能力是否存在,进而执行不同的逻辑。 在本文的[功能开发的一多能力介绍](development-intro.md)章节中,将详细展开介绍。 + + \ No newline at end of file diff --git a/zh-cn/application-dev/media/Readme-CN.md b/zh-cn/application-dev/media/Readme-CN.md index b8d00b5eb8a45c2e24d21a4e0fc3d5c26c5baf7d..dbbe0823c4f646dd8db29fee4c85f320e9a50cd1 100755 --- a/zh-cn/application-dev/media/Readme-CN.md +++ b/zh-cn/application-dev/media/Readme-CN.md @@ -10,11 +10,17 @@ - [OpenSL ES播放开发指导](opensles-playback.md) - [OpenSL ES录音开发指导](opensles-capture.md) - [音频焦点模式开发指导](audio-interruptmode.md) + - [音量管理开发指导](audio-volume-manager.md) + - [路由、设备管理开发指导](audio-routing-manager.md) - 视频 - [视频播放开发指导](video-playback.md) - [视频录制开发指导](video-recorder.md) +- 媒体会话 + - [AVSession开发概述](avsession-overview.md) + - [AVSession开发指导](avsession-guidelines.md) + - 图片 - [图片开发指导](image.md) diff --git a/zh-cn/application-dev/media/audio-capturer.md b/zh-cn/application-dev/media/audio-capturer.md index 60318f711977e7f7001304c74166dd29222ba7e5..577d93292181bcd30a2a0c964c8bcb566d69fe26 100644 --- a/zh-cn/application-dev/media/audio-capturer.md +++ b/zh-cn/application-dev/media/audio-capturer.md @@ -32,86 +32,70 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 在audioCapturerOptions中设置音频采集器的相关参数。该实例可用于音频采集、控制和获取采集状态,以及注册通知回调。 ```js - var audioStreamInfo = { + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW } - var audioCapturerInfo = { + let audioCapturerInfo = { source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 + capturerFlags: 0 // 0是音频采集器的扩展标志位,默认为0 } - var audioCapturerOptions = { + let audioCapturerOptions = { streamInfo: audioStreamInfo, capturerInfo: audioCapturerInfo } let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; + console.log('AudioRecLog: Create audio capturer success.'); ``` -2. (可选)使用on('stateChange')订阅音频采集器状态更改。 - 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 - - ```js - audioCapturer.on('stateChange',(state) => { - console.info('AudioCapturerLog: Changed State to : ' + state) - switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } - }); - ``` - -3. 调用start()方法来启动/恢复采集任务。 +2. 调用start()方法来启动/恢复采集任务。 启动完成后,采集器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 ```js - await audioCapturer.start(); - if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { - console.info('AudioRecLog: Capturer started'); - } else { - console.info('AudioRecLog: Capturer start failed'); - } - ``` - -4. 使用getBufferSize()方法获取要读取的最小缓冲区大小。 + import audio from '@ohos.multimedia.audio'; + + async function startCapturer() { + let state = audioCapturer.state; + // Capturer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. + if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || + state != audio.AudioState.STATE_STOPPED) { + console.info('Capturer is not in a correct state to start'); + return; + } + await audioCapturer.start(); - ```js - var bufferSize = await audioCapturer.getBufferSize(); - console.info('AudioRecLog: buffer size: ' + bufferSize); + let state = audioCapturer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('AudioRecLog: Capturer started'); + } else { + console.error('AudioRecLog: Capturer start failed'); + } + } ``` -5. 读取采集器的音频数据并将其转换为字节流。重复调用read()方法读取数据,直到应用准备停止采集。 +3. 读取采集器的音频数据并将其转换为字节流。重复调用read()方法读取数据,直到应用准备停止采集。 参考以下示例,将采集到的数据写入文件。 ```js import fileio from '@ohos.fileio'; + + let state = audioCapturer.state; + // 只有状态为STATE_RUNNING的时候才可以read. + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Capturer is not in a correct state to read'); + return; + } - const path = '/data/data/.pulse_dir/capture_js.wav'; + const path = '/data/data/.pulse_dir/capture_js.wav'; // 采集到的音频文件存储路径 let fd = fileio.openSync(path, 0o102, 0o777); if (fd !== null) { console.info('AudioRecLog: file fd created'); @@ -126,38 +110,140 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 console.info('AudioRecLog: file fd opened in append mode'); } - var numBuffersToCapture = 150; + let numBuffersToCapture = 150; // 循环写入150次 while (numBuffersToCapture) { - var buffer = await audioCapturer.read(bufferSize, true); + let buffer = await audioCapturer.read(bufferSize, true); if (typeof(buffer) == undefined) { - console.info('read buffer failed'); + console.info('AudioRecLog: read buffer failed'); } else { - var number = fileio.writeSync(fd, buffer); - console.info('AudioRecLog: data written: ' + number); + let number = fileio.writeSync(fd, buffer); + console.info(`AudioRecLog: data written: ${number}`); } numBuffersToCapture--; } ``` -6. 采集完成后,调用stop方法,停止录制。 +4. 采集完成后,调用stop方法,停止录制。 ```js - await audioCapturer.stop(); - if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { - console.info('AudioRecLog: Capturer stopped'); - } else { - console.info('AudioRecLog: Capturer stop failed'); - } + async function StopCapturer() { + let state = audioCapturer.state; + // 只有采集器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('AudioRecLog: Capturer is not running or paused'); + return; + } + + await audioCapturer.stop(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('AudioRecLog: Capturer stopped'); + } else { + console.error('AudioRecLog: Capturer stop failed'); + } + } ``` -7. 任务结束,调用release()方法释放相关资源。 +5. 任务结束,调用release()方法释放相关资源。 ```js - await audioCapturer.release(); - if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { - console.info('AudioRecLog: Capturer released'); - } else { - console.info('AudioRecLog: Capturer release failed'); - } - ``` \ No newline at end of file + async function releaseCapturer() { + let state = audioCapturer.state; + // 采集器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('AudioRecLog: Capturer already released'); + return; + } + + await audioCapturer.release(); + + state = audioCapturer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('AudioRecLog: Capturer released'); + } else { + console.info('AudioRecLog: Capturer release failed'); + } + } + ``` + +6. (可选)获取采集器相关信息 + + 通过以下代码,可以获取采集器的相关信息。 + + ```js + // 获取当前采集器状态 + let state = audioCapturer.state; + + // 获取采集器信息 + let audioCapturerInfo : audio.AuduioCapturerInfo = await audioCapturer.getCapturerInfo(); + + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await audioCapturer.getStreamInfo(); + + // 获取音频流ID + let audioStreamId : number = await audioCapturer.getAudioStreamId(); + + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await audioCapturer.getAudioTime(); + + // 获取合理的最小缓冲区大小 + let bufferSize : number = await audioCapturer.getBuffersize(); + ``` + +7. (可选)使用on('markReach')方法订阅采集器标记到达事件,使用off('markReach')取消订阅事件。 + + 注册markReach监听后,当采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioCapturer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + ``` + +8. (可选)使用on('periodReach')方法订阅采集器区间标记到达事件,使用off('periodReach')取消订阅事件。 + + 注册periodReach监听后,**每当**采集器采集的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioCapturer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the Capturer reached frame: ${reachNumber}`); + }); + + audioCapturer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + ``` + +9. 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件,当采集器状态更新时,会受到一个包含有事件类型的回调。 + + ```js + audioCapturer.on('stateChange', (state) => { + console.info(`AudioCapturerLog: Changed State to : ${state}`) + switch (state) { + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } + }); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md index 98d06c159904f39eb2293ca27d9db653c48b77a2..1bb5841f1cfd21accee96c6f3c7690ec9817385d 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -26,6 +26,10 @@ 详细API含义可参考:[媒体服务API文档AudioPlayer](../reference/apis/js-apis-media.md#audioplayer) +> **说明:** +> +> path路径在FA模型和Stage模型下的获取方式不同,示例代码中仅给出pathDir示例,具体的path路径请开发者根据实际情况获取。获取方式请参考[应用沙箱路径使用说明](../reference/apis/js-apis-fileio.md#使用说明)。 + ### 全流程场景 音频播放的全流程场景包含:创建实例,设置uri,播放音频,跳转播放位置,设置音量,暂停播放,获取轨道信息,停止播放,重置,释放资源等流程。 @@ -35,7 +39,6 @@ AudioPlayer支持的src媒体源输入类型可参考:[src属性说明](../ref ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -import featureAbility from '@ohos.ability.featureAbility' // 打印码流轨道信息 function printfDescription(obj) { @@ -106,14 +109,9 @@ async function audioPlayerDemo() { setCallBack(audioPlayer); // 设置事件回调 // 2. 用户选择音频,设置uri let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 - let path = '' - var context = featureAbility.getContext(); - await context.getFilesDir().then((fileDir) => { - console.info("case file dir is" + JSON.stringify(fileDir)); - path = fileDir + '/01.mp3'; - console.info("case path is" + path); - }); + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -131,7 +129,6 @@ async function audioPlayerDemo() { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -import featureAbility from '@ohos.ability.featureAbility' export class AudioDemo { // 设置播放器回调函数 @@ -154,14 +151,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 - let path = '' - var context = featureAbility.getContext(); - await context.getFilesDir().then((fileDir) => { - console.info("case file dir is" + JSON.stringify(fileDir)); - path = fileDir + '/01.mp3'; - console.info("case path is" + path); - }); + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -180,7 +172,6 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -import featureAbility from '@ohos.ability.featureAbility' export class AudioDemo { // 设置播放器回调函数 @@ -208,14 +199,9 @@ export class AudioDemo { async nextMusic(audioPlayer) { this.isNextMusic = true; let nextFdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 // path路径的码流可通过"hdc file send D:\xxx\02.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 - let nextpath = '' - var context = featureAbility.getContext(); - await context.getFilesDir().then((fileDir) => { - console.info("case file dir is" + JSON.stringify(fileDir)); - nextpath = fileDir + '/02.mp3'; - console.info("case path is" + nextpath); - }); + let nextpath = pathDir + '/02.mp3' await fileIO.open(nextpath).then((fdNumber) => { nextFdPath = nextFdPath + '' + fdNumber; console.info('open fd success fd is' + nextFdPath); @@ -231,14 +217,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 - let path = '' - var context = featureAbility.getContext(); - await context.getFilesDir().then((fileDir) => { - console.info("case file dir is" + JSON.stringify(fileDir)); - path = fileDir + '/01.mp3'; - console.info("case path is" + path); - }); + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); @@ -257,7 +238,6 @@ export class AudioDemo { ```js import media from '@ohos.multimedia.media' import fileIO from '@ohos.fileio' -import featureAbility from '@ohos.ability.featureAbility' export class AudioDemo { // 设置播放器回调函数 @@ -276,14 +256,9 @@ export class AudioDemo { let audioPlayer = media.createAudioPlayer(); // 创建一个音频播放实例 this.setCallBack(audioPlayer); // 设置事件回调 let fdPath = 'fd://' + let pathDir = "/data/storage/el2/base/haps/entry/files" // pathDir在FA模型和Stage模型的获取方式不同,请参考开发步骤首行的说明,根据实际情况自行获取。 // path路径的码流可通过"hdc file send D:\xxx\01.mp3 /data/app/el2/100/base/ohos.acts.multimedia.audio.audioplayer/haps/entry/files" 命令,将其推送到设备上 - let path = '' - var context = featureAbility.getContext(); - await context.getFilesDir().then((fileDir) => { - console.info("case file dir is" + JSON.stringify(fileDir)); - path = fileDir + '/01.mp3'; - console.info("case path is" + path); - }); + let path = pathDir + '/01.mp3' await fileIO.open(path).then((fdNumber) => { fdPath = fdPath + '' + fdNumber; console.info('open fd success fd is' + fdPath); diff --git a/zh-cn/application-dev/media/audio-renderer.md b/zh-cn/application-dev/media/audio-renderer.md index 1e573b9a1edf423c9bb57fac7b337625798d95c8..7be8630c4d1d7cea8a950a0174f03760ad2f927d 100644 --- a/zh-cn/application-dev/media/audio-renderer.md +++ b/zh-cn/application-dev/media/audio-renderer.md @@ -8,6 +8,7 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 - **音频中断**:当优先级较高的音频流需要播放时,AudioRenderer会中断优先级较低的流。例如,当用户在收听音乐时有来电,则优先级较低音乐播放将被暂停。 - **状态检查**:在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioRenderer的状态变更。因为针对AudioRenderer的某些操作,仅在音频播放器在固定状态时才能执行。如果应用在音频播放器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 - **异步操作**:为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8)。 +- **焦点模式**:OpenHarmony中有两种焦点模式:**共享焦点模式**和**独立焦点模式**。其中,共享焦点模式是指,同一个应用创建的所有AudioRenderer对象共享一个焦点对象,应用内部无焦点转移,因此无法触发回调通知;独立焦点模式与之相反,即同一个应用创建的每个AudioRenderer对象都拥有独立的焦点对象,会发生焦点抢占,当应用内部发生焦点抢占,将会发生焦点转移,原本拥有焦点的AudioRenderer对象会获取到相关的回调通知。需要注意的是,默认情况下,应用创建的都是共享焦点,开发者可以调用setInterruptMode()来设置创建的焦点模式,完整示例请参考开发指导14。 ## 运作机制 @@ -25,76 +26,281 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 ## 开发指导 +详细API含义可参考:[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8) + 1. 使用createAudioRenderer()创建一个AudioRenderer实例。 - 在audioCapturerOptions中设置相关参数。该实例可用于音频渲染、控制和获取采集状态,以及注册通知回调。 + 在audioRendererOptions中设置相关参数。该实例可用于音频渲染、控制和获取渲染状态,以及注册通知回调。 ```js - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } + import audio from '@ohos.multimedia.audio'; + + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + console.log("Create audio renderer success."); + ``` + +2. 调用start()方法来启动/恢复播放任务。 + + ```js + async function startRenderer() { + let state = audioRenderer.state; + // Renderer start时的状态应该是STATE_PREPARED、STATE_PAUSED和STATE_STOPPED之一. + if (state != audio.AudioState.STATE_PREPARED && state != audio.AudioState.STATE_PAUSED && + state != audio.AudioState.STATE_STOPPED) { + console.info('Renderer is not in a correct state to start'); + return; + } + + await audioRenderer.start(); - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + } } + ``` + 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 + + +3. 调用write()方法向缓冲区写入数据。 + + 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo + ```js + import fileio from '@ohos.fileio'; + import audio from '@ohos.multimedia.audio'; + + async function writeBuffer(buf) { + // 写入数据时,渲染器的状态必须为STATE_RUNNING + if (audioRenderer.state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + return; + } + let writtenbytes = await audioRenderer.write(buf); + console.info(`Actual written bytes: ${writtenbytes} `); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } } + + // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + const bufferSize = await audioRenderer.getBufferSize(); + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path = dir + '/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/file_example_WAV_2MG.wav + console.info(`file path: ${ path}`); + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = fileio.statSync(path).size; // 音乐文件大小 + let discardHeader = new ArrayBuffer(bufferSize); + ss.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + let id = setInterval(() => { + if (audioRenderer.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + if (audioRenderer.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize) { // 如果音频文件已经被读取完,停止渲染 + ss.closeSync(); + await audioRenderer.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 + ``` + +4. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 + + ```js + async function pauseRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能暂停 + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING或STATE_PAUSED的时候才可以停止 + if (state != audio.AudioState.STATE_RUNNING && state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } + } + ``` + +5. (可选)调用drain()方法清空缓冲区。 + + ```js + async function drainRenderer() { + let state = audioRenderer.state; + // 只有渲染器状态为STATE_RUNNING的时候才能使用drain() + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.drain(); + + state = audioRenderer.state; + } + ``` + +6. 任务完成,调用release()方法释放相关资源。 + + AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + ```js + async function releaseRenderer() { + let state = audioRenderer.state; + // 渲染器状态不是STATE_RELEASED或STATE_NEW状态,才能release + if (state == audio.AudioState.STATE_RELEASED || state == audio.AudioState.STATE_NEW) { + console.info('Renderer already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + } + ``` + +7. (可选)获取渲染器相关信息 + + 通过以下代码,可以获取渲染器的相关信息。 + + ```js + // 获取当前渲染器状态 + let state = audioRenderer.state; + + // 获取渲染器信息 + let audioRendererInfo : audio.AudioRendererInfo = await audioRenderer.getRendererInfo(); + + // 获取音频流信息 + let audioStreamInfo : audio.AudioStreamInfo = await audioRenderer.getStreamInfo(); + + // 获取音频流ID + let audioStreamId : number = await audioRenderer.getAudioStreamId(); + + // 获取纳秒形式的Unix时间戳 + let audioTime : number = await audioRenderer.getAudioTime(); + + // 获取合理的最小缓冲区大小 + let bufferSize : number = await audioRenderer.getBuffersize(); + + // 获取渲染速率 + let renderRate : audio.AudioRendererRate = await audioRenderer.getRenderRate(); + ``` + +8. (可选)设置渲染器相关信息 + + 通过以下代码,可以设置渲染器的相关信息。 + + ```js + // 设置渲染速率为正常速度 + let renderRate : audio.AudioRendererRate = audio.AudioRendererRate.RENDER_RATE_NORMAL; + await audioRenderer.setRenderRate(renderRate); + + // 设置渲染器音频中断模式为SHARE_MODE + let interruptMode : audio.InterruptMode = audio.InterruptMode.SHARE_MODE; + await audioRenderer.setInterruptMode(interruptMode); + + // 设置一个流的音量为10 + let volume : number = 10; + await audioRenderer.setVolume(volume); ``` -2. 使用on('interrupt')方法订阅音频中断事件。 +9. (可选)使用on('audioInterrupt')方法订阅渲染器音频中断事件,使用off('audioInterrupt')取消订阅事件。 当优先级更高或相等的Stream-B请求激活并使用输出设备时,Stream-A被中断。 在某些情况下,框架会采取暂停播放、降低音量等强制操作,并通过InterruptEvent通知应用。在其他情况下,应用可以自行对InterruptEvent做出响应。 在音频中断的情况下,应用可能会碰到音频数据写入失败的问题。所以建议不感知、不处理中断的应用在写入音频数据前,使用audioRenderer.state检查播放器状态。而订阅音频中断事件,可以获取到更多详细信息,具体可参考[InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9)。 + + 需要说明的是,本模块的订阅音频中断事件与[AudioManager](../reference/apis/js-apis-audio.md#audiomanager)模块中的on('interrupt')稍有不同。自api9以来,on('interrupt')和off('interrupt')均被废弃。在AudioRenderer模块,当开发者需要监听焦点变化事件时,只需要调用on('audioInterrupt')函数,当应用内部的AudioRenderer对象在start\stop\pause等动作发生时,会主动请求焦点,从而发生焦点转移,相关的AudioRenderer对象即可获取到对应的回调信息。但对除AudioRenderer的其他对象,例如FM、语音唤醒等,应用不会创建对象,此时可调用AudioManager中的on('interrupt')获取焦点变化通知。 ```js - audioRenderer.on('interrupt', (interruptEvent) => { + audioRenderer.on('audioInterrupt', (interruptEvent) => { console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); + console.info(`InterruptType: ${interruptEvent.eventType}`); + console.info(`InterruptForceType: ${interruptEvent.forceType}`); + console.info(`AInterruptHint: ${interruptEvent.hintType}`); if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. + // 音频框架发起的强制暂停操作,为防止数据丢失,此时应该停止数据的写操作 case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. + // 音频框架发起的强制停止操作,为防止数据丢失,此时应该停止数据的写操作 case audio.InterruptHint.INTERRUPT_HINT_STOP: isPlay = false; break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. + // 音频框架发起的强制降低音量操作 case audio.InterruptHint.INTERRUPT_HINT_DUCK: break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. + // 音频框架发起的恢复音量操作 case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: break; } } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. + // 提醒App开始渲染 case audio.InterruptHint.INTERRUPT_HINT_RESUME: startRenderer(); break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. + // 提醒App音频流被中断,由App自主决定是否继续(此处选择暂停) case audio.InterruptHint.INTERRUPT_HINT_PAUSE: isPlay = false; pauseRenderer(); @@ -102,137 +308,236 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 } } }); - ``` - -3. 调用start()方法来启动/恢复播放任务。 - - 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 - - ```js - async function startRenderer() { - var state = audioRenderer.state; - // state should be prepared, paused or stopped. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Renderer is not in a correct state to start'); - return; - } - - await audioRenderer.start(); - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('Renderer started'); - } else { - console.error('Renderer start failed'); - } - } + audioRenderer.off('audioInterrupt'); // 取消音频中断事件的订阅,后续将无法监听到音频中断事件 ``` -4. 调用write()方法向缓冲区写入数据。 +10. (可选)使用on('markReach')方法订阅渲染器标记到达事件,使用off('markReach')取消订阅事件。 - 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 + 注册markReach监听后,当渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 + + ```js + audioRenderer.on('markReach', (reachNumber) => { + console.info('Mark reach event Received'); + console.info(`The renderer reached frame: ${reachNumber}`); + }); - ```js - async function writeBuffer(buf) { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - isPlay = false; - return; - } - let writtenbytes = await audioRenderer.write(buf); + audioRenderer.off('markReach'); // 取消markReach事件的订阅,后续将无法监听到“标记到达”事件 + ``` - console.info('Actual written bytes: ' + writtenbytes); - if (writtenbytes < 0) { - console.error('Write buffer failed. check the state of renderer'); - } - } +11. (可选)使用on('periodReach')方法订阅渲染器区间标记到达事件,使用off('periodReach')取消订阅事件。 + + 注册periodReach监听后,**每当**渲染器渲染的帧数到达设定值时,会触发回调并返回设定的值。 - // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. - const bufferSize = await audioRenderer.getBufferSize(); - const path = '/data/file_example_WAV_2MG.wav'; - let ss = fileio.createStreamSync(path, 'r'); - const totalSize = 2146166; // file_example_WAV_2MG.wav - let rlen = 0; - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - rlen += 44; + ```js + audioRenderer.on('periodReach', (reachNumber) => { + console.info('Period reach event Received'); + console.info(`In this period, the renderer reached frame: ${reachNumber} `); + }); - var id = setInterval(() => { - if (isPlay || isRelease) { - if (rlen >= totalSize || isRelease) { - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - let buf = new ArrayBuffer(bufferSize); - rlen += ss.readSync(buf); - console.info('Total bytes read from file: ' + rlen); - writeBuffer(buf); - } else { - console.info('check after next interval'); - } - } , 30); // interval to be set based on audio file format - ``` + audioRenderer.off('periodReach'); // 取消periodReach事件的订阅,后续将无法监听到“区间标记到达”事件 + ``` -5. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 +12. (可选)使用on('stateChange')方法订阅渲染器音频状态变化事件。 - ```js - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } + 注册stateChange监听后,当渲染器的状态发生改变时,会触发回调并返回当前渲染器的状态。 + + ```js + audioRenderer.on('stateChange', (audioState) => { + console.info('State change event Received'); + console.info(`Current renderer state is: ${audioState}`); + }); + ``` - await audioRenderer.pause(); +13. (可选)对on()方法的异常处理。 - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } + 在使用on()方法时,如果传入的字符串错误或传入的参数类型错误,程序会抛出异常,需要用try catch来捕获。 + + ```js + try { + audioRenderer.on('invalidInput', () => { // 字符串不匹配 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出401异常 + } + try { + audioRenderer.on(1, () => { // 入参类型错误 + }) + } catch (err) { + console.info(`Call on function error, ${err}`); // 程序抛出6800101异常 + } + ``` + +14. (可选)on('audioInterrupt')方法完整示例。 + 同一个应用中的AudioRender1和AudioRender2在创建时均设置了焦点模式为独立,并且调用on('audioInterrupt')监听焦点变化。刚开始AudioRender1拥有焦点,当AudioRender2获取到焦点时,audioRenderer1将收到焦点转移的通知,打印相关日志。如果AudioRender1和AudioRender2不将焦点模式设置为独立,则监听处理中的日志在应用运行过程中永远不会被打印。 + ```js + async runningAudioRender1(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; + //1.1 创建对象 + audioRenderer1 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 1 success."); + + //1.2 设置焦点模式为独立模式 :1 + audioRenderer1.setInterruptMode(1).then( data => { + console.info('audioRenderer1 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer1 setInterruptMode Fail: ${err}`); + }); + + //1.3 设置监听 + audioRenderer1.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer1 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + //1.4 启动渲染 + await audioRenderer1.start(); + console.info('startAudioRender1 success'); + + //1.5 获取缓存区大小,此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + const bufferSize = await audioRenderer1.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + //1.6 获取原始音频数据文件 + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path1 = dir + '/music001_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music001_48000_32_1.wav + console.info(`audioRender1 file path: ${ path1}`); + let ss1 = await fileio.createStream(path1,'r'); + const totalSize1 = fileio.statSync(path1).size; // 音乐文件大小 + console.info(`totalSize1 -------: ${totalSize1}`); + let discardHeader = new ArrayBuffer(bufferSize); + ss1.readSync(discardHeader); + let rlen = 0; + rlen += bufferSize; + + //2.7 通过audioRender对缓存区的原始音频数据进行渲染 + let id = setInterval(async () => { + if (audioRenderer1.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss1.closeSync(); + audioRenderer1.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize1) { // 如果音频文件已经被读取完,停止渲染 + ss1.closeSync(); + await audioRenderer1.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss1.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer1); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 } - await audioRenderer.stop(); + async runningAudioRender2(){ + let audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + let audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_MUSIC, + usage: audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags: 0 // 0是音频渲染器的扩展标志位,默认为0 + } + let audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); + //2.1 创建对象 + audioRenderer2 = await audio.createAudioRenderer(audioRendererOptions); + console.info("Create audio renderer 2 success."); + + //2.2 设置焦点模式为独立模式 :1 + audioRenderer2.setInterruptMode(1).then( data => { + console.info('audioRenderer2 setInterruptMode Success!'); + }).catch((err) => { + console.error(`audioRenderer2 setInterruptMode Fail: ${err}`); + }); + + //2.3 设置监听 + audioRenderer2.on('audioInterrupt', async(interruptEvent) => { + console.info(`audioRenderer2 on audioInterrupt : ${JSON.stringify(interruptEvent)}`) + }); + + //2.4 启动渲染 + await audioRenderer2.start(); + console.info('startAudioRender2 success'); + + //2.5 获取缓存区大小 + const bufferSize = await audioRenderer2.getBufferSize(); + console.info(`audio bufferSize: ${bufferSize}`); + + //2.6 读取原始音频数据文件 + let dir = globalThis.fileDir; //不可直接访问,没权限,切记!!!一定要使用沙箱路径 + const path2 = dir + '/music002_48000_32_1.wav'; // 需要渲染的音乐文件 实际路径为:/data/storage/el2/base/haps/entry/files/music002_48000_32_1.wav + console.error(`audioRender1 file path: ${ path2}`); + let ss2 = await fileio.createStream(path2,'r'); + const totalSize2 = fileio.statSync(path2).size; // 音乐文件大小 + console.error(`totalSize2 -------: ${totalSize2}`); + let discardHeader2 = new ArrayBuffer(bufferSize); + ss2.readSync(discardHeader2); + let rlen = 0; + rlen += bufferSize; + + //2.7 通过audioRender对缓存区的原始音频数据进行渲染 + let id = setInterval(async () => { + if (audioRenderer2.state == audio.AudioState.STATE_RELEASED) { // 如果渲染器状态为release,停止渲染 + ss2.closeSync(); + that.audioRenderer2.stop(); + clearInterval(id); + } + if (audioRenderer1.state == audio.AudioState.STATE_RUNNING) { + if (rlen >= totalSize2) { // 如果音频文件已经被读取完,停止渲染 + ss2.closeSync(); + await audioRenderer2.stop(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss2.readSync(buf); + console.info(`Total bytes read from file: ${rlen}`); + await writeBuffer(buf, that.audioRenderer2); + } else { + console.info('check after next interval'); + } + }, 30); // 定时器区间根据音频格式设置,单位为毫秒 } - } - ``` - -6. 任务完成,调用release()方法释放相关资源。 - AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 - - ```js - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; + async writeBuffer(buf, audioRender) { + let writtenbytes; + await audioRender.write(buf).then((value) => { + writtenbytes = value; + console.info(`Actual written bytes: ${writtenbytes} `); + }); + if (typeof(writtenbytes) != 'number' || writtenbytes < 0) { + console.error('get Write buffer failed. check the state of renderer'); + } } - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); + //综合调用入口 + async test(){ + await runningAudioRender1(); + await runningAudioRender2(); } - } - ``` \ No newline at end of file + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-routing-manager.md b/zh-cn/application-dev/media/audio-routing-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..4d5f07047ccd27952945dbc61bc7a37fcb8a0bbe --- /dev/null +++ b/zh-cn/application-dev/media/audio-routing-manager.md @@ -0,0 +1,112 @@ +# 路由、设备管理开发指导 + +## 简介 + +AudioRoutingManager提供了音频路由、设备管理的方法。开发者可以通过本指导了解应用如何通过AudioRoutingManager获取当前工作的输入、输出音频设备,监听音频设备的连接状态变化,激活通信设备等。 + +## 运作机制 + +该模块提供了路由、设备管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_routing_manager](figures/zh-ch_image_audio_routing_manager.png) + +**说明:** AudioRoutingManager主要接口有:获取设备列表信息、监听与取消监听设备连接状态、激活通信设备、查询通信设备激活状态。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + +## 开发指导 + +详细API含义可参考:[音频路由、设备管理API文档AudioRoutingManager](../reference/apis/js-apis-audio.md#audioroutingmanager9) + +1. 创建AudioRoutingManager实例。 + + 在使用AudioRoutingManager的API前,需要使用getRoutingManager创建一个AudioRoutingManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + + ``` + +2. (可选)获取设备列表信息、监听设备链接状态变化。 + + 如果开发者需要获取设备列表信息(输入、输出、分布式输入、分布式输出等),或者监听音频设备的链接状态变化时,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //获取全部音频设备信息(开发者可以根据自身需要填入适当的DeviceFlag) + async getDevices() { + await loadAudioRoutingManager(); + await audioRoutingManager.getDevices(audio.DeviceFlag.ALL_DEVICES_FLAG).then((data) => { + console.info(`getDevices success and data is: ${JSON.stringify(data)}.`); + }); + } + //监听音频设备状态变化 + async onDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.on('deviceChange', audio.DeviceFlag.ALL_DEVICES_FLAG, (deviceChanged) => { + console.info('on device change type : ' + deviceChanged.type); + console.info('on device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('on device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //取消监听音频设备状态变化 + async offDeviceChange() { + await loadAudioRoutingManager(); + await audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('off device change type : ' + deviceChanged.type); + console.info('off device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('off device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); + }); + } + //综合调用:先查询所有设备,设置监听,然后开发者手动变更设备连接(例如有线耳机),再次查询所有设备,最后取消设备状态变化的监听。 + async test(){ + await getDevices(); + await onDeviceChange()(); + //开发者手动断开/连接设备 + await getDevices(); + await offDeviceChange(); + } + ``` + +3. (可选)设置通信设备激活并查询激活状态。 + + ```js + import audio from '@ohos.multimedia.audio'; + //创建AudioRoutingManager实例 + async loadAudioRoutingManager() { + var audioRoutingManager = await audio.getAudioManager().getRoutingManager(); + console.info('audioRoutingManager------create-------success.'); + } + //设置通信设备激活状态 + async setCommunicationDevice() { + await loadAudioRoutingManager(); + await audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('setCommunicationDevice true is success.'); + }); + } + //查询通信设备激活状态 + async isCommunicationDeviceActive() { + await loadAudioRoutingManager(); + await audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`CommunicationDevice state is: ${value}.`); + }); + } + //综合调用:先设置设备激活,然后查询设备状态。 + async test(){ + await setCommunicationDevice(); + await isCommunicationDeviceActive(); + } + ``` + diff --git a/zh-cn/application-dev/media/audio-volume-manager.md b/zh-cn/application-dev/media/audio-volume-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d26175b8822b49aafd9a5e7a0e26b009a1e8d451 --- /dev/null +++ b/zh-cn/application-dev/media/audio-volume-manager.md @@ -0,0 +1,127 @@ +# 音量管理开发指导 + +## 简介 + +AudioVolumeManager提供了音量管理的方法。开发者可以通过本指导了解应用如何通过AudioVolumeManager获取指定流音量信息、监听铃声模式变化、设置麦克风静音等。 + +## 运作机制 + +该模块提供了音量管理模块常用接口 + +**图1** 音量管理常用接口 + +![zh-ch_image_audio_volume_manager](figures/zh-ch_image_audio_volume_manager.png) + +**说明:** AudioVolumeManager包含音量变化监听处理和音频音量组管理相关(AudioVolumeGroupManager),开发者调用AudioVolumeGroupManager的相关方法,需要先调用getVolumeGroupManager方法创建AudioVolumeGroupManager实例,从而调用对应的接口实现相应的功能,主要接口有:获取指定流的音量、设置麦克风静音、监听麦克风状态变化等。更多介绍请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + +## 约束与限制 + +开发者在进行麦克风管理开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),如果要设置麦克风状态,则需要配置音频管理配置权限(ohos.permission.MANAGE_AUDIO_CONFIG),需注意该权限为系统级别权限。权限配置相关内容可参考:[访问控制授权申请指导](../security/accesstoken-guidelines.md) + +## 开发指导 + +详细API含义可参考:[音量管理API文档AudioVolumeManager](../reference/apis/js-apis-audio.md#audiovolumemanager9) + +1. 创建AudioVolumeGroupManager实例。 + + 在使用AudioVolumeGroupManager的API前,需要使用getVolumeGroupManager创建一个AudioStreamManager实例。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.error('audioVolumeGroupManager create success.'); + } + + ``` + +2. (可选)获取音量信息、铃声模式。 + + 如果开发者需要获取指定音频流的音量信息(铃声、语音电话、媒体、语音助手等),或者获取当前设备是静音、震动、响铃模式,可参考并调用以下接口。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + //获取指定流的当前音量(范围为0 ~ 15) + async getVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最小音量 + async getMinVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMinVolume success and volume is: ${value}.`); + }); + } + //获取指定流的最大音量 + async getMaxVolume() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`getMaxVolume success and volume is: ${value}.`); + }); + } + //获取当前铃声模式: 静音(0)| 震动(1) | 响铃(2) + async getRingerMode() { + await loadVolumeGroupManager(); + await audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`getRingerMode success and RingerMode is: ${value}.`); + }); + } + ``` + +3. (可选)查询、设置、监听麦克风状态。 + + 如果开发者需要获取、设置麦克风状态,或者监听麦克风状态变化等信息,可参考并调用以下接口。 + + ```js + import audio from '@ohos.multimedia.audio'; + async loadVolumeGroupManager() { + const groupid = audio.DEFAULT_VOLUME_GROUP_ID; + var audioVolumeGroupManager = await audio.getAudioManager().getVolumeManager().getVolumeGroupManager(groupid); + console.info('audioVolumeGroupManager create success.'); + } + + async on() { //监听麦克风状态变化 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); + }); + } + + async isMicrophoneMute() { //查询麦克风是否静音 + await audioVolumeGroupManager.audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`isMicrophoneMute is: ${value}.`); + }); + } + + async setMicrophoneMuteTrue() { //设置麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('setMicrophoneMute to mute.'); + }); + } + + async setMicrophoneMuteFalse() { //取消麦克风静音 + await loadVolumeGroupManager(); + await audioVolumeGroupManager.audioVolumeGroupManager.setMicrophoneMute(false).then(() => { + console.info('setMicrophoneMute to not mute.'); + }); + } + async test(){ //综合调用:先设置监听,然后查询麦克风状态,设置麦克风静音后再查询状态,最后取消麦克风静音。 + await on(); + await isMicrophoneMute(); + await setMicrophoneMuteTrue(); + await isMicrophoneMute(); + await setMicrophoneMuteFalse(); + } + ``` + diff --git a/zh-cn/application-dev/media/camera.md b/zh-cn/application-dev/media/camera.md index 617c4107faa983dc2231c80578405be95cf93e1c..12c785c1d5cd84044cc43466661e515673fcb66c 100644 --- a/zh-cn/application-dev/media/camera.md +++ b/zh-cn/application-dev/media/camera.md @@ -89,22 +89,22 @@ if (!cameraOutputCap) { console.info("outputCapability: " + JSON.stringify(cameraOutputCap)); } -let previewProfilesArray = cameraOutputCap.previewProfiles; +let previewProfilesArray = cameraOutputCap.GetPreviewProfiles(); if (!previewProfilesArray) { console.error("createOutput previewProfilesArray == null || undefined") } -let photoProfilesArray = cameraOutputCap.photoProfiles; +let photoProfilesArray = cameraOutputCap.GetPhotoProfiles(); if (!photoProfilesArray) { console.error("createOutput photoProfilesArray == null || undefined") } -let videoProfilesArray = cameraOutputCap.videoProfiles; +let videoProfilesArray = cameraOutputCap.GetVideoProfiles(); if (!videoProfilesArray) { console.error("createOutput videoProfilesArray == null || undefined") } -let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes; +let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType(); if (!metadataObjectTypesArray) { console.error("createOutput metadataObjectTypesArray == null || undefined") } @@ -115,7 +115,7 @@ if (!previewOutput) { console.error("Failed to create the PreviewOutput instance.") } -// 创建ImageReceiver对象,并设置照片参数 +// 创建ImageReceiver对象,并设置照片参数:分辨率大小是根据前面 photoProfilesArray 获取的当前设备所支持的拍照分辨率大小去设置 let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8) // 获取照片显示SurfaceId let photoSurfaceId = await imageReceiver.getReceivingSurfaceId() @@ -188,7 +188,7 @@ build() { controller: this.mXComponentController }) .onload(() => { // 设置onload回调 - // 设置Surface宽高(1920*1080) + // 设置Surface宽高(1920*1080),预览尺寸设置参考前面 previewProfilesArray 获取的当前设备所支持的预览分辨率大小去设置 this.mXComponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080}) // 获取Surface ID globalThis.surfaceId = mXComponentController.getXComponentSurfaceId() diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..710679f6cac0c30d06dffa97b0e80b3cebe80f79 Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_routing_manager.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png index 7497edd0edbdcfccbc448e9f2f48268ebb75e72e..22b7aeaa1db5b369d3daf44854d7f7f9a00f775b 100644 Binary files a/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_state_machine.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png b/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png new file mode 100644 index 0000000000000000000000000000000000000000..0d47fbfacce9c1ff48811e1cf5d764231bdb596b Binary files /dev/null and b/zh-cn/application-dev/media/figures/zh-ch_image_audio_volume_manager.png differ diff --git a/zh-cn/application-dev/media/image.md b/zh-cn/application-dev/media/image.md index 8d69c76aca22570ed3a875670be6d0c3496bfa74..e36f90f47891eed3165ef79156a622f348ef5814 100644 --- a/zh-cn/application-dev/media/image.md +++ b/zh-cn/application-dev/media/image.md @@ -96,7 +96,7 @@ pixelmap.writeBufferToPixels(writeColor).then(() => { }) // 用于获取图片信息 -pixelmap.getImageInfo( imageInfo => { +pixelmap.getImageInfo((error, imageInfo) => { if (imageInfo !== null) { console.log('Succeeded in getting imageInfo'); } @@ -171,17 +171,13 @@ catch(error => { }) // 用于获取像素每行字节数 -pixelmap.getBytesNumberPerRow( num => { - console.log('Succeeded in getting BytesNumber PerRow.'); -}) +var num = pixelmap.getBytesNumberPerRow(); // 用于获取像素总字节数 -pixelmap.getPixelBytesNumber(num => { - console.log('Succeeded in getting PixelBytesNumber.'); -}) +var pixelSize = pixelmap.getPixelBytesNumber(); // 用于获取pixelmap信息 -pixelmap.getImageInfo( imageInfo => {}) +pixelmap.getImageInfo().then( imageInfo => {}); // 用于释放pixelmap pixelmap.release(()=>{ @@ -229,7 +225,7 @@ imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.release(); // 用于获取imagesource信息 -imageSourceApi.getImageInfo(imageInfo => { +imageSourceApi.getImageInfo((err, imageInfo) => { console.log('Succeeded in getting imageInfo'); }) @@ -249,8 +245,9 @@ public async init(surfaceId: any) { var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1); // 获取Surface ID - var surfaceId = await receiver.getReceivingSurfaceId(); - + receiver.getReceivingSurfaceId((err, surfaceId) => { + console.info("receiver getReceivingSurfaceId success"); + }); // 注册Surface的监听,在surface的buffer准备好后触发 receiver.on('imageArrival', () => { // 去获取Surface中最新的buffer diff --git a/zh-cn/application-dev/napi/Readme-CN.md b/zh-cn/application-dev/napi/Readme-CN.md index 99e16d5ce95c7c565a768d8d9df737bb98300fca..e6626f0373a002a6344fe7b8c934b99d9b7209b6 100644 --- a/zh-cn/application-dev/napi/Readme-CN.md +++ b/zh-cn/application-dev/napi/Readme-CN.md @@ -5,3 +5,4 @@ - [Rawfile开发指导](rawfile-guidelines.md) - [Window开发指导](native-window-guidelines.md) - [使用MindSpore Lite引擎进行模型推理](mindspore-lite-guidelines.md) +- [Neural Network Runtime对接AI推理框架开发指导](neural-network-runtime-guidelines.md) \ No newline at end of file diff --git a/zh-cn/application-dev/napi/figures/02.png b/zh-cn/application-dev/napi/figures/02.png new file mode 100644 index 0000000000000000000000000000000000000000..1e31c1ce7f4e93ed9bd2e8acda0facce7a9a00f7 Binary files /dev/null and b/zh-cn/application-dev/napi/figures/02.png differ diff --git a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md index fa5d32573516b4da0bde2d7a931d5fac6e901792..057948c52a68b8525b0f7c815039139f31ddcb54 100644 --- a/zh-cn/application-dev/napi/mindspore-lite-guidelines.md +++ b/zh-cn/application-dev/napi/mindspore-lite-guidelines.md @@ -24,7 +24,7 @@ MindSpore Lite是一款AI引擎,它提供了面向不同硬件设备AI模型 | ------------------ | ----------------- | |OH_AI_ContextHandle OH_AI_ContextCreate()|创建一个上下文的对象。| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|设置运行时的线程数量。| -| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|设置运行时线程绑定CPU核心的策略。一般情况下CPU会按照频率分为大小核,即频率较高的为大核,频率较低的为小核。| +| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|创建一个运行时设备信息对象。| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|释放上下文对象。| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|设置是否开启Float16推理模式,仅CPU/GPU设备可用。| diff --git a/zh-cn/application-dev/napi/napi-guidelines.md b/zh-cn/application-dev/napi/napi-guidelines.md index 84c0b827089cf8001181fa2b45b6c2b820431d57..9ff575a8e0755a2546cc51b78d48df76b9746a85 100644 --- a/zh-cn/application-dev/napi/napi-guidelines.md +++ b/zh-cn/application-dev/napi/napi-guidelines.md @@ -642,7 +642,7 @@ export default { } ``` ## 相关实例 + 针对Native API的开发,有以下相关实例可供参考: -- [`NativeAPI`:NativeAPI(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI) - [第一个Native C++应用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) - [Native Component(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) \ No newline at end of file diff --git a/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..d1db02f381152821b699ffcc3870081a46742641 --- /dev/null +++ b/zh-cn/application-dev/napi/neural-network-runtime-guidelines.md @@ -0,0 +1,491 @@ +# Neural Network Runtime对接AI推理框架开发指导 + +## 场景介绍 + +Neural Network Runtime作为AI推理引擎和加速芯片的桥梁,为AI推理引擎提供精简的Native接口,满足推理引擎通过加速芯片执行端到端推理的需求。 + +本文以图1展示的`Add`单算子模型为例,介绍Neural Network Runtime的开发流程。`Add`算子包含两个输入、一个参数和一个输出,其中的`activation`参数用于指定`Add`算子中激活函数的类型。 + +**图1** Add单算子网络示意图 +!["Add单算子网络示意图"](figures/02.png) + +## 环境准备 + +### 环境要求 + +Neural Network Runtime部件的环境要求如下: + +- 系统版本:OpenHarmony master分支。 +- 开发环境:Ubuntu 18.04及以上。 +- 接入设备:OpenHarmony定义的标准设备,并且系统中内置的硬件加速器驱动,已通过HDI接口对接Neural Network Runtime。 + +由于Neural Network Runtime通过OpenHarmony Native API对外开放,需要通过OpenHarmony的Native开发套件编译Neural Network Runtime应用。在社区的[每日构建](http://ci.openharmony.cn/dailys/dailybuilds)下载对应系统版本的ohos-sdk压缩包,从压缩包中提取对应平台的Native开发套件。以Linux为例,Native开发套件的压缩包命名为`native-linux-{版本号}.zip`。 + +### 环境搭建 + +1. 打开Ubuntu编译服务器的终端。 +2. 把下载好的Native开发套件压缩包拷贝至当前用户根目录下。 +3. 执行以下命令解压Native开发套件的压缩包。 +```shell +unzip native-linux-{版本号}.zip +``` + +解压缩后的内容如下(随版本迭代,目录下的内容可能发生变化,请以最新版本的Native API为准): +```text +native/ +├── build // 交叉编译工具链 +├── build-tools // 编译构建工具 +├── docs +├── llvm +├── nativeapi_syscap_config.json +├── ndk_system_capability.json +├── NOTICE.txt +├── oh-uni-package.json +└── sysroot // Native API头文件和库 +``` +## 接口说明 + +这里给出Neural Network Runtime开发流程中通用的接口,具体请见下列表格。 + +### 结构体 + +| 结构体名称 | 描述 | +| --------- | ---- | +| typedef struct OH_NNModel OH_NNModel | Neural Network Runtime的模型句柄,用于构造模型。 | +| typedef struct OH_NNCompilation OH_NNCompilation | Neural Network Runtime的编译器句柄,用于编译AI模型。 | +| typedef struct OH_NNExecutor OH_NNExecutor | Neural Network Runtime的执行器句柄,用于在指定设备上执行推理计算。 | + +### 模型构造相关接口 + +| 接口名称 | 描述 | +| ------- | --- | +| OH_NNModel_Construct() | 创建OH_NNModel类型的模型实例。 | +| OH_NN_ReturnCode OH_NNModel_AddTensor(OH_NNModel *model, const OH_NN_Tensor *tensor) | 向模型实例中添加张量。 | +| OH_NN_ReturnCode OH_NNModel_SetTensorData(OH_NNModel *model, uint32_t index, const void *dataBuffer, size_t length) | 设置张量的数值。 | +| OH_NN_ReturnCode OH_NNModel_AddOperation(OH_NNModel *model, OH_NN_OperationType op, const OH_NN_UInt32Array *paramIndices, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | 向模型实例中添加算子。 | +| OH_NN_ReturnCode OH_NNModel_SpecifyInputsAndOutputs(OH_NNModel *model, const OH_NN_UInt32Array *inputIndices, const OH_NN_UInt32Array *outputIndices) | 指定模型的输入输出。 | +| OH_NN_ReturnCode OH_NNModel_Finish(OH_NNModel *model) | 完成模型构图。| +| void OH_NNModel_Destroy(OH_NNModel **model) | 释放模型实例。 | + +### 模型编译相关接口 + +| 接口名称 | 描述 | +| ------- | --- | +| OH_NNCompilation *OH_NNCompilation_Construct(const OH_NNModel *model) | 创建OH_NNCompilation类型的编译实例。 | +| OH_NN_ReturnCode OH_NNCompilation_SetDevice(OH_NNCompilation *compilation, size_t deviceID) | 指定模型编译和计算的硬件。 | +| OH_NN_ReturnCode OH_NNCompilation_SetCache(OH_NNCompilation *compilation, const char *cachePath, uint32_t version) | 设置编译后的模型缓存路径和缓存版本。 | +| OH_NN_ReturnCode OH_NNCompilation_Build(OH_NNCompilation *compilation) | 进行模型编译。 | +| void OH_NNCompilation_Destroy(OH_NNCompilation **compilation) | 释放OH_NNCompilation对象。 | + +### 执行推理相关接口 + +| 接口名称 | 描述 | +| ------- | --- | +| OH_NNExecutor *OH_NNExecutor_Construct(OH_NNCompilation *compilation) | 创建OH_NNExecutor类型的执行器实例。 | +| OH_NN_ReturnCode OH_NNExecutor_SetInput(OH_NNExecutor *executor, uint32_t inputIndex, const OH_NN_Tensor *tensor, const void *dataBuffer, size_t length) | 设置模型单个输入的数据。 | +| OH_NN_ReturnCode OH_NNExecutor_SetOutput(OH_NNExecutor *executor, uint32_t outputIndex, void *dataBuffer, size_t length) | 设置模型单个输出的缓冲区。 | +| OH_NN_ReturnCode OH_NNExecutor_Run(OH_NNExecutor *executor) | 执行推理。 | +| void OH_NNExecutor_Destroy(OH_NNExecutor **executor) | 销毁OH_NNExecutor实例,释放实例占用的内存。 | + +### 设备管理相关接口 + +| 接口名称 | 描述 | +| ------- | --- | +| OH_NN_ReturnCode OH_NNDevice_GetAllDevicesID(const size_t **allDevicesID, uint32_t *deviceCount) | 获取对接到 Neural Network Runtime 的硬件ID。 | + + +## 开发步骤 + +Neural Network Runtime的开发流程主要包含**模型构造**、**模型编译**和**推理执行**三个阶段。以下开发步骤以`Add`单算子模型为例,介绍调用Neural Network Runtime接口,开发应用的过程。 + +1. 创建应用样例文件。 + + 首先,创建Neural Network Runtime应用样例的源文件。在项目目录下执行以下命令,创建`nnrt_example/`目录,在目录下创建 `nnrt_example.cpp` 源文件。 + + ```shell + mkdir ~/nnrt_example && cd ~/nnrt_example + touch nnrt_example.cpp + ``` + +2. 导入Neural Network Runtime。 + + 在 `nnrt_example.cpp` 文件的开头添加以下代码,引入Neural Network Runtime模块。 + + ```cpp + #include + #include + #include + + #include "neural_network_runtime/neural_network_runtime.h" + + // 常量,用于指定输入、输出数据的字节长度 + const size_t DATA_LENGTH = 4 * 12; + ``` + +3. 构造模型。 + + 使用Neural Network Runtime接口,构造`Add`单算子样例模型。 + + ```cpp + OH_NN_ReturnCode BuildModel(OH_NNModel** pModel) + { + // 创建模型实例,进行模型构造 + OH_NNModel* model = OH_NNModel_Construct(); + if (model == nullptr) { + std::cout << "Create model failed." << std::endl; + return OH_NN_MEMORY_ERROR; + } + + // 添加Add算子的第一个输入Tensor,类型为float32,张量形状为[1, 2, 2, 3] + int32_t inputDims[4] = {1, 2, 2, 3}; + OH_NN_Tensor input1 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR}; + OH_NN_ReturnCode ret = OH_NNModel_AddTensor(model, &input1); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, add Tensor of first input failed." << std::endl; + return ret; + } + + // 添加Add算子的第二个输入Tensor,类型为float32,张量形状为[1, 2, 2, 3] + OH_NN_Tensor input2 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR}; + ret = OH_NNModel_AddTensor(model, &input2); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, add Tensor of second input failed." << std::endl; + return ret; + } + + // 添加Add算子的参数Tensor,该参数Tensor用于指定激活函数的类型,Tensor的数据类型为int8。 + int32_t activationDims = 1; + int8_t activationValue = OH_NN_FUSED_NONE; + OH_NN_Tensor activation = {OH_NN_INT8, 1, &activationDims, nullptr, OH_NN_ADD_ACTIVATIONTYPE}; + ret = OH_NNModel_AddTensor(model, &activation); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, add Tensor of activation failed." << std::endl; + return ret; + } + + // 将激活函数类型设置为OH_NN_FUSED_NONE,表示该算子不添加激活函数。 + ret = OH_NNModel_SetTensorData(model, 2, &activationValue, sizeof(int8_t)); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, set value of activation failed." << std::endl; + return ret; + } + + // 设置Add算子的输出,类型为float32,张量形状为[1, 2, 2, 3] + OH_NN_Tensor output = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR}; + ret = OH_NNModel_AddTensor(model, &output); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, add Tensor of output failed." << std::endl; + return ret; + } + + // 指定Add算子的输入、参数和输出索引 + uint32_t inputIndicesValues[2] = {0, 1}; + uint32_t paramIndicesValues = 2; + uint32_t outputIndicesValues = 3; + OH_NN_UInt32Array paramIndices = {¶mIndicesValues, 1}; + OH_NN_UInt32Array inputIndices = {inputIndicesValues, 2}; + OH_NN_UInt32Array outputIndices = {&outputIndicesValues, 1}; + + // 向模型实例添加Add算子 + ret = OH_NNModel_AddOperation(model, OH_NN_OPS_ADD, ¶mIndices, &inputIndices, &outputIndices); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, add operation failed." << std::endl; + return ret; + } + + // 设置模型实例的输入、输出索引 + ret = OH_NNModel_SpecifyInputsAndOutputs(model, &inputIndices, &outputIndices); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, specify inputs and outputs failed." << std::endl; + return ret; + } + + // 完成模型实例的构建 + ret = OH_NNModel_Finish(model); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed, error happened when finishing model construction." << std::endl; + return ret; + } + + *pModel = model; + return OH_NN_SUCCESS; + } + ``` + +4. 查询Neural Network Runtime已经对接的加速芯片。 + + Neural Network Runtime支持通过HDI接口,对接多种加速芯片。在执行模型编译前,需要查询当前设备下,Neural Network Runtime已经对接的加速芯片。每个加速芯片对应唯一的ID值,在编译阶段需要通过设备ID,指定模型编译的芯片。 + ```cpp + void GetAvailableDevices(std::vector& availableDevice) + { + availableDevice.clear(); + + // 获取可用的硬件ID + const size_t* devices = nullptr; + uint32_t deviceCount = 0; + OH_NN_ReturnCode ret = OH_NNDevice_GetAllDevicesID(&devices, &deviceCount); + if (ret != OH_NN_SUCCESS) { + std::cout << "GetAllDevicesID failed, get no available device." << std::endl; + return; + } + + for (uint32_t i = 0; i < deviceCount; i++) { + availableDevice.emplace_back(devices[i]); + } + } + ``` + +5. 在指定的设备上编译模型。 + + Neural Network Runtime使用抽象的模型表达描述AI模型的拓扑结构,在加速芯片上执行前,需要通过Neural Network Runtime提供的编译模块,将抽象的模型表达下发至芯片驱动层,转换成可以直接推理计算的格式。 + ```cpp + OH_NN_ReturnCode CreateCompilation(OH_NNModel* model, const std::vector& availableDevice, OH_NNCompilation** pCompilation) + { + // 创建编译实例,用于将模型传递至底层硬件编译 + OH_NNCompilation* compilation = OH_NNCompilation_Construct(model); + if (compilation == nullptr) { + std::cout << "CreateCompilation failed, error happended when creating compilation." << std::endl; + return OH_NN_MEMORY_ERROR; + } + + // 设置编译的硬件、缓存路径、性能模式、计算优先级、是否开启float16低精度计算等选项 + + // 选择在第一个设备上编译模型 + OH_NN_ReturnCode ret = OH_NNCompilation_SetDevice(compilation, availableDevice[0]); + if (ret != OH_NN_SUCCESS) { + std::cout << "CreateCompilation failed, error happened when setting device." << std::endl; + return ret; + } + + // 将模型编译结果缓存在/data/local/tmp目录下,版本号指定为1 + ret = OH_NNCompilation_SetCache(compilation, "/data/local/tmp", 1); + if (ret != OH_NN_SUCCESS) { + std::cout << "CreateCompilation failed, error happened when setting cache path." << std::endl; + return ret; + } + + // 完成编译设置,进行模型编译 + ret = OH_NNCompilation_Build(compilation); + if (ret != OH_NN_SUCCESS) { + std::cout << "CreateCompilation failed, error happened when building compilation." << std::endl; + return ret; + } + + *pCompilation = compilation; + return OH_NN_SUCCESS; + } + ``` + +6. 创建执行器。 + + 完成模型编译后,需要调用Neural Network Runtime的执行模块,创建推理执行器。执行阶段,设置模型输入、获取模型输出和触发推理计算的操作均围绕执行器完成。 + ```cpp + OH_NNExecutor* CreateExecutor(OH_NNCompilation* compilation) + { + // 创建执行实例 + OH_NNExecutor* executor = OH_NNExecutor_Construct(compilation); + return executor; + } + ``` + +7. 执行推理计算,并打印计算结果。 + + 通过执行模块提供的接口,将推理计算所需要的输入数据传递给执行器,触发执行器完成一次推理计算,获取模型的推理计算结果。 + ```cpp + OH_NN_ReturnCode Run(OH_NNExecutor* executor) + { + // 构造示例数据 + float input1[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; + float input2[12] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}; + + int32_t inputDims[4] = {1, 2, 2, 3}; + OH_NN_Tensor inputTensor1 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR}; + OH_NN_Tensor inputTensor2 = {OH_NN_FLOAT32, 4, inputDims, nullptr, OH_NN_TENSOR}; + + // 设置执行的输入 + + // 设置执行的第一个输入,输入数据由input1指定 + OH_NN_ReturnCode ret = OH_NNExecutor_SetInput(executor, 0, &inputTensor1, input1, DATA_LENGTH); + if (ret != OH_NN_SUCCESS) { + std::cout << "Run failed, error happened when setting first input." << std::endl; + return ret; + } + + // 设置执行的第二个输入,输入数据由input2指定 + ret = OH_NNExecutor_SetInput(executor, 1, &inputTensor2, input2, DATA_LENGTH); + if (ret != OH_NN_SUCCESS) { + std::cout << "Run failed, error happened when setting second input." << std::endl; + return ret; + } + + // 设置输出的数据缓冲区,OH_NNExecutor_Run执行计算后,输出结果将保留在output中 + float output[12]; + ret = OH_NNExecutor_SetOutput(executor, 0, output, DATA_LENGTH); + if (ret != OH_NN_SUCCESS) { + std::cout << "Run failed, error happened when setting output buffer." << std::endl; + return ret; + } + + // 执行计算 + ret = OH_NNExecutor_Run(executor); + if (ret != OH_NN_SUCCESS) { + std::cout << "Run failed, error doing execution." << std::endl; + return ret; + } + + // 打印输出结果 + for (uint32_t i = 0; i < 12; i++) { + std::cout << "Output index: " << i << ", value is: " << output[i] << "." << std::endl; + } + + return OH_NN_SUCCESS; + } + ``` + +8. 构建端到端模型构造-编译-执行流程。 + + 步骤3-步骤7实现了模型的模型构造、编译和执行流程,并封装成4个函数,便于模块化开发。以下示例代码将4个函数串联成完整的Neural Network Runtime开发流程。 + ```cpp + int main() + { + OH_NNModel* model = nullptr; + OH_NNCompilation* compilation = nullptr; + OH_NNExecutor* executor = nullptr; + std::vector availableDevices; + + // 模型构造阶段 + OH_NN_ReturnCode ret = BuildModel(&model); + if (ret != OH_NN_SUCCESS) { + std::cout << "BuildModel failed." << std::endl; + OH_NNModel_Destroy(&model); + return -1; + } + + // 获取可执行的设备 + GetAvailableDevices(availableDevices); + if (availableDevices.empty()) { + std::cout << "No available device." << std::endl; + OH_NNModel_Destroy(&model); + return -1; + } + + // 模型编译阶段 + ret = CreateCompilation(model, availableDevices, &compilation); + if (ret != OH_NN_SUCCESS) { + std::cout << "CreateCompilation failed." << std::endl; + OH_NNModel_Destroy(&model); + OH_NNCompilation_Destroy(&compilation); + return -1; + } + + // 创建模型的推理执行器 + executor = CreateExecutor(compilation); + if (executor == nullptr) { + std::cout << "CreateExecutor failed, no executor is created." << std::endl; + OH_NNModel_Destroy(&model); + OH_NNCompilation_Destroy(&compilation); + return -1; + } + + // 使用上一步创建的执行器,执行单步推理计算 + ret = Run(executor); + if (ret != OH_NN_SUCCESS) { + std::cout << "Run failed." << std::endl; + OH_NNModel_Destroy(&model); + OH_NNCompilation_Destroy(&compilation); + OH_NNExecutor_Destroy(&executor); + return -1; + } + + // 释放申请的资源 + OH_NNModel_Destroy(&model); + OH_NNCompilation_Destroy(&compilation); + OH_NNExecutor_Destroy(&executor); + + return 0; + } + ``` + +## 调测验证 + +1. 准备应用样例的编译配置文件。 + + 新建一个 `CMakeLists.txt` 文件,为开发步骤中的应用样例文件 `nnrt_example.cpp` 添加编译配置。以下提供简单的 `CMakeLists.txt` 示例: + ```text + cmake_minimum_required(VERSION 3.16) + project(nnrt_example C CXX) + + add_executable(nnrt_example + ./nnrt_example.cpp + ) + + target_link_libraries(nnrt_example + neural_network_runtime.z + ) + ``` + +2. 编译应用样例。 + + 执行以下命令,在当前目录下新建build/目录,在build/目录下编译 `nnrt_example.cpp`,得到二进制文件 `nnrt_example`。 + ```shell + mkdir build && cd build + cmake -DCMAKE_TOOLCHAIN_FILE={交叉编译工具链的路径}/build/cmake/ohos.toolchain.cmake -DOHOS_ARCH=arm64-v8a -DOHOS_PLATFORM=OHOS -DOHOS_STL=c++_static .. + make + ``` + +3. 执行以下代码,将样例推送到设备上执行。 + ```shell + # 将编译得到的 `nnrt_example` 推送到设备上,执行样例。 + hdc_std file send ./nnrt_example /data/local/tmp/. + + # 给测试用例可执行文件加上权限。 + hdc_std shell "chmod +x /data/local/tmp/nnrt_example" + + # 执行测试用例 + hdc_std shell "/data/local/tmp/nnrt_example" + ``` + + 如果样例执行正常,应该得到以下输出。 + ```text + Output index: 0, value is: 11.000000. + Output index: 1, value is: 13.000000. + Output index: 2, value is: 15.000000. + Output index: 3, value is: 17.000000. + Output index: 4, value is: 19.000000. + Output index: 5, value is: 21.000000. + Output index: 6, value is: 23.000000. + Output index: 7, value is: 25.000000. + Output index: 8, value is: 27.000000. + Output index: 9, value is: 29.000000. + Output index: 10, value is: 31.000000. + Output index: 11, value is: 33.000000. + ``` + +4. 检查模型缓存(可选)。 + + 如果在调测环境下,Neural Network Runtime对接的HDI服务支持模型缓存功能,执行完 `nnrt_example`, 可以在 `/data/local/tmp` 目录下找到生成的缓存文件。 + + > **说明:** + > + > 模型的IR需要传递到硬件驱动层,由HDI服务将统一的IR图,编译成硬件专用的计算图,编译的过程非常耗时。Neural Network Runtime支持计算图缓存的特性,可以将HDI服务编译生成的计算图,缓存到设备存储中。当下一次在同一个加速芯片上编译同一个模型时,通过指定缓存的路径,Neural Network Runtime可以直接加载缓存文件中的计算图,减少编译消耗的时间。 + + 检查缓存目录下的缓存文件: + ```shell + ls /data/local/tmp + ``` + + 以下为打印结果: + ```text + # 0.nncache cache_info.nncache + ``` + + 如果缓存不再使用,需要手动删除缓存,可以参考以下命令,删除缓存文件。 + ```shell + rm /data/local/tmp/*nncache + ``` + +## 相关实例 + +第三方AI推理框架对接Neural Network Runtime的流程,可以参考以下相关实例: +- [Tensorflow Lite接入NNRt Delegate开发指南](https://gitee.com/openharmony/neural_network_runtime/tree/master/example/deep_learning_framework) + diff --git a/zh-cn/application-dev/notification/notification-guidelines.md b/zh-cn/application-dev/notification/notification-guidelines.md index 05e9e97a51132ca686c0a27aebb3e44ed2327f04..5c2eb30a117305bb76b78f2337a525fe7dfe8945 100644 --- a/zh-cn/application-dev/notification/notification-guidelines.md +++ b/zh-cn/application-dev/notification/notification-guidelines.md @@ -133,7 +133,7 @@ var subscriber = { ##### 开启通知使能 -应用发布通知的使能开关默认是关闭的,所以应用发布通知前需要用户允许后才能发送。应用可以通过Notification.requestEnableNotification弹窗提醒用户允许发送通知。 +应用发布通知的使能开关默认是关闭的,需要通过下拉通知栏,在通知设置里打开通知开关。应用也可以通过调用Notification.requestEnableNotification接口,弹窗提示用户是否允许发送通知。 ```js Notification.requestEnableNotification().then((data) => { @@ -263,5 +263,3 @@ Notification.cancel(1, "label", cancelCallback) 针对通知开发,有以下相关可供参考: - [`Notification:`订阅、发送通知(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/Notification) - -- [`Notification`:通知(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/Notification) diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index 429b62a2cf66d8a20401184d8fa6fc3a56a3f7a9..64e10076782a08f6aea0572f55d421b22603c086 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -8,7 +8,6 @@ - [应用包结构说明(FA模型)](package-structure.md) - [应用包结构说明(Stage模型)](stage-structure.md) - [SysCap说明](syscap.md) - - [HarmonyAppProvision配置文件](app-provision-structure.md) - [资源分类与访问](resource-categories-and-access.md) - 学习ArkTS语言 - [初识ArkTS语言](arkts-get-started.md) diff --git a/zh-cn/application-dev/quick-start/arkts-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md index 08663ab440ede2aa39dcc722da1fdb54217942a3..11066681cec9d1e13a10c4031dd407c9e72abb70 100644 --- a/zh-cn/application-dev/quick-start/arkts-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -125,8 +125,8 @@ interface DataChangeListener { | 参数名 | 参数类型 | 必填 | 参数描述 | | ------------- | --------------------- | ---- | ------------------------------------------------------------ | | dataSource | IDataSource | 是 | 实现IDataSource接口的对象,需要开发者实现相关接口。 | -| itemGenerator | (item: any) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | -| keyGenerator | (item: any) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | +| itemGenerator | (item: any, index?: number) => void | 是 | 生成子组件的lambda函数,为数组中的每一个数据项创建一个或多个子组件,单个子组件或子组件列表必须包括在大括号“{...}”中。 | +| keyGenerator | (item: any, index?: number) => string | 否 | 匿名函数,用于给数组中的每一个数据项生成唯一且固定的键值。当数据项在数组中的位置更改时,其键值不得更改,当数组中的数据项被新项替换时,被替换项的键值和新项的键值必须不同。键值生成器的功能是可选的,但是,为了使开发框架能够更好地识别数组更改,提高性能,建议提供。如将数组反向时,如果没有提供键值生成器,则LazyForEach中的所有节点都将重建。 | ### IDataSource类型说明 @@ -142,14 +142,14 @@ interface DataChangeListener { | 名称 | 描述 | | -------------------------------------------------------- | -------------------------------------- | | onDataReloaded(): void | 重新加载所有数据。 | -| onDataAdded(index: number): void (deprecated) | 通知组件index的位置有数据添加。 | -| onDataMoved(from: number, to: number): void (deprecated) | 通知组件数据从from的位置移到to的位置。 | -| onDataDeleted(index: number): void (deprecated) | 通知组件index的位置有数据删除。 | -| onDataChanged(index: number): void (deprecated) | 通知组件index的位置有数据变化。 | -| onDataAdd(index: number): void 8+ | 通知组件index的位置有数据添加。 | -| onDataMove(from: number, to: number): void 8+ | 通知组件数据从from的位置移到to的位置。 | -| onDataDelete(index: number): void 8+ | 通知组件index的位置有数据删除。 | -| onDataChange(index: number): void 8+ | 通知组件index的位置有数据变化。 | +| onDataAdded(index: number): voiddeprecated | 通知组件index的位置有数据添加。从API Version 8开始废弃,建议使用onDataAdd。 | +| onDataMoved(from: number, to: number): voiddeprecated | 通知组件数据从from的位置移到to的位置。从API Version 8开始废弃,建议使用onDataMove。 | +| onDataDeleted(index: number): voiddeprecated | 通知组件index的位置有数据删除。从API Version 8开始废弃,建议使用onDataDelete。 | +| onDataChanged(index: number): voiddeprecated | 通知组件index的位置有数据变化。 从API Version 8开始废弃,建议使用onDataChange。 | +| onDataAdd(index: number): void8+ | 通知组件index的位置有数据添加。 | +| onDataMove(from: number, to: number): void8+ | 通知组件数据从from的位置移到to的位置。 | +| onDataDelete(index: number): void8+ | 通知组件index的位置有数据删除。 | +| onDataChange(index: number): void8+ | 通知组件index的位置有数据变化。 | ## 示例 diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md index a140452948660edabecc87e7b98706b91c51a268..0f67972ef260d3e515a5d9a9d4b35694d8e35d1b 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -468,6 +468,11 @@ struct CompC { 装饰器@State、@Prop、@Link、@ObjectLink、@Provide、@Consume、@StorageProp以及@StorageLink所装饰的变量均可以通过@Watch监听其变化。 + +> **说明:** +> +> 深层次数据修改不会触发@Watch回调,例如无法监听数组中对象值的改变。 + ```ts // xxx.ets @Entry diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index bb5ca929eabd6a97f1cb2a5245cf28147bc2162e..b0acbfbbdeca2001712ad83c4002d04b5cfb96c0 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -61,33 +61,20 @@ - continuation/[ContinuationResult (ContinuationResult)](js-apis-continuation-continuationResult.md) - 公共事件与通知 - [@ohos.commonEvent (公共事件模块)](js-apis-commonEvent.md) + - [@ohos.commonEventManager (新公共事件模块)](js-apis-commonEventManager.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.notification (Notification模块)](js-apis-notification.md) - application/[EventHub (EventHub)](js-apis-eventhub.md) -- 应用程序包管理 - - [@ohos.bundle (Bundle模块)](js-apis-Bundle.md) - - [@ohos.bundle.defaultAppManager (Bundle模块)](js-apis-bundle-defaultAppManager.md) - - [@ohos.bundle.innerBundleManager (innerBundleManager模块(JS端SDK接口))](js-apis-Bundle-InnerBundleManager.md) - - [@ohos.distributedBundle (distributedBundle模块(JS端SDK接口))](js-apis-Bundle-distributedBundle.md) +- 包管理 + - [@ohos.bundle.appControl(appControl模块)](js-apis-appControl.md) + - [@ohos.bundle.bundleManager (bundleManager模块)](js-apis-bundleManager.md) + - [@ohos.bundle.bundleMonitor(bundleMonitor模块)](js-apis-bundleMonitor.md) + - [@ohos.bundle.defaultAppManager(defaultAppManager模块)](js-apis-defaultAppManager.md) + - [@ohos.bundle.innerBundleManager (innerBundleManager模块)](js-apis-Bundle-InnerBundleManager.md) + - [@ohos.bundle.distributedBundle (distributedBundle模块)](js-apis-distributedBundle.md) + - [@ohos.bundle.freeInstall(freeInstall模块)](js-apis-freeInstall.md) + - [@ohos.bundle.installer(installer模块)](js-apis-installer.md) - [@ohos.zlib (Zip模块)](js-apis-zlib.md) - - bundle/[AbilityInfo (AbilityInfo)](js-apis-bundle-AbilityInfo.md) - - bundle/[ApplicationInfo (ApplicationInfo)](js-apis-bundle-ApplicationInfo.md) - - bundle/[BundleInfo (BundleInfo)](js-apis-bundle-BundleInfo.md) - - bundle/[BundleInstaller (BundleInstaller)](js-apis-bundle-BundleInstaller.md) - - bundle/[BundleStatusCallback (BundleStatusCallback)](js-apis-Bundle-BundleStatusCallback.md) - - bundle/[CustomizeData (CustomizeData)](js-apis-bundle-CustomizeData.md) - - bundle/[DispatchInfo (DispatchInfo)](js-apis-dispatchInfo.md) - - bundle/[ElementName (ElementName)](js-apis-bundle-ElementName.md) - - bundle/[ExtensionAbilityInfo (ExtensionAbilityInfo)](js-apis-bundle-ExtensionAbilityInfo.md) - - bundle/[HapModuleInfo (HapModuleInfo)](js-apis-bundle-HapModuleInfo.md) - - bundle/[LauncherAbilityInfo (LauncherAbilityInfo)](js-apis-bundle-LauncherAbilityInfo.md) - - bundle/[Metadata (Metadata)](js-apis-bundle-Metadata.md) - - bundle/[ModuleInfo (ModuleInfo)](js-apis-bundle-ModuleInfo.md) - - bundle/[PermissionDef (PermissionDef)](js-apis-bundle-PermissionDef.md) - - bundle/[RemoteAbilityInfo (RemoteAbilityInfo)](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[ShortcutInfo(deprecated) (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md) - - bundle/[PackInfo (PackInfo)](js-apis-bundle-PackInfo.md) - - bundleManager/[ShortcutInfo (ShortcutInfo)](js-apis-bundleManager-shortcutInfo.md) - UI界面 - [@ohos.animator (动画)](js-apis-animator.md) - [@ohos.curves (插值计算)](js-apis-curve.md) @@ -220,7 +207,7 @@ - [@ohos.geolocation (位置服务)](js-apis-geolocation.md) - [@ohos.multimodalInput.inputConsumer (组合按键)](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice (输入设备)](js-apis-inputdevice.md) - - [@ohos.multimodalInput.inputDeviceCooperate (键鼠穿越管理)](js-apis-cooperate.md) + - [@ohos.multimodalInput.inputDeviceCooperate (键鼠穿越)](js-apis-cooperate.md) - [@ohos.multimodalInput.inputEvent (输入事件)](js-apis-inputevent.md) - [@ohos.multimodalInput.inputEventClient (按键注入)](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputMonitor (输入监听)](js-apis-inputmonitor.md) @@ -268,13 +255,14 @@ - 测试 - [@ohos.application.testRunner (TestRunner)](js-apis-testRunner.md) - [@ohos.uitest (UiTest)](js-apis-uitest.md) - - 已停止维护的接口 - [@ohos.backgroundTaskManager (后台任务管理)](js-apis-backgroundTaskManager.md) + - [@ohos.bundle(包管理)](js-apis-Bundle.md) - [@ohos.bundleState (设备使用信息统计)](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace (性能打点)](js-apis-bytrace.md) - [@ohos.data.storage (轻量级存储)](js-apis-data-storage.md) - [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md) + - [@ohos.distributedBundle(分布式包管理)](js-apis-Bundle-distributedBundle.md) - [@ohos.prompt (弹窗)](js-apis-prompt.md) - [@ohos.reminderAgent (后台代理提醒)](js-apis-reminderAgent.md) - [@ohos.usb (USB管理)](js-apis-usb-deprecated.md) diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png new file mode 100644 index 0000000000000000000000000000000000000000..e3b0acfef7bffa4e6a8c9f9ab6a7dc9b809fa467 Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Blur.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png new file mode 100644 index 0000000000000000000000000000000000000000..997602e7d7c8ea440a4f344f6a480ea66022fabf Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Brightness.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png new file mode 100644 index 0000000000000000000000000000000000000000..69990adea571b907fabd854eb531528d7a60dc8f Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Add_Grayscale.png differ diff --git a/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png new file mode 100644 index 0000000000000000000000000000000000000000..25e130fcf37fc3654592f619c8a93b703a085e9a Binary files /dev/null and b/zh-cn/application-dev/reference/apis/figures/zh-ch_image_Main_Color.png differ diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index 128c916edc2d5616aa91d00d689d360a97cd7c9b..bc19287abd6bf80a3f78211e937207df1ab4c58f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -1,25 +1,21 @@ # BundleStatusCallback - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 从API version 9开始不再支持。建议使用[bundleMonitor](js-apis-bundleMonitor.md)替代。 +应用状态回调的信息,通过接口[innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md)获取。 -应用包回调的信息,通过接口[innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md)获取。 -## BundleStatusCallback +## BundleStatusCallback(deprecated) +> 从API version 9开始不再支持。建议使用[bundleMonitor](js-apis-bundleMonitor.md)替代。 **系统API:** 此接口为系统接口,三方应用不支持调用。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework。 -| 名称 | 类型 | 说明 | +| 监听类型 | 注册回调 | 说明 | | ------ | --------------------------------------------- | -------------------------------------- | -| add | (bundleName : string, userId: number) => void | 获取添加的launcherStatusCallback回调。 | -| update | (bundleName : string, userId: number) => void | 获取编辑的launcherStatusCallback回调。 | -| remove | (bundleName : string, userId: number) => void | 获取移除的launcherStatusCallback回调。 | - - - +| add | (bundleName : string, userId: number) => void | 获取应用安装时的信息。 | +| update | (bundleName : string, userId: number) => void | 获取应用更新时的信息。 | +| remove | (bundleName : string, userId: number) => void | 获取应用卸载时的信息。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 7c0bf1054168d9f5a0bbd66840239a6af4f3ccbd..448741f08e871599414a29ca7a134df8811c560a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,14 +1,14 @@ -# innerBundleManager模块(JS端SDK接口) +# innerBundleManager模块(deprecated) -本模块提供内部包的管理 +本模块提供launcher应用使用的接口 -> **说明:** > > 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块从API version 9开始不再支持。建议使用[launcherBundleManager](js-apis-launcherBundleManager.md)及[bundleMonitor](js-apis-bundleMonitor.md)替代。 ## 导入模块 -``` +```typescript import innerBundleManager from '@ohos.bundle.innerBundleManager'; ``` @@ -16,20 +16,13 @@ import innerBundleManager from '@ohos.bundle.innerBundleManager'; SystemCapability.BundleManager.BundleFramework -## 权限列表 - -| 权限 | 权限等级 | 描述 | -| ------------------------------------------ | ------------ | ---------------------------- | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 | -| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant | 允许该应用获取应用变化消息。 | -权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) - -## innerBundleManager.getLauncherAbilityInfos +## innerBundleManager.getLauncherAbilityInfos(deprecated) getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; 以异步方法根据给定的包名获取LauncherAbilityInfos,使用callback形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** @@ -52,12 +45,12 @@ SystemCapability.BundleManager.BundleFramework | callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回程序信息。 | - -## innerBundleManager.getLauncherAbilityInfos +## innerBundleManager.getLauncherAbilityInfos(deprecated) getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> 以异步方法根据给定的包名获取LauncherAbilityInfos,使用Promise形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getLauncherAbilityInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** @@ -84,11 +77,12 @@ SystemCapability.BundleManager.BundleFramework | ------------------------------------------------------------ | ------------------------- | | Promise\> | Promise形式返回程序信息。 | -## innerBundleManager.on +## innerBundleManager.on(deprecated) on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void; 注册Callback。 +> 从API version 9开始不再支持。建议使用[bundleMonitor#on](js-apis-bundleMonitor.md)替代。 **需要权限:** @@ -110,11 +104,12 @@ SystemCapability.BundleManager.BundleFramework | bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | 是 | 指示要注册的回调。 | | callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 | -## innerBundleManager.on +## innerBundleManager.on(deprecated) -on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback): Promise<string> +on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback) : Promise<string> 注册Callback。 +> 从API version 9开始不再支持。建议使用[bundleMonitor#on](js-apis-bundleMonitor.md)替代。 **需要权限:** @@ -141,11 +136,12 @@ SystemCapability.BundleManager.BundleFramework | --------------- | ----------------------------------- | | Promise\ | Promise形式返回正确结果或错误信息。 | -## innerBundleManager.off +## innerBundleManager.off(deprecated) off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void; 取消注册Callback。 +> 从API version 9开始不再支持。建议使用[bundleMonitor#off](js-apis-bundleMonitor.md)替代。 **需要权限:** @@ -166,11 +162,12 @@ SystemCapability.BundleManager.BundleFramework | type | string | 是 | 指示应执行命令,只支持BundleStatusChange。 | | callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回正确结果或错误信息。 | -## innerBundleManager.off +## innerBundleManager.off(deprecated) -off(type:"BundleStatusChange"): Promise<string> +off(type:"BundleStatusChange") : Promise<string> 取消注册Callback。 +> 从API version 9开始不再支持。建议使用[bundleMonitor#off](js-apis-bundleMonitor.md)替代。 **需要权限:** @@ -196,11 +193,12 @@ SystemCapability.BundleManager.BundleFramework | --------------- | ----------------------------------- | | Promise\ | Promise形式返回正确结果或错误信息。 | -## innerBundleManager.getAllLauncherAbilityInfos +## innerBundleManager.getAllLauncherAbilityInfos(deprecated) getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; 以异步方法获取所有的LauncherAbilityInfos,使用callback形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** @@ -221,11 +219,12 @@ SystemCapability.BundleManager.BundleFramework | userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | | callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回程序信息。 | -## innerBundleManager.getAllLauncherAbilityInfos +## innerBundleManager.getAllLauncherAbilityInfos(deprecated) getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> 以异步方法获取LauncherAbilityInfos,使用Promise形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getAllLauncherAbilityInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** @@ -251,11 +250,12 @@ SystemCapability.BundleManager.BundleFramework | ------------------------------------------------------------ | ------------------------- | | Promise\> | Promise形式返回程序信息。 | -## innerBundleManager.getShortcutInfos +## innerBundleManager.getShortcutInfos(deprecated) getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void; 以异步方法根据给定的包名获取快捷方式信息,使用callback形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** @@ -276,11 +276,12 @@ SystemCapability.BundleManager.BundleFramework | bundleName | string | 是 | 要查询的应用程序包名称。 | | callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回快捷方式信息。 | -## innerBundleManager.getShortcutInfos +## innerBundleManager.getShortcutInfos(deprecated) getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> 以异步方法根据给定的包名获取快捷方式信息,使用Promise形式返回结果。 +> 从API version 9开始不再支持。建议使用[launcherBundleManager#getShortcutInfo](js-apis-launcherBundleManager.md)替代。 **需要权限:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md index 47ce911e2440f773a8d22cb8a0058aae19005e37..f10b2bea8943bb0f0b713d048267c902b9e9c335 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle.md @@ -3,9 +3,8 @@ 本模块提供应用信息查询能力,支持BundleInfo、ApplicationInfo、Ability、ExtensionAbility、应用状态等信息的查询 > **说明:** -> -> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> API9 当前为Canary版本,仅供试用,不保证接口可稳定调用。 +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 ```js @@ -23,7 +22,9 @@ import bundle from '@ohos.bundle'; 权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) -## bundle.getApplicationInfo +## bundle.getApplicationInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo)替代。 getApplicationInfo(bundleName: string, bundleFlags: number, userId?: number): Promise\ @@ -65,7 +66,9 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId) }) ``` -## bundle.getApplicationInfo +## bundle.getApplicationInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo)替代。 getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void @@ -103,7 +106,10 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId, (err, data) => { }) ``` -## bundle.getApplicationInfo +## bundle.getApplicationInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getApplicationInfo](js-apis-bundleManager.md#bundlemanagergetapplicationinfo)替代。 + getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -139,81 +145,10 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { }) ``` -## bundle.getApplicationInfoSync9+ - -getApplicationInfoSync(bundleName: string, bundleFlags: number, userId: number): ApplicationInfo; - -以同步方法根据给定的包名获取ApplicationInfo,返回ApplicationInfo对象。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | 是 | 要查询的包名。 | -| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)中应用信息相关flag。 | -| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------------------- | ------------------- | -| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | ApplicationInfo对象 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let bundleFlags = 0; -let userId = 100; -var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags, userId); -console.info('Operation successful. Name:' + applicationInfo.name); -``` - -## bundle.getApplicationInfoSync9+ - -getApplicationInfoSync(bundleName: string, bundleFlags: number) : ApplicationInfo; -以同步方法根据给定的包名获取ApplicationInfo,返回ApplicationInfo对象。 +## bundle.getAllBundleInfodeprecated -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | 是 | 要查询的包名。 | -| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)中应用信息相关flag。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------------------- | ------------------- | -| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | ApplicationInfo对象 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let bundleFlags = 0; -var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags); -console.info('Operation successful. Name:' + applicationInfo.name); -``` - -## bundle.getAllBundleInfo +> 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> @@ -253,7 +188,10 @@ bundle.getAllBundleInfo(bundleFlag, userId) }) ``` -## bundle.getAllBundleInfo +## bundle.getAllBundleInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 + getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void @@ -287,7 +225,10 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { }) ``` -## bundle.getAllBundleInfo +## bundle.getAllBundleInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAllBundleInfo](js-apis-bundleManager.md#bundlemanagergetallbundleinfo)替代。 + getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void @@ -323,7 +264,10 @@ bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { }) ``` -## bundle.getBundleInfo +## bundle.getBundleInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)替代。 + getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Promise\ @@ -367,7 +311,9 @@ bundle.getBundleInfo(bundleName, bundleFlags, options) }) ``` -## bundle.getBundleInfo +## bundle.getBundleInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)替代。 getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -404,7 +350,9 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { ``` -## bundle.getBundleInfo +## bundle.getBundleInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)替代。 getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, callback: AsyncCallback\): void @@ -444,83 +392,11 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { }) ``` -## bundle.getBundleInfoSync9+ - -getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo; - -以同步方法根据给定的包名获取BundleInfo,返回BundleInfo对象。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | 是 | 要查询的包名。 | -| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)中包信息相关flag。 | -| options | [BundleOptions](#bundleoptions) | 是 | 指定包的选项。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------ | -------------- | -| [BundleInfo](js-apis-bundle-BundleInfo.md) | BundleInfo对象 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let bundleFlags = 1; -let options = { - "userId" : 100 -}; -var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags, options); -console.info('Operation successful. Name:' + bundleInfo.name); -``` - -## bundle.getBundleInfoSync9+ - -getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo; - -以同步方法根据给定的包名获取BundleInfo,返回BundleInfo对象。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | 是 | 要查询的包名。 | -| bundleFlags | number | 是 | 用于指定返回的应用信息对象中包含信息的标记。默认值:0,取值范围:参考[BundleFlag说明](#bundleflag)中包信息相关flag。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------ | -------------- | -| [BundleInfo](js-apis-bundle-BundleInfo.md) | BundleInfo对象 | -**示例:** -```js -let bundleName = "com.example.myapplication"; -let bundleFlags = 1; -var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags); -console.info('Operation successful. Name:' + bundleInfo.name); -``` +## bundle.getBundleInstallerdeprecated -## bundle.getBundleInstaller +> 从API version 9开始不再维护,建议使用[installer.getBundleInstaller](js-apis-installer.md#bundleinstallergetbundleinstaller)替代。 getBundleInstaller(): Promise<BundleInstaller>; @@ -544,7 +420,9 @@ SystemCapability.BundleManager.BundleFramework | ------------------------------------------------------------ | -------------------------------------------- | | Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | 返回值为Promise对象,Promise中包含安装信息。 | -## bundle.getBundleInstaller +## bundle.getBundleInstallerdeprecated + +> 从API version 9开始不再维护,建议使用[installer.getBundleInstaller](js-apis-installer.md#bundleinstallergetbundleinstaller)替代。 getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void; @@ -568,7 +446,9 @@ SystemCapability.BundleManager.BundleFramework | -------- | ------------------------------------------------------------ | ---- | ---------------- | | callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | 是 | 安装应用程序包。 | -## bundle.cleanBundleCacheFiles8+ +## bundle.cleanBundleCacheFilesdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles)替代。 cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback<void>): void; @@ -593,7 +473,9 @@ SystemCapability.BundleManager.BundleFramework | bundleName | string | 是 | 指示要清除其缓存数据的应用程序包名称. | | callback | AsyncCallback\ | 是 | 为返回操作结果而调用的回调。 | -## bundle.cleanBundleCacheFiles8+ +## bundle.cleanBundleCacheFilesdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles)替代。 cleanBundleCacheFiles(bundleName: string): Promise<void> @@ -623,7 +505,9 @@ SystemCapability.BundleManager.BundleFramework | ------------- | ------------------------------------ | | Promise\ | 返回值为Promise对象,Promise中为空。 | -## bundle.setApplicationEnabled8+ +## bundle.setApplicationEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.setApplicationEnabled](js-apis-bundleManager.md#bundlemanagersetapplicationenabled)替代。 setApplicationEnabled(bundleName: string, isEnable: boolean, callback: AsyncCallback<void>): void; @@ -649,7 +533,9 @@ SystemCapability.BundleManager.BundleFramework | isEnable | boolean | 是 | 指定是否启用应用程序。true表示启用,false禁用。 | | callback | AsyncCallback\ | 是 | 为返回操作结果而调用的回调。 | -## bundle.setApplicationEnabled8+ +## bundle.setApplicationEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.setApplicationEnabled](js-apis-bundleManager.md#bundlemanagersetapplicationenabled)替代。 setApplicationEnabled(bundleName: string, isEnable: boolean): Promise<void> @@ -680,7 +566,9 @@ SystemCapability.BundleManager.BundleFramework | ------------- | ------------------------------------ | | Promise\ | 返回值为Promise对象,Promise中为空。 | -## bundle.setAbilityEnabled8+ +## bundle.setAbilityEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.setAbilityEnabled](js-apis-bundleManager.md#bundlemanagersetabilityenabled)替代。 setAbilityEnabled(info: AbilityInfo, isEnable: boolean, callback: AsyncCallback<void>): void; @@ -706,7 +594,9 @@ SystemCapability.BundleManager.BundleFramework | isEnable | boolean | 是 | 指定是否启用应用程序。true表示启用,false禁用。 | | callback | AsyncCallback\ | 是 | 为返回操作结果而调用的回调。 | -## bundle.setAbilityEnabled8+ +## bundle.setAbilityEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.setAbilityEnabled](js-apis-bundleManager.md#bundlemanagersetabilityenabled)替代。 setAbilityEnabled(info: AbilityInfo, isEnable: boolean): Promise<void> @@ -737,7 +627,9 @@ SystemCapability.BundleManager.BundleFramework | ------------- | ------------------------------------ | | Promise\ | 返回值为Promise对象,Promise中为空。 | -## bundle.getPermissionDef8+ +## bundle.getPermissionDefdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef)替代。 getPermissionDef(permissionName: string, callback: AsyncCallback<PermissionDef>): void; @@ -762,7 +654,9 @@ SystemCapability.BundleManager.BundleFramework | permissionName | string | 是 | 指定权限的名称。 | | callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | 是 | 程序启动作为入参的回调函数,返回定义的权限信息。 | -## bundle.getPermissionDef8+ +## bundle.getPermissionDefdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef)替代。 getPermissionDef(permissionName: string): Promise<PermissionDef> @@ -792,196 +686,10 @@ SystemCapability.BundleManager.BundleFramework | ------------------------------------------------------ | ------------------------------------------------------ | | Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | 返回值为Promise对象,Promise中包含定义的权限信息对象。 | -## bundle.setModuleUpgradeFlag9+ - -setModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag, callback: AsyncCallback<void>):void; - -设置模块是否需要升级 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | --------------------------- | ---- | ---------------------------- | -| bundleName | string | 是 | 应用程序包名称。 | -| moduleName | string | 是 | 应用程序模块名称。 | -| upgradeFlag | [UpgradeFlag](#upgradeflag) | 是 | 仅供内部系统使用标志位 | -| callback | AsyncCallback\ | 是 | 为返回操作结果而调用的回调。 | - -## bundle.setModuleUpgradeFlag9+ - -setModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag): Promise<void> - -设置模块是否需要升级 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | --------------------------- | ---- | ---------------------- | -| bundleName | string | 是 | 应用程序包名称。 | -| moduleName | string | 是 | 应用程序模块名称。 | -| upgradeFlag | [UpgradeFlag](#upgradeflag) | 是 | 仅供内部系统使用标志位 | - -**返回值:** - -| 类型 | 说明 | -| ------------- | ------------------------------------ | -| Promise\ | 返回值为Promise对象,Promise中为空。 | - -## bundle.isModuleRemovable9+ - -isModuleRemovable(bundleName: string, moduleName: string, callback: AsyncCallback<boolean>): void; - -检查指定模块是否被移除 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------- | ---------------------- | ---- | --------------------------------------------- | -| bundleName | string | 是 | 应用程序包名称。 | -| moduleName | string | 是 | 应用程序模块名称。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回boolean信息。 | - -## bundle.isModuleRemovable9+ - -isModuleRemovable(bundleName: string, moduleName: string): Promise<boolean> - -检查指定模块是否被移除 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------- | ------ | ---- | ------------------ | -| bundleName | string | 是 | 应用程序包名称。 | -| moduleName | string | 是 | 应用程序模块名称。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | ---------------------------- | -| Promise\ | Promise形式返回boolean信息。 | - -## bundle.getBundlePackInfo9+ - -getBundlePackInfo(bundleName: string, bundlePackFlag : pack.BundlePackFlag, callback: AsyncCallback<pack.BundlePackInfo>): void; - -基于bundleName和bundleFlags获取bundlePackInfo - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | -| bundleName | string | 是 | 应用程序包名称。 | -| bundlePackFlag | [pack.BundlePackFlag](js-apis-bundle-PackInfo.md) | 是 | 指示要查询的应用包标志 | -| callback | AsyncCallback<[pack.BundlePackInfo](js-apis-bundle-PackInfo.md)> | 是 | 程序启动作为入参的回调函数,返回BundlePackInfo信息。 | - -## bundle.getBundlePackInfo9+ - -getBundlePackInfo(bundleName: string, bundlePackFlag : pack.BundlePackFlag): Promise<pack.BundlePackInfo>; - -基于bundleName和bundleFlags获取bundlePackInfo - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------------- | ------------------------------------------------- | ---- | ---------------------- | -| bundleName | string | 是 | 应用程序包名称。 | -| bundlePackFlag | [pack.BundlePackFlag](js-apis-bundle-PackInfo.md) | 是 | 指示要查询的应用包标志 | - -**返回值:** - -| 类型 | 说明 | -| ---------------------------------------------------------- | ----------------------------------- | -| Promise<[pack.BundlePackInfo](js-apis-bundle-PackInfo.md)> | Promise形式返回BundlePackInfo信息。 | - -## bundle.getDispatcherVersion9+ - -getDispatcherVersion(callback: AsyncCallback<DispatchInfo>): void; - -获取有关dispatcher版本的信息 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[DispatchInfo](js-apis-dispatchInfo.md)> | 是 | 程序启动作为入参的回调函数,返回[DispatchInfo](js-apis-dispatchInfo.md)信息。 | - -## bundle.getDispatcherVersion9+ - -getDispatcherVersion(): Promise<DispatchInfo>; - -获取有关dispatcher版本的信息 - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**系统API:** - -此接口为系统接口,三方应用不支持调用 - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------ | ------------------------------------------------------------ | -| Promise<[DispatchInfo](js-apis-dispatchInfo.md)> | Promise形式返回[DispatchInfo](js-apis-dispatchInfo.md)信息。 | +## bundle.getAllApplicationInfodeprecated -## bundle.getAllApplicationInfo +> 从API version 9开始不再维护,建议使用[bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo)替代。 getAllApplicationInfo(bundleFlags: number, userId?: number): Promise> @@ -1021,9 +729,9 @@ bundle.getAllApplicationInfo(bundleFlags, userId) }) ``` +## bundle.getAllApplicationInfodeprecated - -## bundle.getAllApplicationInfo +> 从API version 9开始不再维护,建议使用[bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo)替代。 getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void @@ -1060,7 +768,9 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ``` -## bundle.getAllApplicationInfo +## bundle.getAllApplicationInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo)替代。 getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; @@ -1094,7 +804,9 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { }) ``` -## bundle.getBundleArchiveInfo +## bundle.getBundleArchiveInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleArchiveInfo](js-apis-bundleManager.md#bundlemanagergetbundlearchiveinfo)替代。 getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise\ @@ -1129,7 +841,9 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) }) ``` -## bundle.getBundleArchiveInfo +## bundle.getBundleArchiveInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleArchiveInfo](js-apis-bundleManager.md#bundlemanagergetbundlearchiveinfo)替代。 getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback\) : void @@ -1162,7 +876,9 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { ``` -## bundle.getAbilityInfo +## bundle.getAbilityInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 getAbilityInfo(bundleName: string, abilityName: string): Promise\ @@ -1202,7 +918,9 @@ bundle.getAbilityInfo(bundleName, abilityName) }) ``` -## bundle.getAbilityInfo +## bundle.getAbilityInfodeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\): void; @@ -1237,91 +955,14 @@ bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { console.info('Operation successful. Data:' + JSON.stringify(data)); }) ``` -## bundle.getAbilityInfo9+ -getAbilityInfo(bundleName: string, moduleName: string, abilityName: string): Promise\ +## bundle.getAbilityLabeldeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityLabel](js-apis-bundleManager.md#bundlemanagergetabilitylabel)替代。 + +getAbilityLabel(bundleName: string, abilityName: string): Promise\ -通过包名称、moduleName和abilityName获取Ability信息,使用Promise形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | 是 | 应用程序包名。 | -| moduleName | string | 是 | Module名称。 | -| abilityName | string | 是 | Ability名称。 | - -**返回值:** - -| 类型 | 说明 | -| --------------------- | --------------------- | -| Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise形式返回Ability信息。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityInfo(bundleName, moduleName, abilityName) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - -## bundle.getAbilityInfo9+ - -getAbilityInfo(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void; - -通过包名称、moduleName和abilityName获取Ability信息,使用callback形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------------ | ---- | ---------------- | -| bundleName | string | 是 | 应用程序包名。 | -| moduleName | string | 是 | Module名称。 | -| abilityName | string | 是 | Ability名称。 | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | 是 | 程序启动作为入参的回调函数,返回Ability信息。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityInfo(bundleName, moduleName, abilityName, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - -## bundle.getAbilityLabel8+ - -getAbilityLabel(bundleName: string, abilityName: string): Promise\ - -通过包名称和abilityName获取应用名称,使用Promise形式返回结果。 +通过包名称和abilityName获取应用名称,使用Promise形式返回结果。 **需要权限:** @@ -1357,7 +998,9 @@ bundle.getAbilityLabel(bundleName, abilityName) }) ``` -## bundle.getAbilityLabel8+ +## bundle.getAbilityLabeldeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityLabel](js-apis-bundleManager.md#bundlemanagergetabilitylabel)替代。 getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallback\): void @@ -1392,87 +1035,10 @@ bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { console.info('Operation successful. Data:' + JSON.stringify(data)); }) ``` -## bundle.getAbilityLabel9+ - -getAbilityLabel(bundleName: string, moduleName: string, abilityName: string): Promise\ -通过包名称、moduleName和abilityName获取应用名称,使用Promise形式返回结果。 +## bundle.isAbilityEnableddeprecated -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | 是 | 应用程序包名。 | -| moduleName | string | 是 | Module名称。 | -| abilityName | string | 是 | Ability名称。 | - -**返回值:** - -| 类型 | 说明 | -| ---------------- | ------------------ | -| Promise\ | Promise形式返回应用名称信息。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityLabel(bundleName, moduleName, abilityName) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - -## bundle.getAbilityLabel9+ - -getAbilityLabel(bundleName: string, moduleName: string, abilityName: string, callback : AsyncCallback\): void - -通过包名称、moduleName和abilityName获取应用名称,使用callback形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | 是 | 应用程序包名。 | -| moduleName | string | 是 | Module名称。 | -| abilityName | string | 是 | Ability名称。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回应用名称信息。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityLabel(bundleName, moduleName, abilityName, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - -## bundle.isAbilityEnabled8+ +> 从API version 9开始不再维护,建议使用[bundleManager.isAbilityEnabled](js-apis-bundleManager.md#bundlemanagerisabilityenabled)替代。 isAbilityEnabled(info: AbilityInfo): Promise\ @@ -1508,7 +1074,9 @@ bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ }) ``` -## bundle.isAbilityEnabled8+ +## bundle.isAbilityEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.isAbilityEnabled](js-apis-bundleManager.md#bundlemanagerisabilityenabled)替代。 isAbilityEnabled(info : AbilityInfo, callback : AsyncCallback\): void @@ -1541,7 +1109,9 @@ bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ }) ``` -## bundle.isApplicationEnabled8+ +## bundle.isApplicationEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.isApplicationEnabled](js-apis-bundleManager.md#bundlemanagerisapplicationenabled)替代。 isApplicationEnabled(bundleName: string): Promise\ @@ -1575,7 +1145,9 @@ bundle.isApplicationEnabled(bundleName) }) ``` -## bundle.isApplicationEnabled8+ +## bundle.isApplicationEnableddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.isApplicationEnabled](js-apis-bundleManager.md#bundlemanagerisapplicationenabled)替代。 isApplicationEnabled(bundleName: string, callback : AsyncCallback\): void @@ -1605,7 +1177,9 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { }) ``` -## bundle.queryAbilityByWant +## bundle.queryAbilityByWantdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> @@ -1652,7 +1226,9 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) -## bundle.queryAbilityByWant +## bundle.queryAbilityByWantdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback>): void @@ -1693,7 +1269,9 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { }) ``` -## bundle.queryAbilityByWant +## bundle.queryAbilityByWantdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.queryAbilityInfo](js-apis-bundleManager.md#bundlemanagerqueryabilityinfo)替代。 queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; @@ -1734,7 +1312,9 @@ bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { -## bundle.getLaunchWantForBundle +## bundle.getLaunchWantForBundledeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getLaunchWantForBundle](js-apis-bundleManager.md#bundlemanagergetlaunchwantforbundle)替代。 getLaunchWantForBundle(bundleName: string): Promise\ @@ -1771,7 +1351,9 @@ bundle.getLaunchWantForBundle(bundleName) }) ``` -## bundle.getLaunchWantForBundle +## bundle.getLaunchWantForBundledeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getLaunchWantForBundle](js-apis-bundleManager.md#bundlemanagergetlaunchwantforbundle)替代。 getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; @@ -1806,7 +1388,9 @@ bundle.getLaunchWantForBundle(bundleName, (err, data) => { ``` -## bundle.getNameForUid8+ +## bundle.getNameForUiddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleNameByUid](js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid)替代。 getNameForUid(uid: number): Promise\ @@ -1839,7 +1423,9 @@ bundle.getNameForUid(uid) }) ``` -## bundle.getNameForUid8+ +## bundle.getNameForUiddeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getBundleNameByUid](js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid)替代。 getNameForUid(uid: number, callback: AsyncCallback\) : void @@ -1870,7 +1456,9 @@ bundle.getNameForUid(uid, (err, data) => { ``` -## bundle.getAbilityIcon8+ +## bundle.getAbilityIcondeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon)替代。 getAbilityIcon(bundleName: string, abilityName: string): Promise\; @@ -1909,7 +1497,9 @@ bundle.getAbilityIcon(bundleName, abilityName) }) ``` -## bundle.getAbilityIcon8+ +## bundle.getAbilityIcondeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.getAbilityIcon](js-apis-bundleManager.md#bundlemanagergetabilityicon)替代。 getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; @@ -1945,487 +1535,8 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { }) ``` -## bundle.getAbilityIcon9+ - -getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise\; - -以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用Promise形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 要查询的bundleName。 | -| moduleName | string | 是 | moduleName。 | -| abilityName | string | 是 | 要查询的abilityName。 | - -**返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------------------------------------------ | -| Promise\ | 返回值为[PixelMap](js-apis-image.md)。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityIcon(bundleName, moduleName, abilityName) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - -## bundle.getAbilityIcon9+ - -getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void; - -以异步方法通过bundleName、moduleName和abilityName获取对应Icon的[PixelMap](js-apis-image.md),使用callback形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 要查询的bundleName。 | -| moduleName | string | 是 | moduleName。 | -| abilityName | string | 是 | 要查询的abilityName。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回指定[PixelMap](js-apis-image.md)。 | - -**示例:** - -```js -let bundleName = "com.example.myapplication"; -let moduleName = "entry"; -let abilityName = "com.example.myapplication.MainAbility"; -bundle.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - -## bundle.queryExtensionAbilityInfos9+ - -queryExtensionAbilityInfos(want: Want, extensionType: number, extensionFlags: number, userId?: number): Promise> - -以异步方法根据给定的意图获取ExtensionAbility信息,使用Promise形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------------- | ------ | ---- | ---------------------------------------- | -| want | [Want](js-apis-application-Want.md) | 是 | 包含要查询的应用程序包名称的意图。 | -| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) | -| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9) | -| userId | number | 否 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | ------------------------------ | -| Promise> | Promise形式返回ExtensionAbility信息。 | - -**示例:** - -```js -let extensionType = 0; -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfos(want, extensionType, extensionFlags, userId) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - - - -## bundle.queryExtensionAbilityInfos9+ - -queryExtensionAbilityInfos(want: Want, extensionType: number, extensionFlags: number, userId: number, callback: AsyncCallback>): void - -以异步方法根据给定的意图获取指定用户下的ExtensionAbility信息,使用callback形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | 是 | 指示包含要查询的应用程序包名称的意图。 | -| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) | -| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9)| -| userId | number | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0 | -| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 | - -**示例:** - -```js -let extensionType = 0; -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -const receiver = function onReceive(err, data) { - var errValue = JSON.stringify(err) - var dataValue = JSON.stringify(data) - console.error('Operation failed. Cause: ' + errValue); - console.error('Operation failed. Cause: ' + dataValue); -} -bundle.queryExtensionAbilityInfos(want, extensionType, extensionFlags, userId, receiver) -``` - -## bundle.queryExtensionAbilityInfos9+ - -queryExtensionAbilityInfos(want: Want, extensionType: number, extensionFlags: number, callback: AsyncCallback>): void; - -以异步方法根据给定的意图获取ExtensionAbility信息,使用callback形式返回结果。 - -**需要权限:** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED 或 ohos.permission.GET_BUNDLE_INFO - -**系统能力:** - -SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| -------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| want | [Want](js-apis-application-Want.md) | 是 | 指示包含要查询的应用程序包名称的意图。 | -| extensionType | number | 是 | 用于指定查找的extensionAbilityInfo的类型。 默认值:0,取值范围:枚举值: [ExtensionAbilityType](#extensionabilitytype9) | -| extensionFlags | number | 是 | 用于指定返回ExtensionAbilityInfo信息。默认值:0,取值范围:枚举值: [ExtensionFlags](#extensionflag9) | -| callback | AsyncCallback> | 是 | 程序启动作为入参的回调函数,返回ExtensionAbility信息。 | - -**示例:** - -```js -let extensionType = 0; -let extensionFlags = 0; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -const receiver = function onReceive(err, data) { - var errValue = JSON.stringify(err) - var dataValue = JSON.stringify(data) - console.error('Operation failed. Cause: ' + errValue); - console.error('Operation failed. Cause: ' + dataValue); -} -bundle.queryExtensionAbilityInfos(want, extensionType, extensionFlags, receiver) -``` - -## bundle.getProfileByAbility9+ - -getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\>): void; - -以异步方法根据给定的moduleName,abilityName,metadataName来获取[metadata](js-apis-bundle-Metadata.md)中的配置文件的json字符串,使用callback形式返回结果。 该接口只能用来获取当前应用的配置文件的json字符串,不能在当前应用获取其他应用的配置文件json字符串。 - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | -| abilityName | string | 是 | 表示要获取的配置文件所属的ability。 | -| metadataName | string | 是 | 表示要获取的配置文件所属的metadata。 | -| callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回配置文件的json字符串数组。 | - -**示例:** - -```js -let moduleName = 'entry'; -let abilityName = 'MainAbility'; -let metadataName = 'ohos.ability.shortcuts'; -const caller = function callback(err, data) { - console.error('Operation errcode is: ' + err); - console.error('Operation result is: ' + data); -} -bundle.getProfileByAbility(moduleName, abilityName, metadataName, caller) -``` - -## bundle.getProfileByAbility9+ - -getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise\>; - -以异步方法根据给定的moduleName,abilityName,metadataName来获取[metadata](js-apis-bundle-Metadata.md)中的配置文件的json字符串,使用Promise形式返回结果。 该接口只能用来获取当前应用的配置文件的json字符串,不能在当前应用获取其他应用的配置文件json字符串。 - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | -| abilityName | string | 是 | 表示要获取的配置文件所属的ability。 | -| metadataName | string | 否 | 表示要获取的配置文件所属的metadata。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | ------------------------------ | -| Promise\> | Promise形式返回配置文件的json字符串数组。 | - -**示例:** - -```js -let moduleName = 'entry'; -let abilityName = 'MainAbility'; -let metadataName = 'ohos.ability.shortcuts'; - -bundle.getProfileByAbility(moduleName, abilityName, metadataName).then(data=>{ - console.error('Operation result is: ' + data); -}).catch(err=>{ - console.error('Operation errcode is: ' + err); -}) -``` - -## bundle.getProfileByExtensionAbility9+ - -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\>): void; - -以异步方法根据给定的moduleName,extensionAbilityName,metadataName来获取[metadata](js-apis-bundle-Metadata.md)中的配置文件的json字符串,使用callback形式返回结果。 该接口只能用来获取当前应用的配置文件的json字符串,不能在当前应用获取其他应用的配置文件json字符串。 - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | -| extensionAbilityName | string | 是 | 表示要获取的配置文件所属的extensionAbility。 | -| metadataName | string | 是 | 表示要获取的配置文件所属的metadata。 | -| callback | AsyncCallback\> | 是 | 程序启动作为入参的回调函数,返回配置文件的json字符串数组。 | - -**示例:** - -```js -let moduleName = 'entry'; -let extensionAbilityName = 'Form'; -let metadataName = 'ohos.extension.form'; -const caller = function callback(err, data) { - console.error('Operation errcode is: ' + err); - console.error('Operation result is: ' + data); -} -bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName, caller) -``` - -## bundle.getProfileByExtensionAbility9+ - -getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise\>; - -以异步方法根据给定的moduleName,extensionAbilityName,metadataName来获取[metadata](js-apis-bundle-Metadata.md)中的配置文件的json字符串,使用Promise形式返回结果。 该接口只能用来获取当前应用的配置文件的json字符串,不能在当前应用获取其他应用的配置文件json字符串。 - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| moduleName | string | 是 | 表示要获取的配置文件所属的module。 | -| extensionAbilityName | string | 是 | 表示要获取的配置文件所属的extensionAbility。 | -| metadataName | string | 否 | 表示要获取的配置文件所属的metadata。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | ------------------------------ | -| Promise\> | Promise形式返回配置文件的json字符串数组。 | - -**示例:** - -```js -let moduleName = 'entry'; -let extensionAbilityName = 'Form'; -let metadataName = 'ohos.extension.form'; - -bundle.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName).then(data=>{ - console.error('Operation result is: ' + data); -}).catch(err=>{ - console.error('Operation errcode is: ' + err); -}) -``` - -## bundle.setDisposedStatus9+ - -setDisposedStatus(bundleName: string, status: number, callback: AsyncCallback\): void; - -以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用callback形式返回结果。 - -**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 表示要被设置处置状态的应用包名。 | -| status | number | 是 | 表示要设置的处置状态值。该值预留用于应用市场设置应用的处置状态,默认为0,不做处置。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,无返回值。 | - -**示例:** - -```js -let bundleName = 'com.ohos.camera'; -let status = 1; -const caller = function callback(err, data) { - console.error('Operation err is: ' + err); - console.error('Operation result is: ' + data); -} -bundle.setDisposedStatus(bundleName, status, caller) -``` - -## bundle.setDisposedStatus9+ - -setDisposedStatus(bundleName: string, status: number): Promise\; - -以异步方法根据给定的bundleName和status来设置对应应用的处置状态,使用Promise形式返回结果。 - -**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 表示要被设置处置状态的应用包名。 | -| status | number | 是 | 表示要设置的处置状态值。该值预留用于应用市场设置应用的处置状态,默认为0,不做处置。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | ------------------------------ | -| Promise\ | Promise形式,无返回值。 | - -**示例:** - -```js -let bundleName = 'com.ohos.camera'; -let status = 1; - -bundle.setDisposedStatus(bundleName, status).then(data=>{ - console.error('Operation result is: ' + data); -}).catch(err=>{ - console.error('Operation err is: ' + err); -}) -``` - -## bundle.getDisposedStatus9+ - -getDisposedStatus(bundleName: string, callback: AsyncCallback\): void; - -以异步方法根据给定的bundleName来获取对应应用的处置状态,使用callback形式返回结果。 - -**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 表示要获取处置状态的应用包名。 | -| callback | AsyncCallback\ | 是 | 程序启动作为入参的回调函数,返回应用的处置状态值。 | - -**示例:** - -```js -let bundleName = 'com.ohos.camera'; -const caller = function callback(err, data) { - console.error('Operation err is: ' + err); - console.error('Operation result is: ' + data); -} -bundle.getDisposedStatus(bundleName, caller) -``` - -## bundle.getDisposedStatus9+ - -getDisposedStatus(bundleName: string): Promise\; - -以异步方法根据给定的bundleName来获取对应应用的处置状态,使用Promise形式返回结果。 - -**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**系统能力:** SystemCapability.BundleManager.BundleFramework - -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**参数:** - -| 名称 | 类型 | 必填 | 描述 | -| ---------------- | ---------------------------------- | ---- | ---------------------------------------- | -| bundleName | string | 是 | 表示要获取处置状态的应用包名。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------- | ------------------------------ | -| Promise\ | Promise返回应用的处置状态。 | - -**示例:** - -```js -let bundleName = 'com.ohos.camera'; - -bundle.getDisposedStatus(bundleName).then(data=>{ - console.error('Operation result is: ' + data); -}).catch(err=>{ - console.error('Operation err is: ' + err); -}) -``` - -## InstallErrorCode +## InstallErrorCodedeprecated +> 从API version 9开始不再维护,不推荐使用。 **系统能力:** SystemCapability.BundleManager.BundleFramework @@ -2452,7 +1563,9 @@ bundle.getDisposedStatus(bundleName).then(data=>{ | STATUS_INSTALL_PERMISSION_DENIED8+ | 0x44 | 安装权限拒绝 | | STATUS_UNINSTALL_PERMISSION_DENIED8+ | 0x45 | 卸载权限拒绝 | -## BundleFlag +## BundleFlagdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.BundleFlag](js-apis-bundleManager.md#bundleflag)替代。 包的标志 @@ -2467,16 +1580,14 @@ bundle.getDisposedStatus(bundleName).then(data=>{ | GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | 获取包括权限的应用信息 | | GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | 获取包括所需权限的包信息 | | GET_ABILITY_INFO_WITH_METADATA8+ | 0x00000020 | 获取ability的元数据信息 | -| GET_BUNDLE_WITH_EXTENSION_ABILITY9+ | 0x00000020 | 获取包括Ability信息的扩展包信息 | | GET_APPLICATION_INFO_WITH_METADATA8+ | 0x00000040 | 获取应用的元数据信息 | | GET_ABILITY_INFO_SYSTEMAPP_ONLY8+ | 0x00000080 | 获取仅包括系统应用的ability信息 | | GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | 获取包括被禁用的ability信息 | | GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | 获取包括被禁用的应用信息 | -| GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT 9+ | 0x00000400 | 获取包括应用申请的签名证书的指纹信息 | | GET_ALL_APPLICATION_INFO | 0xFFFF0000 | 获取应用所有的信息 | -| GET_BUNDLE_WITH_HASH_VALUE9+ | 0x00000030 | 获取包含Hash值的包信息. | -## BundleOptions +## BundleOptionsdeprecated +> 从API version 9开始不再维护,不推荐使用。 包的选项 @@ -2486,7 +1597,9 @@ bundle.getDisposedStatus(bundleName).then(data=>{ | ------ | ------ | ---- | ---- | ---------------------------- | | userId | number | 是 | 是 | 用户ID。默认值:调用方所在用户,取值范围:大于等于0。 | -## AbilityType +## AbilityTypedeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.AbilityType](js-apis-bundleManager.md#abilitytype)替代。 Ability类型 @@ -2499,7 +1612,9 @@ Ability类型 | SERVICE | 无 | Ability没有UI界面 | | DATA | 无 | Ability用于提供数据访问服务 | -## DisplayOrientation +## DisplayOrientationdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.DisplayOrientation](js-apis-bundleManager.md#displayorientation)替代。 屏幕显示方向 @@ -2511,16 +1626,9 @@ Ability类型 | LANDSCAPE | 无 | 屏幕方向--横屏 | | PORTRAIT | 无 | 屏幕方向--竖屏 | | FOLLOW_RECENT | 无 | 屏幕方向--紧跟上一个组件 | -| LANDSCAPE_INVERTED9+ |无 | 屏幕方向--反向横屏 | -| PORTRAIT_INVERTED9+ |无 | 屏幕方向--反向竖屏 | -| AUTO_ROTATION9+ |无 | 屏幕方向--随传感器旋转 | -| AUTO_ROTATION_LANDSCAPE9+ |无 | 屏幕方向--传感器横屏旋转,包括了横屏和反向横屏 | -| AUTO_ROTATION_PORTRAIT9+ |无 | 屏幕方向--传感器竖屏旋转,包括了竖屏和反向竖屏 | -| AUTO_ROTATION_RESTRICTED9+ |无 | 屏幕方向--传感器开关打开,方向可随传感器旋转 | -| AUTO_ROTATION_LANDSCAPE_RESTRICTED9+ |无 | 屏幕方向--传感器开关打开,方向可随传感器旋转为横屏, 包括了横屏和反向横屏 | -| AUTO_ROTATION_PORTRAIT_RESTRICTED9+ |无 | 屏幕方向--传感器开关打开,方向随可传感器旋转为竖屏, 包括了横屏和反向横屏 | -| LOCKED9+ |无 | 屏幕方向--传感器开关关闭,方向锁定 | -## LaunchMode +## LaunchModedeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.LaunchType](js-apis-bundleManager.md#launchtype)替代。 启动模式 @@ -2531,7 +1639,8 @@ Ability类型 | SINGLETON | 0 | Ability只有一个示例 | | STANDARD | 1 | Ability有多个示例 | -## AbilitySubType +## AbilitySubTypedeprecated +> 从API version 9开始不再维护,不推荐使用。 Ability的子类型 @@ -2542,44 +1651,8 @@ Ability的子类型 | UNSPECIFIED | 0 | 未定义Ability子类型 | | CA | 1 | Ability子类型是带有 UI 的服务 | -## ExtensionAbilityType9+ - -ExtensionAbility的类型 - - **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - -| 名称 | 类型 | 说明 | -| ------------------------------ | ---- | ------------------------- | -| FORM9+ | 0 | ExtensionAbility的类型包括卡片 | -| WORK_SCHEDULER9+ | 1 | ExtensionAbility的类型包括行程安排 | -| INPUT_METHOD9+ | 2 | ExtensionAbility的类型包括输入法 | -| SERVICE9+ | 3 | ExtensionAbility的类型包括服务 | -| ACCESSIBILITY9+ | 4 | ExtensionAbility的类型包括无障碍 | -| DATA_SHARE9+ | 5 | ExtensionAbility的类型包括数据共享 | -| FILE_SHARE9+ | 6 | ExtensionAbility的类型包括文件共享 | -| STATIC_SUBSCRIBER9+ | 7 | ExtensionAbility的类型包括订阅者 | -| WALLPAPER9+ | 8 | ExtensionAbility的类型包括墙纸 | -| BACKUP9+ | 9 | ExtensionAbility的类型包括数据备份恢复 | -| WINDOW9+ | 10 | ExtensionAbility的类型包括窗口类型扩展信息 | -| ENTERPRISE_ADMIN9+ | 11 | ExtensionAbility的类型包括企业管理员 | -| THUMBNAIL9+ | 13 | ExtensionAbility的类型包括缩略图 | -| PREVIEW9+ | 14 | ExtensionAbility的类型包括预览 | -| UNSPECIFIED9+ | 255 | ExtensionAbility未指定类型 | - -## ExtensionFlag9+ - -扩展标志 - - **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - -| 名称 | 默认值 | 说明 | -| ---------------------------------------- | ---------- | ------------------------------ | -| GET_EXTENSION_INFO_DEFAULT9+ | 0x00000000 | 获取默认的extensionAbilityInfo | -| GET_EXTENSION_INFO_WITH_PERMISSION9+ | 0x00000002 | 获取携带权限信息的extensionAbilityInfo | -| GET_EXTENSION_INFO_WITH_APPLICATION9+ | 0x00000004 | 获取携带应用信息的extensionAbilityInfo | -| GET_EXTENSION_INFO_WITH_METADATA9+ | 0x00000020 | 获取携带元数据信息的extensionAbilityInfo | - -## ColorMode +## ColorModedeprecated +> 从API version 9开始不再维护,不推荐使用。 颜色模式 @@ -2592,7 +1665,9 @@ ExtensionAbility的类型 | LIGHT_MODE | 1 | 亮度模式 | -## GrantStatus +## GrantStatusdeprecated + +> 从API version 9开始不再维护,建议使用[bundleManager.PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)替代。 授予状态 @@ -2601,30 +1676,4 @@ ExtensionAbility的类型 | 名称 | 类型 | 说明 | | ------------------ | ---- | ---- | | PERMISSION_DENIED | -1 | 拒绝许可 | -| PERMISSION_GRANTED | 0 | 批准 | - -## SupportWindowMode - -支持窗口模式 - - **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - -| 名称 | 类型 | 说明 | -| ------------------ | ---- | ---- | -| FULL_SCREEN9+ | 0 | 全屏模式 | -| SPLIT9+ | 1 | 分屏模式 | -| FLOATING9+ | 2 | 悬浮模式 | - -## UpgradeFlag - -此项仅供内部系统使用 - -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - -| 名称 | 值 | 说明 | -| ----------------------------- | ---- | ---------------- | -| NOT_UPGRADE9+ | 0 | 模块无需升级 | -| SINGLE_UPGRADE9+ | 1 | 单个模块需要升级 | -| RELATION_UPGRADE9+ | 2 | 关系模块需要升级 | +| PERMISSION_GRANTED | 0 | 批准 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-Want.md b/zh-cn/application-dev/reference/apis/js-apis-ability-Want.md new file mode 100644 index 0000000000000000000000000000000000000000..dd0fb019c7241ea9b66dc1ef79d5d8812acb0f4a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-Want.md @@ -0,0 +1,65 @@ +# Want6+ + +Want是对象间信息传递的载体, 可以用于应用组件间的信息传递。 Want的使用场景之一是作为startAbility的参数, 其包含了指定的启动目标, 以及启动时需携带的相关数据, 如bundleName和abilityName字段分别指明目标Ability所在应用的包名以及对应包内的Ability名称。当Ability A需要启动Ability B并传入一些数据时, 可使用Want作为载体将这些数据传递给Ability B。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 读写属性 | 类型 | 必填 | 描述 | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | 只读 | string | 否 | 表示运行指定Ability的设备ID。 | +| bundleName | 只读 | string | 否 | 表示包名。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | +| abilityName | 只读 | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | +| uri | 只读 | string | 否 | 表示Uri。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | +| type | 只读 | string | 否 | 表示MIME type类型,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | +| flags | 只读 | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-featureAbility.md#flags说明)。 | +| action | 只读 | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。 | +| parameters | 只读 | {[key: string]: any} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | +| entities | 只读 | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | +| moduleName9+ | 只读 | string | 否 | 表示待启动的Ability所属的模块(module)。 | + +具体字段描述参考ability/want.d.ts文件 + +**示例:** + +- 基础用法 + + ``` ts + var want = { + "deviceId": "", // deviceId为空表示本设备 + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName非必选 + }; + this.context.startAbility(want, (error) => { + // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability + console.log("error.code = " + error.code) + }) + ``` + +- 传递FD数据,FD表示文件描述符(FileDescriptor) + + ``` ts + import fileio from '@ohos.fileio'; + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // deviceId为空表示本设备 + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry", // moduleName非必选 + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability + console.log("error.code = " + error.code) + }) + ``` + + + diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..5ff48efe1904e054c0fbefc92707039ba14a350a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md @@ -0,0 +1,38 @@ +# Ability + +Ability模块将二级模块API组织在一起方便开发者进行导出。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口仅可在FA模型下使用 + +## 导入模块 + +```ts +import ability from '@ohos.ability.ability' +``` + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 读写属性 | 类型 | 必填 | 描述 | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| DataAbilityHelper | 只读 | number | 否 | DataAbilityHelper二级模块。 | +| PacMap | 只读 | Want | 否 | PacMap二级模块。 | +| DataAbilityOperation | 只读 | Want | 否 | DataAbilityOperation二级模块。 | +| DataAbilityResult | 只读 | Want | 否 | DataAbilityResult二级模块。 | +| AbilityResult | 只读 | Want | 否 | AbilityResult二级模块。 | +| ConnectOptions | 只读 | Want | 否 | ConnectOptions二级模块。 | +| StartAbilityParameter | 只读 | Want | 否 | StartAbilityParameter二级模块。 | + +**示例:** + + ```ts + let dataAbilityHelper: ability.DataAbilityHelper; + let pacMap: ability.PacMap; + let dataAbilityOperation: ability.DataAbilityOperation; + let dataAbilityResult: ability.DataAbilityResult; + let abilityResult: ability.AbilityResult; + let connectOptions: ability.ConnectOptions; + let startAbilityParameter: ability.StartAbilityParameter; + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-abilityResult.md b/zh-cn/application-dev/reference/apis/js-apis-ability-abilityResult.md new file mode 100644 index 0000000000000000000000000000000000000000..2305ac5a20596fb301c4857eccccaaa840dc9311 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-abilityResult.md @@ -0,0 +1,22 @@ +# AbilityResult7+ + +定义ability拉起、销毁之后返回的结果码和数据。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 读写属性 | 类型 | 必填 | 描述 | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| resultCode | 只读 | number | 否 | 表示ability拉起、销毁之后返回的结果码。 | +| want | 只读 | [Want](js-apis-ability-Want.md) | 否 | 表示ability销毁之后返回的数据。 | + +**示例:** + ```ts + let want = { + bundleName: 'com.example.mydocapplication', + abilityName: 'MainAbility', + }; + this.context.startAbilityForResult(want, (error, data) => { + let resultCode = data.resultCode; + let want = data.want; + }); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md index 4b64eed4162a4bbc9db8cf10e6d4e97c42be8eaa..89222edbdadcf8a22f074e101cd4927d9751da6a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-ability-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-ability-context.md @@ -13,11 +13,13 @@ AbilityContext模块提供允许访问特定Ability的资源的能力,包括 在使用AbilityContext的功能前,需要通过Ability子类实例获取。 -```js -import Ability from '@ohos.application.Ability'; +```ts +import Ability from '@ohos.app.ability.UIAbility'; + + let context = undefined; class MainAbility extends Ability { onWindowStageCreate(windowStage) { - let context = this.context; + context = this.context; } } ``` @@ -47,17 +49,54 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; - this.context.startAbility(want, (error) => { - console.log("error.code = " + error.code) - }) + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -77,22 +116,59 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) - ``` + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` ## AbilityContext.startAbility @@ -115,23 +191,57 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; | -------- | -------- | | Promise<void> | Promise形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; var options = { windowMode: 0, }; - this.context.startAbility(want, options) - .then(() => { - console.log('Operation successful.') - }).catch((error) => { - console.log('Operation failed.'); - }) + + try { + this.context.startAbility(want, options) + .then((data) => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -139,7 +249,7 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -启动Ability并在结束的时候返回执行结果(callback形式)。 +启动Ability并在该Ability退出的时候返回执行结果(callback形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -150,24 +260,63 @@ startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): | want |[Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | 是 | 执行结果回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **示例:** - ```js - this.context.startAbilityForResult( - {deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; + + try { + this.context.startAbilityForResult(want, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityForResult startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -启动Ability并在结束的时候返回执行结果(callback形式)。 +启动Ability并在该Ability退出的时候返回执行结果(callback形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -179,20 +328,59 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | 是 | 执行结果回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **示例:** - ```js + ```ts + var want = { + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" + }; var options = { windowMode: 0, }; - this.context.startAbilityForResult( - {deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); + + try { + this.context.startAbilityForResult(want, options, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -200,7 +388,7 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -启动Ability并在结束的时候返回执行结果(promise形式)。 +启动Ability并在该Ability退出的时候返回执行结果(promise形式)。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -218,17 +406,57 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityRes | -------- | -------- | | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise形式返回执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; var options = { - windowMode: 0, + windowMode: 0, }; - this.context.startAbilityForResult({deviceId: "", bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { - console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) - }, (error) => { - console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) - }) + + try { + this.context.startAbilityForResult(want, options) + .then((result) => { + // 执行正常业务 + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityForResultWithAccount @@ -251,19 +479,58 @@ startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncC | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数,返回Ability结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err, data) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - console.log('---------- startAbilityWithAccount success, data: -----------', data); - }); + + try { + this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -288,21 +555,61 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOp | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityForResultWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error, result) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -332,25 +639,61 @@ startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartO | -------- | -------- | | Promise<AbilityResult> | 返回一个Promise,包含Ability结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityForResultWithAccount(want, accountId, options) - .then((data) => { - console.log('---------- startAbilityForResultWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result) => { + // 执行正常业务 + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbility @@ -369,17 +712,48 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want, (err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbility @@ -398,22 +772,50 @@ startServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want) - .then(() => { - console.log('---------- startServiceExtensionAbility success -----------'); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` + ## AbilityContext.startServiceExtensionAbilityWithAccount startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; @@ -434,18 +836,46 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startServiceExtensionAbilityWithAccount @@ -467,22 +897,50 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId) - .then(() => { - console.log('---------- startServiceExtensionAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbility @@ -501,17 +959,45 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want, (err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbility @@ -530,21 +1016,45 @@ stopServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | -------- | -------- | | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want) - .then(() => { - console.log('---------- stopServiceExtensionAbility success -----------'); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbilityWithAccount @@ -567,18 +1077,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.stopServiceExtensionAbilityWithAccount @@ -600,22 +1139,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId) - .then(() => { - console.log('---------- stopServiceExtensionAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.terminateSelf @@ -632,11 +1196,29 @@ terminateSelf(callback: AsyncCallback<void>): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | 是 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + this.context.terminateSelf((error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('terminateSelf succeed'); }); ``` @@ -655,13 +1237,27 @@ terminateSelf(): Promise<void>; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf().then(() => { - console.log('success'); + ```ts + this.context.terminateSelf().then((data) => { + // 执行正常业务 + console.log('terminateSelf succeed'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); }); ``` @@ -681,12 +1277,23 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | 是 | 返回给调用startAbilityForResult 接口调用方的相关信息。 | | callback | AsyncCallback<void> | 是 | callback形式返回停止结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "bundleName": "com.extreme.myapplication", - "abilityName": "SecondAbility" + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" } var resultCode = 100; // 返回给接口调用方AbilityResult信息 @@ -694,10 +1301,23 @@ terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<voi want, resultCode } - this.context.terminateSelfWithResult(abilityResult, (error) => { - console.log("terminateSelfWithResult is called = " + error.code) + + try { + this.context.terminateSelfWithResult(abilityResult, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; } - ); + // 执行正常业务 + console.log('terminateSelfWithResult succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -721,12 +1341,24 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; | -------- | -------- | | Promise<void> | promise形式返回停止结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + + **示例:** - ```js + ```ts var want = { - "bundleName": "com.extreme.myapplication", - "abilityName": "SecondAbility" + bundleName: "com.extreme.myapplication", + abilityName: "SecondAbility" } var resultCode = 100; // 返回给接口调用方AbilityResult信息 @@ -734,15 +1366,28 @@ terminateSelfWithResult(parameter: AbilityResult): Promise<void>; want, resultCode } - this.context.terminateSelfWithResult(abilityResult).then((result) => { - console.log("terminateSelfWithResult") + + try { + this.context.terminateSelfWithResult(abilityResult) + .then((data) => { + // 执行正常业务 + console.log('terminateSelfWithResult succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); } - ) ``` -## AbilityContext.connectAbility +## AbilityContext.connectServiceExtensionAbility -connectAbility(want: Want, options: ConnectOptions): number; +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板将当前Ability连接到一个Ability。 @@ -763,27 +1408,46 @@ connectAbility(want: Want, options: ConnectOptions): number; | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbility(want, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.connectAbilityWithAccount +## AbilityContext.connectServiceExtensionAbilityWithAccount -connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板和account将当前Ability连接到一个Ability。 @@ -807,13 +1471,26 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { @@ -821,13 +1498,20 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbilityWithAccount(want, accountId, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.disconnectAbility +## AbilityContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number): Promise\; +disconnectServiceExtensionAbility(connection: number): Promise\; 断开连接(promise形式)。 @@ -847,20 +1531,44 @@ disconnectAbility(connection: number): Promise\; | -------- | -------- | | Promise\ | 返回执行结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - var connectionNumber = 0; - this.context.disconnectAbility(connectionNumber).then(() => { - console.log('disconnectAbility success'); - }).catch((err) => { - console.log('disconnectAbility fail, err: ', err); - }); + ```ts + // connection为connectAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## AbilityContext.disconnectAbility +## AbilityContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number, callback:AsyncCallback\): void; +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; 断开连接(callback形式)。 @@ -875,13 +1583,39 @@ disconnectAbility(connection: number, callback:AsyncCallback\): void; | connection | number | 是 | 连接的Ability的数字代码。 | | callback | AsyncCallback\ | 是 | 表示指定的回调方法。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - var connectionNumber = 0; - this.context.disconnectAbility(connectionNumber, (err) => { - console.log('---------- disconnectAbility fail, err: -----------', err); + ```ts + // connection为connectServiceExtensionAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityByCall @@ -906,8 +1640,10 @@ startAbilityByCall(want: Want): Promise<Caller>; **示例:** - ```js - let caller = undefined; + 后台启动: + + ```ts + var caller = undefined; // 后台启动Ability,不配置parameters var wantBackground = { @@ -916,13 +1652,29 @@ startAbilityByCall(want: Want): Promise<Caller>; abilityName: "MainAbility", deviceId: "" }; - this.context.startAbilityByCall(wantBackground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + 前台启动: + + ```ts + var caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true var wantForeground = { @@ -934,13 +1686,23 @@ startAbilityByCall(want: Want): Promise<Caller>; "ohos.aafwk.param.callAbilityToForeground": true } }; - this.context.startAbilityByCall(wantForeground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.startAbilityWithAccount @@ -963,18 +1725,57 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -999,21 +1800,60 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -1037,25 +1877,60 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options) - .then(() => { - console.log('---------- startAbilityWithAccount success -----------'); - }) - .catch((err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## AbilityContext.requestPermissionsFromUser @@ -1075,7 +1950,7 @@ requestPermissionsFromUser(permissions: Array<string>, requestCallback: As **示例:** - ```js + ```ts var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions,(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); @@ -1106,7 +1981,7 @@ requestPermissionsFromUser(permissions: Array<string>) : Promise<Permis **示例:** - ```js + ```ts var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions).then((data) => { console.log('success:' + JSON.stringify(data)); @@ -1134,7 +2009,7 @@ setMissionLabel(label: string, callback:AsyncCallback<void>): void; **示例:** - ```js + ```ts this.context.setMissionLabel("test",(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); }); @@ -1163,7 +2038,7 @@ setMissionLabel(label: string): Promise<void>; **示例:** - ```js + ```ts this.context.setMissionLabel("test").then(() => { console.log('success'); }).catch((error) => { @@ -1189,7 +2064,7 @@ setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; **示例:** - ```js + ```ts import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); @@ -1236,7 +2111,7 @@ setMissionIcon(icon: image.PixelMap): Promise\; **示例:** - ```js + ```ts import image from '@ohos.multimedia.image'; var imagePixelMap; var color = new ArrayBuffer(0); @@ -1277,7 +2152,7 @@ restoreWindowStage(localStorage: LocalStorage) : void; **示例:** - ```js + ```ts var storage = new LocalStorage(); this.context.restoreWindowStage(storage); ``` @@ -1298,7 +2173,7 @@ isTerminating(): boolean; **示例:** - ```js + ```ts var isTerminating = this.context.isTerminating(); console.log('ability state :' + isTerminating); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 3bf7786bb7175ba951fbce561abe33050f5d8e52..15895ab2b64d8b76e8e5c1c928e812f37aeeff19 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -48,7 +48,7 @@ checkAccessToken(tokenID: number, permissionName: Permissions): Promise<Grant | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | Permissions | 是 | 需要校验的权限名称。 | **返回值:** @@ -135,7 +135,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被授予的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | @@ -190,7 +190,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: Permissions, permiss | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。| | permissionName | Permissions | 是 | 被授予的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 授予应用user grant权限。当授予权限成功时,err为undefine;否则为错误对象。 | @@ -242,7 +242,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | @@ -297,7 +297,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: Permissions, permis | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | Permissions | 是 | 被撤销的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | | callback | AsyncCallback<void> | 是 | 撤销应用user grant权限。当撤销权限成功时,err为undefine;否则为错误对象。 | @@ -349,7 +349,7 @@ getPermissionFlags(tokenID: number, permissionName: Permissions): Promise<num | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | Permissions | 是 | 查询的权限名称。 | **返回值:** @@ -379,7 +379,7 @@ let permissionFlag = 1; try { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); - }).catch((err) = > { + }).catch((err) => { console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); }); } catch(err) { @@ -610,6 +610,6 @@ promise.then(data => { | 名称 | 类型 | 可读 | 可写 | 说明 | | -------------- | ------------------------- | ---- | ---- | ------------------ | -| change | [PermissionStateChangeType](#permissionstatechangetype9) | 是 | 否 | 权限授权状态变化类型 | -| tokenID | number | 是 | 否 | 被订阅的应用身份标识 | -| permissionName | Permissions | 是 | 否 | 当前授权状态发生变化的权限名 | +| change | [PermissionStateChangeType](#permissionstatechangetype9) | 是 | 否 | 权限授权状态变化类型。 | +| tokenID | number | 是 | 否 | 被订阅的应用身份标识。 | +| permissionName | Permissions | 是 | 否 | 当前授权状态发生变化的权限名。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md index 89e43e02cbb2de776cca4c6fa1f43cce120eac67..771686fc1c32393d01438c40774cc4e628ebb18e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -22,7 +22,7 @@ import GesturePath from '@ohos.accessibility.GesturePath'; ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ------------ | ---------------------------------------- | ---- | ---- | ------ | | points | Array<[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)> | 是 | 是 | 手势触摸点。 | | durationTime | number | 是 | 是 | 手势总耗时, 单位为毫秒。 | @@ -37,13 +37,12 @@ constructor(durationTime: number); **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | durationTime | number | 是 | 手势总耗时,单位为毫秒。 | **示例:** ```ts -let durationTime = 20; -let gesturePath = new GesturePath(durationTime); +let gesturePath = new GesturePath.GesturePath(20); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md index d787f38222017e3e524d8d4712f81af7873d5d41..2e1703d2afb51ed3c273b3a829112620231468b0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -22,7 +22,7 @@ import GesturePoint from '@ohos.accessibility.GesturePoint'; ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ------ | ---- | ---- | ------- | | positionX | number | 是 | 是 | 触摸点X坐标。 | | positionY | number | 是 | 是 | 触摸点Y坐标。 | @@ -37,7 +37,7 @@ constructor(positionX: number, positionY: number); **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | positionX | number | 是 | 触摸点X坐标。 | | positionY | number | 是 | 触摸点Y坐标。 | @@ -45,7 +45,5 @@ constructor(positionX: number, positionY: number); **示例:** ```ts -let positionX = 1; -let positionY = 2; -let gesturePoint = new GesturePoint(positionX, positionY); +let gesturePoint = new GesturePoint.GesturePoint(1, 2); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md index 4d7842e34181c20e99e296135c343b359a48d1e5..bc3b90897ad090431db9c679dadb656ed7b581b1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @@ -16,7 +16,7 @@ import config from '@ohos.accessibility.config'; **系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | highContrastText | [Config](#config)\| 是 | 是 | 表示高对比度文字功能启用状态。 | | invertColor | [Config](#config)\| 是 | 是 | 表示颜色反转功能启用状态。 | @@ -41,7 +41,7 @@ enableAbility(name: string, capability: Array<accessibility.Capability>): **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | | capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)>) | 是 | 辅助应用的能力属性。 | @@ -65,7 +65,7 @@ enableAbility(name: string, capability: Array<accessibility.Capability>): ```ts let name = 'com.ohos.example/axExtension'; -let capability = ['retrieve']; +let capability : accessibility.Capability[] = ['retrieve']; try { config.enableAbility(name, capability).then(() => { console.info('enable ability succeed'); @@ -75,7 +75,7 @@ try { } catch (exception) { console.error('failed to enable ability, because ' + JSON.stringify(exception)); }; - ``` +``` ## enableAbility @@ -87,7 +87,7 @@ enableAbility(name: string, capability: Array<accessibility.Capability>, c **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | | capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | 是 | 辅助应用的能力属性。 | @@ -106,9 +106,9 @@ enableAbility(name: string, capability: Array<accessibility.Capability>, c ```ts let name = 'com.ohos.example/axExtension'; -let capability = ['retrieve']; +let capability : accessibility.Capability[] = ['retrieve']; try { - config.enableAbility(name, capability, (err, data) => { + config.enableAbility(name, capability, (err) => { if (err) { console.error('failed to enable ability, because ' + JSON.stringify(err)); return; @@ -130,7 +130,7 @@ disableAbility(name: string): Promise<void>; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | @@ -153,7 +153,7 @@ disableAbility(name: string): Promise<void>; ```ts let name = 'com.ohos.example/axExtension'; try { - config.enableAbility(name).then(() => { + config.disableAbility(name).then(() => { console.info('disable ability succeed'); }).catch((err) => { console.error('failed to disable ability, because ' + JSON.stringify(err)); @@ -173,7 +173,7 @@ disableAbility(name: string, callback: AsyncCallback<void>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 辅助应用的名称,格式为:'bundleName/abilityName'。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -213,7 +213,7 @@ on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void&g **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 参数固定为enabledAccessibilityExtensionListChange,监听启用的辅助扩展的列表变化。 | | callback | Callback<void> | 是 | 回调函数,在启用的辅助扩展的列表变化时通过此函数进行通知。 | @@ -224,12 +224,9 @@ on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void&g try { config.on('enabledAccessibilityExtensionListChange', () => { console.info('subscribe enabled accessibility extension list change state success'); - }).catch((err) => { - console.error('failed to subscribe enabled accessibility extension list change state, because ' + - JSON.stringify(err)); }); } catch (exception) { - console.error('failed to subscribe enabled accessibility extension list change state, because ' + + console.error('failed to subscribe enabled accessibility extension list change state, because ' + JSON.stringify(exception)); }; ``` @@ -244,7 +241,7 @@ off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 否 | 参数固定为enabledAccessibilityExtensionListChange,监听启用的辅助扩展的列表变化。 | | callback | Callback<void> | 否 | 要取消的监听回调函数。 | @@ -254,13 +251,10 @@ off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void ```ts try { config.off('enabledAccessibilityExtensionListChange', () => { - console.info('unSubscribe enabled accessibility extension list change state success'); - }).catch((err) => { - console.error('failed to unSubscribe enabled accessibility extension list change state, because ' + - JSON.stringify(err)); + console.info('Unsubscribe enabled accessibility extension list change state success'); }); } catch (exception) { - console.error('failed to unSubscribe enabled accessibility extension list change state, because ' + + console.error('failed to Unsubscribe enabled accessibility extension list change state, because ' + JSON.stringify(exception)); }; ``` @@ -279,7 +273,7 @@ set(value: T): Promise<void>; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | T | 是 | 设置的属性值。 | @@ -314,7 +308,7 @@ set(value: T, callback: AsyncCallback<void>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | value | T | 是 | 设置的属性值。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -372,7 +366,7 @@ get(callback: AsyncCallback<T>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | 是 | 回调函数,返回属性值。 | @@ -400,7 +394,7 @@ on(callback: Callback<T>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | Callback<T> | 是 | 回调函数,在属性变化时通过此函数进行通知。 | @@ -408,12 +402,8 @@ on(callback: Callback<T>): void; ```ts try { - config.highContrastText.on((err, data) => { - if (err) { - console.error('failed subscribe highContrastText, because ' + JSON.stringify(err)); - return; - } - console.info('subscribe highContrastText success'); + config.highContrastText.on((data) => { + console.info('subscribe highContrastText success, result: ' + JSON.stringify(data)); }); } catch (exception) { console.error('failed subscribe highContrastText, because ' + JSON.stringify(exception)); @@ -430,19 +420,15 @@ off(callback?: Callback<T>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | Callback<T> | 否 | 要取消的监听回调函数。 | **示例:** ```ts -config.highContrastText.off((err, data) => { - if (err) { - console.error('failed unSubscribe highContrastText, because ' + JSON.stringify(err)); - return; - } - console.info('unSubscribe highContrastText success'); +config.highContrastText.off((data) => { + console.info('Unsubscribe highContrastText success, result: ' + JSON.stringify(data)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md index 896b51ae188eec0a7851d8c6647a7939da71444e..b6242740c4627f1c962896c93427bcc1936dc122 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -56,7 +56,7 @@ class MainAbility extends AccessibilityExtensionAbility { **系统能力**:以下各项对应的系统能力均为 SystemCapability.BarrierFree.Accessibility.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ---- | ---- | --------- | | left | number | 是 | 否 | 矩形区域的左边界。 | | top | number | 是 | 否 | 矩形区域的上边界。 | @@ -84,7 +84,7 @@ setTargetBundleName(targetNames: Array\): Promise\; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------- | ---- | -------- | | targetNames | Array<string> | 是 | 关注的目标包名。 | @@ -119,7 +119,7 @@ setTargetBundleName(targetNames: Array\, callback: AsyncCallback\) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------- | ---- | -------- | | targetNames | Array<string> | 是 | 关注的目标包名。 | | callback | AsyncCallback<void> | 是 | 回调函数,如果设置关注的目标包名失败,则AsyncCallback中err有数据返回。 | @@ -151,7 +151,7 @@ getFocusElement(isAccessibilityFocus?: boolean): Promise\; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------- | ---- | ------------------- | | isAccessibilityFocus | boolean | 否 | 获取的是否是无障碍焦点元素,默认为否。 | @@ -195,7 +195,7 @@ getFocusElement(callback: AsyncCallback\): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回当前对应的焦点元素。 | @@ -234,7 +234,7 @@ getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------- | ---- | ------------------- | | windowId | number | 否 | 指定窗口的编号,未指定则从当前活跃窗口获取。 | @@ -309,7 +309,7 @@ getWindowRootElement(callback: AsyncCallback\): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回指定窗口的根节点元素。 | @@ -348,7 +348,7 @@ getWindowRootElement(windowId: number, callback: AsyncCallback\>; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------- | ---- | ------------------- | | displayId | number | 否 | 指定的屏幕编号,未指定则从默认主屏幕获取。 | @@ -432,7 +432,7 @@ getWindows(callback: AsyncCallback\>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<AccessibilityElement>> | 是 | 回调函数,返回指定屏幕的所有窗口。 | @@ -472,7 +472,7 @@ getWindows(displayId: number, callback: AsyncCallback\; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | 是 | 表示手势的路径信息。 | @@ -561,7 +561,7 @@ injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | 是 | 表示手势的路径信息。 | | callback | AsyncCallback<void> | 是 | 回调函数,表示注入手势执行结果的回调。 | @@ -637,7 +637,7 @@ attributeNames\(callback: AsyncCallback\ **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | callback | AsyncCallback<Array<T>> | 是 | 回调函数,返回节点元素的所有属性名称。 | @@ -665,7 +665,7 @@ attributeValue\(attributeName: T): Promi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | attributeName | T | 是 | 表示属性的名称。 | @@ -709,7 +709,7 @@ attributeValue\(attributeName: T, **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | attributeName | T | 是 | 表示属性的名称。 | | callback | AsyncCallback<ElementAttributeValues[T]> | 是 | 回调函数,返回根据节点属性名称获取的属性值。 | @@ -777,7 +777,7 @@ actionNames(callback: AsyncCallback\>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | callback | AsyncCallback<Array<string>> | 是 | 回调函数,返回节点元素支持的所有操作名称。 | @@ -805,7 +805,7 @@ performAction(actionName: string, parameters?: object): Promise\; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | actionName | string | 是 | 表示属性的名称。 | | parameters | object | 否 | 表示执行操作时所需要的参数。 | @@ -848,7 +848,7 @@ performAction(actionName: string, callback: AsyncCallback\): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | | actionName | string | 是 | 表示属性的名称。 | | callback | AsyncCallback<void> | 是 | 回调函数,表示执行指定操作的回调。| @@ -887,7 +887,7 @@ performAction(actionName: string, parameters: object, callback: AsyncCallback\ { - if (err) { - console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(err)); - return; - } - result = data; - console.info('subscribe caption manager enable state change success'); + captionsManager.on('enableChange', (data) => { + console.info('subscribe caption manager enable state change, result: ' + JSON.stringify(data)); }); } catch (exception) { console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(exception)); @@ -195,7 +189,7 @@ on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 监听的事件名,固定为‘styleChange’,即字幕风格变化事件。 | | callback | Callback<[CaptionsStyle](#captionsstyle8)> | 是 | 回调函数,在字幕风格变化时通过此函数进行通知。 | @@ -206,13 +200,9 @@ on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; let captionStyle; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.on('styleChange', (err, data) => { - if (err) { - console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(err)); - return; - } + captionsManager.on('styleChange', (data) => { captionStyle = data; - console.info('subscribe caption manager style state change success'); + console.info('subscribe caption manager style state change, result: ' + JSON.stringify(data)); }); } catch (exception) { console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(exception)); @@ -227,7 +217,7 @@ off(type: 'enableChange', callback?: Callback<boolean>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 取消监听的事件名,固定为‘enableChange’,即字幕配置启用状态变化事件。 | | callback | Callback<boolean> | 否 | 回调函数,在字幕配置启用状态变化时将状态通过此函数进行通知。 | @@ -235,19 +225,13 @@ off(type: 'enableChange', callback?: Callback<boolean>): void; **示例:** ```ts -let result = false; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.off('enableChange', (err, data) => { - if (err) { - console.error('failed to unSubscribe caption manager enable state change, because ' + JSON.stringify(err)); - return; - } - result = data; - console.info('unSubscribe caption manager enable state change success'); + captionsManager.off('enableChange', (data) => { + console.info('Unsubscribe caption manager enable state change, result: ' + JSON.stringify(data)); }); } catch (exception) { - console.error('failed to unSubscribe caption manager enable state change, because ' + JSON.stringify(exception)); + console.error('failed to Unsubscribe caption manager enable state change, because ' + JSON.stringify(exception)); } ``` @@ -259,7 +243,7 @@ off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 取消监听的事件名,固定为‘styleChange’,即字幕风格变化事件。 | | callback | Callback<[CaptionsStyle](#captionsstyle8)> | 否 | 回调函数,在字幕风格变化时通过此函数进行通知。 | @@ -270,16 +254,12 @@ off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; let captionStyle; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.off('styleChange', (err, data) => { - if (err) { - console.error('failed to unSubscribe caption manager style state change, because ' + JSON.stringify(err)); - return; - } + captionsManager.off('styleChange', (data) => { captionStyle = data; - console.info('unSubscribe caption manager style state change success'); + console.info('Unsubscribe caption manager style state change, result: ' + JSON.stringify(data)); }); } catch (exception) { - console.error('failed to unSubscribe caption manager style state change, because ' + JSON.stringify(exception)); + console.error('failed to Unsubscribe caption manager style state change, because ' + JSON.stringify(exception)); } ``` @@ -291,7 +271,7 @@ try { ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | type | [EventType](#eventtype) | 是 | 是 | 无障碍事件类型。 | | windowUpdateType | [WindowUpdateType](#windowupdatetype) | 是 | 是 | 窗口变化类型。 | @@ -318,7 +298,7 @@ constructor(jsonObject) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | jsonObject | string | 是 | 创建对象所需要的 JSON 格式字符串。 | @@ -395,7 +375,7 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<A **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | @@ -445,7 +425,7 @@ getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: Asyn **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | @@ -489,7 +469,7 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | @@ -503,9 +483,9 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState) **示例:** ```ts -let abilityType = 'spoken'; -let abilityState = 'enable'; -let extensionList: accessibility.AccessibilityInfo[]; +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; try { accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { for (let item of data) { @@ -526,7 +506,7 @@ try { ## accessibility.getAccessibilityExtensionList9+ -getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void 查询辅助应用列表,使用callback异步回调。 @@ -534,7 +514,7 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | @@ -543,9 +523,9 @@ getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, **示例:** ```ts -let abilityType = 'spoken'; -let abilityState = 'enable'; -let extensionList: accessibility.AccessibilityInfo[]; +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; try { accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { if (err) { @@ -560,8 +540,6 @@ try { extensionList.push(item); } console.info('get accessibility extension list success'); - }).catch((err) => { - console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); }); } catch (exception) { console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); @@ -598,7 +576,7 @@ on(type: 'accessibilityStateChange', callback: Callback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 监听的事件名,固定为‘accessibilityStateChange’,即辅助应用启用状态变化事件。 | | callback | Callback<boolean> | 是 | 回调函数,在辅助应用启用状态变化时将状态通过此函数进行通知。 | @@ -607,12 +585,8 @@ on(type: 'accessibilityStateChange', callback: Callback<boolean>): void ```ts try { - accessibility.on('accessibilityStateChange', (err, data) => { - if (err) { - console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(err)); - return; - } - console.info('subscribe accessibility state change success'); + accessibility.on('accessibilityStateChange', (data) => { + console.info('subscribe accessibility state change, result: ' + JSON.stringify(data)); }); } catch (exception) { console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(exception)); @@ -629,7 +603,7 @@ on(type: 'touchGuideStateChange', callback: Callback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 监听的事件名,固定为‘touchGuideStateChange’,即触摸浏览启用状态变化事件。 | | callback | Callback<boolean> | 是 | 回调函数,在触摸浏览启用状态变化时将状态通过此函数进行通知。 | @@ -638,12 +612,8 @@ on(type: 'touchGuideStateChange', callback: Callback<boolean>): void ```ts try { - accessibility.on('touchGuideStateChange', (err, data) => { - if (err) { - console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(err)); - return; - } - console.info('subscribe touch guide state change success'); + accessibility.on('touchGuideStateChange', (data) => { + console.info('subscribe touch guide state change, result: ' + JSON.stringify(data)); }); } catch (exception) { console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(exception)); @@ -660,7 +630,7 @@ off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 否 | 取消监听的事件名,固定为‘accessibilityStateChange’,即辅助应用启用状态变化事件。 | | callback | Callback<boolean> | 否 | 回调函数,在辅助应用启用状态变化时将状态通过此函数进行通知。 | @@ -669,15 +639,11 @@ off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void ```ts try { - accessibility.on('accessibilityStateChange', (err, data) => { - if (err) { - console.error('failed to unSubscribe accessibility state change, because ' + JSON.stringify(err)); - return; - } - console.info('unSubscribe accessibility state change success'); + accessibility.off('accessibilityStateChange', (data) => { + console.info('Unsubscribe accessibility state change, result: ' + JSON.stringify(data)); }); } catch (exception) { - console.error('failed to unSubscribe accessibility state change, because ' + JSON.stringify(exception)); + console.error('failed to Unsubscribe accessibility state change, because ' + JSON.stringify(exception)); } ``` @@ -691,7 +657,7 @@ off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 否 | 取消监听的事件名,固定为‘touchGuideStateChange’,即触摸浏览启用状态变化事件。 | | callback | Callback<boolean> | 否 | 回调函数,在触摸浏览启用状态变化时将状态通过此函数进行通知。 | @@ -700,15 +666,11 @@ off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void ```ts try { - accessibility.on('touchGuideStateChange', (err, data) => { - if (err) { - console.error('failed to unSubscribe touch guide state change, because ' + JSON.stringify(err)); - return; - } - console.info('unSubscribe touch guide state change success'); + accessibility.off('touchGuideStateChange', (data) => { + console.info('Unsubscribe touch guide state change, result: ' + JSON.stringify(data)); }); } catch (exception) { - console.error('failed to unSubscribe touch guide state change, because ' + JSON.stringify(exception)); + console.error('failed to Unsubscribe touch guide state change, because ' + JSON.stringify(exception)); } ``` @@ -746,7 +708,7 @@ isOpenAccessibility(callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | 是 | 回调函数,如果辅助功能已启用,则返回 true;否则返回 false。 | @@ -796,7 +758,7 @@ isOpenTouchGuide(callback: AsyncCallback<boolean>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | 是 | 回调函数,如果触摸浏览模式已开启,则返回 true;否则返回 false。 | @@ -827,7 +789,7 @@ sendEvent(event: EventInfo): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | [EventInfo](#eventinfo) | 是 | 无障碍事件对象。 | @@ -867,7 +829,7 @@ sendEvent(event: EventInfo, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | [EventInfo](#eventinfo) | 是 | 辅助事件对象。 | | callback | AsyncCallback<void> | 是 | 回调函数,如果发送无障碍事件失败,则 AsyncCallback中err有数据返回。 | @@ -899,7 +861,7 @@ sendAccessibilityEvent(event: EventInfo): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | [EventInfo](#eventinfo) | 是 | 无障碍事件对象。 | @@ -938,7 +900,7 @@ sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): v **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | [EventInfo](#eventinfo) | 是 | 辅助事件对象。 | | callback | AsyncCallback<void> | 是 | 回调函数,如果发送无障碍事件失败,则 AsyncCallback中err有数据返回。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index 9e2835b6930e7da7e569e7c8eda729baa5392d93..49b4ff2e97c184127eb2faeea6a0c3401a7a6c9e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -4691,10 +4691,16 @@ onResult: (code: number, result?: AuthResult) => void let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { console.log("getAuthCallback err: " + JSON.stringify(err)); @@ -4727,9 +4733,16 @@ onRequestRedirected: (request: Want) => void } auth(name, authType, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } } diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-appControl.md similarity index 74% rename from zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md rename to zh-cn/application-dev/reference/apis/js-apis-appControl.md index 144887f76d9d62e5eda6ea2790bff6a2e38c4c24..fbb5eacb11eba06abcb272518fce2bf1e04ab844 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md @@ -30,7 +30,7 @@ setDisposedStatus(appId: string, disposedWant: Want): Promise\ | 名称 | 类型 | 必填 | 描述 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 需要设置处置状态的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| appId | string | 是 | 需要设置处置状态的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | disposedWant | Want | 是 | 对应用的处置意图。 | **返回值:** @@ -41,7 +41,7 @@ setDisposedStatus(appId: string, disposedWant: Want): Promise\ **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -50,23 +50,7 @@ setDisposedStatus(appId: string, disposedWant: Want): Promise\ **示例:** ```ts -import appControl from '@ohos.bundle.appControl' -import bundleManager from '@ohos.bundle.bundleManager'; - -// 获取appId -var bundleName = 'com.example.myapplication'; -var appId; -try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) - .then((data) => { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} - +var appId = "com.example.myapplication_xxxxx"; var want = {bundleName: 'com.example.myapplication'}; try { @@ -97,13 +81,13 @@ setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\ appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| appId | string | 是 | 需要设置处置的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | disposedWant | Want | 是 | 对应用的处置意图。 | | callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 | **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -112,23 +96,7 @@ setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\ { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} - +var appId = "com.example.myapplication_xxxxx"; var want = {bundleName: 'com.example.myapplication'}; try { @@ -137,7 +105,7 @@ try { console.error('setDisposedStatus failed ' + error.message); return; } - console.info('setDisposedStatus success'); + console.info('setDisposedStatus success'); }); } catch (error) { console.error('setDisposedStatus failed ' + error.message); @@ -160,7 +128,7 @@ getDisposedStatus(appId: string): Promise\; | 名称 | 类型 | 必填 | 描述 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | **返回值:** @@ -170,7 +138,7 @@ getDisposedStatus(appId: string): Promise\; **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -179,22 +147,7 @@ getDisposedStatus(appId: string): Promise\; **示例:** ```ts -import appControl from '@ohos.bundle.appControl' -import bundleManager from '@ohos.bundle.bundleManager'; - -// 获取appId -var bundleName = 'com.example.myapplication'; -var appId; -try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) - .then((data) => { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} +var appId = "com.example.myapplication_xxxxx"; try { appControl.getDisposedStatus(appId) @@ -224,12 +177,12 @@ getDisposedStatus(appId: string, callback: AsyncCallback\): void; | 名称 | 类型 | 必填 | 描述 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 | **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -238,22 +191,7 @@ getDisposedStatus(appId: string, callback: AsyncCallback\): void; **示例:** ```ts -import appControl from '@ohos.bundle.appControl' -import bundleManager from '@ohos.bundle.bundleManager'; - -// 获取appId -var bundleName = 'com.example.myapplication'; -var appId; -try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) - .then((data) => { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} +var appId = "com.example.myapplication_xxxxx"; try { appControl.getDisposedStatus(appId, (err, data) => { @@ -284,7 +222,7 @@ deleteDisposedStatus(appId: string): Promise\ | 名称 | 类型 | 必填 | 描述 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | | +| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | **返回值:** @@ -294,7 +232,7 @@ deleteDisposedStatus(appId: string): Promise\ **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -303,22 +241,7 @@ deleteDisposedStatus(appId: string): Promise\ **示例:** ```ts -import appControl from '@ohos.bundle.appControl' -import bundleManager from '@ohos.bundle.bundleManager'; - -// 获取appId -var bundleName = 'com.example.myapplication'; -var appId; -try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) - .then((data) => { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} +var appId = "com.example.myapplication_xxxxx"; try { appControl.deleteDisposedStatus(appId) @@ -348,12 +271,12 @@ deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void | 名称 | 类型 | 必填 | 描述 | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过getBundleInfo接口获取。 | +| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用的包名和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 | | callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 | **错误码** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码 | 错误信息 | | ------ | -------------------------------------- | @@ -362,23 +285,7 @@ deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void **示例:** ```ts -import appControl from '@ohos.bundle.appControl' -import bundleManager from '@ohos.bundle.bundleManager'; - -// 获取appId -var bundleName = 'com.example.myapplication'; -var appId; -try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) - .then((data) => { - appId = data.signatureInfo.appId; - }, error => { - console.error("getBundleInfo failed " + error.message); - }); -} catch (error) { - console.error("getBundleInfo failed " + error.message); -} - +var appId = "com.example.myapplication_xxxxx"; try { appControl.deleteDisposedStatus(appId, (err, data) => { if (err) { @@ -392,3 +299,26 @@ try { } ``` +## 获取应用的appId + +appId是应用的唯一标识,由应用的包名和签名信息决定,可以通过[getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)接口获取。 + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager'; + +var bundleName = 'com.example.myapplication'; +var appId; +try { + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + .then((data) => { + appId = data.signatureInfo.appId; + console.info("appId is " + appId); + }).catch((error) => { + console.error("getBundleInfo failed " + error.message); + }); +} catch (error) { + console.error("getBundleInfo failed " + error.message); +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md index 46efda388721bc8abf142aa6d021475cf3964dc9..99cb6ea0af827e81afc5e930e8a0bbbf17fd10bc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @@ -18,7 +18,7 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens **系统能力:** SystemCapability.BarrierFree.Accessibility.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | -------- | ---- | ---- | ------------------------- | | context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | 是 | 否 | 表示辅助扩展能力上下文。 | @@ -30,7 +30,7 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ---------------------------------------- | ---- | ---- | ---------- | | eventType | [EventType](js-apis-accessibility.md#EventType) \| [WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | 是 | 否 | 具体事件类型。 | | target | AccessibilityElement | 是 | 否 | 发生事件的目标组件。 | @@ -129,7 +129,7 @@ onAccessibilityEvent(event: AccessibilityEvent): void; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ---------------------------------------- | ---- | --------------- | | event | [AccessibilityEvent](#accessibilityevent) | 是 | 无障碍事件回调函数。无返回值。 | @@ -156,7 +156,7 @@ onKeyEvent(keyEvent: KeyEvent): boolean; **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------------- | | keyEvent | [KeyEvent](js-apis-keyevent.md#KeyEvent) | 是 | 按键事件回调函数。返回true表示拦截此按键。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-Want.md b/zh-cn/application-dev/reference/apis/js-apis-application-Want.md index 73c71a6204d6bbd3bccb0e644bb47e204d401a8b..bcd3d7213b44ff085acd546ddb78aaf97f870c5c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-Want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-Want.md @@ -3,7 +3,7 @@ Want模块提供系统的基本通信组件的能力。 > **说明:** -> +> > 本模块首批接口从API version 8 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -46,79 +46,91 @@ import Want from '@ohos.application.Want'; }) ``` -- 传递FD数据,FD表示文件描述符(FileDescriptor) +- 通过自定字段传递数据, 以下为当前支持类型。 - ``` js - import fileio from '@ohos.fileio'; - var fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); - } - var want = { - "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName非必选 - "parameters": { - "keyFd":{"type":"FD", "value":fd} + * 字符串(String) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForString: "str", + }, } - }; - this.context.startAbility(want, (error) => { - // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability - console.log("error.code = " + error.code) - }) - ``` - -- 传递RemoteObject数据 - - ``` 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; - } + ``` + * 数字(Number) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForInt: 100, + keyForDouble: 99.99, + }, } - - 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; + ``` + * 布尔(Boolean) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForBool: true, + }, } - - method() { - console.log('method called'); + ``` + * 对象(Object) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForObject: { + keyForObjectString: "str", + keyForObjectInt: -200, + keyForObjectDouble: 35.5, + keyForObjectBool: false, + }, + }, } - } - - var remoteObject = new Stub('want-test'); - var want = { - "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName非必选 - "parameters": { - "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} + ``` + * 数组(Array) + ```ts + let want = { + bundleName: "com.example.demo", + abilityName: "com.example.demo.MainAbility", + parameters: { + keyForArrayString: ["str1", "str2", "str3"], + keyForArrayInt: [100, 200, 300, 400], + keyForArrayDouble: [0.1, 0.2], + keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + }, } - }; - - this.context.startAbility(want, (error) => { - // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability - console.log("error.code = " + error.code) - }) + ``` + * 文件描述符(FD) + ```ts + import fileio from '@ohos.fileio'; + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // deviceId为空表示本设备 + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry", // moduleName非必选 + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability + console.log("error.code = " + error.code) + }) + ``` - ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md index 1c67e86ee5d26139313b32180d9beb9a54accbf1..fc61145af95542b9d40503644445fa2337f1c2d6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-ability.md @@ -45,8 +45,8 @@ Ability创建时回调,执行初始化业务逻辑操作。 | param | AbilityConstant.LaunchParam | 是 | 创建 ability、上次异常退出的原因信息。 | **示例:** - - ```js + + ```ts class myAbility extends Ability { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); @@ -71,7 +71,7 @@ onWindowStageCreate(windowStage: window.WindowStage): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -90,7 +90,7 @@ onWindowStageDestroy(): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageDestroy() { console.log('onWindowStageDestroy'); @@ -115,7 +115,7 @@ onWindowStageRestore(windowStage: window.WindowStage): void **示例:** - ```js + ```ts class myAbility extends Ability { onWindowStageRestore(windowStage) { console.log('onWindowStageRestore'); @@ -134,7 +134,7 @@ Ability生命周期回调,在销毁时回调,执行资源清理等操作。 **示例:** - ```js + ```ts class myAbility extends Ability { onDestroy() { console.log('onDestroy'); @@ -153,7 +153,7 @@ Ability生命周期回调,当应用从后台转到前台时触发。 **示例:** - ```js + ```ts class myAbility extends Ability { onForeground() { console.log('onForeground'); @@ -172,7 +172,7 @@ Ability生命周期回调,当应用从前台转到后台时触发。 **示例:** - ```js + ```ts class myAbility extends Ability { onBackground() { console.log('onBackground'); @@ -203,7 +203,7 @@ onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; **示例:** - ```js + ```ts import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { onContinue(wantParams) { @@ -232,7 +232,7 @@ onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; **示例:** - ```js + ```ts class myAbility extends Ability { onNewWant(want) { console.log('onNewWant, want:' + want.abilityName); @@ -257,7 +257,7 @@ onConfigurationUpdated(config: Configuration): void; **示例:** - ```js + ```ts class myAbility extends Ability { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); @@ -281,7 +281,7 @@ dump(params: Array\): Array\; **示例:** - ```js + ```ts class myAbility extends Ability { dump(params) { console.log('dump, params:' + JSON.stringify(params)); @@ -306,7 +306,7 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; **示例:** - ```js + ```ts class myAbility extends Ability { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); @@ -320,7 +320,6 @@ onMemoryLevel(level: AbilityConstant.MemoryLevel): void; 通用组件Caller通信客户端调用接口, 用来向通用组件服务端发送约定数据。 - ## Caller.call call(method: string, data: rpc.Sequenceable): Promise<void>; @@ -342,54 +341,65 @@ call(method: string, data: rpc.Sequenceable): Promise<void>; | -------- | -------- | | Promise<void> | Promise形式返回应答。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ // 自定义的Sequenceable数据结构 - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } }; var method = 'call_Function'; // 约定的通知消息字符串 var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); // 参考Sequenceable数据定义 - caller.call(method, msg) - .then(() => { - console.log('Caller call() called'); - }).catch((e) => { - console.log('Caller call() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble("msg", "world"); // 参考Sequenceable数据定义 + caller.call(method, msg) + .then(() => { + console.log('Caller call() called'); + }) + .catch((callErr) => { + console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -415,55 +425,67 @@ callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessagePa | -------- | -------- | | Promise<rpc.MessageParcel> | Promise形式返回通用组件服务端应答数据。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - - ```js - import Ability from '@ohos.application.Ability'; + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ - name:"" - str:"" - num: 1 - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } }; var method = 'call_Function'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); - caller.callWithResult(method, msg) - .then((data) => { - console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); - data.readSequenceable(retmsg); - }).catch((e) => { - console.log('Caller callWithResult() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble(1, "world"); + caller.callWithResult(method, msg) + .then((data) => { + console.log('Caller callWithResult() called'); + let retmsg = new MyMessageAble(0, ""); + data.readSequenceable(retmsg); + }) + .catch((callErr) => { + console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -476,36 +498,46 @@ release(): void; **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.release(); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.release(); + } catch (releaseErr) { + console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + + ' error.message: ' + JSON.stringify(releaseErr.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` -## Caller.onRelease +## Caller.on -onRelease(callback: OnReleaseCallBack): void; + on(type: "release", callback: OnReleaseCallback): void; 注册通用组件服务端Stub(桩)断开监听通知。 @@ -515,33 +547,43 @@ onRelease(callback: OnReleaseCallBack): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | type | string | 是 | 监听releaseCall事件,固定为'release'。 | | callback | OnReleaseCallBack | 是 | 返回onRelease回调结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var caller; export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); - }); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } + onWindowStageCreate(windowStage) { + this.context.startAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.on("release", (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } } ``` @@ -550,7 +592,6 @@ onRelease(callback: OnReleaseCallBack): void; 通用组件服务端注册和解除客户端caller通知送信的callback接口。 - ## Callee.on on(method: string, callback: CalleeCallBack): void; @@ -566,10 +607,18 @@ on(method: string, callback: CalleeCallBack): void; | method | string | 是 | 与客户端约定的通知消息字符串。 | | callback | CalleeCallBack | 是 | 一个rpc.MessageParcel类型入参的js通知同步回调函数, 回调函数至少要返回一个空的rpc.Sequenceable数据对象, 其他视为函数执行错误。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200004 | Method registered. The method has registered. | +| 16000050 | Internal Error. | + **示例:** - - ```js - import Ability from '@ohos.application.Ability'; + + ```ts + import Ability from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -599,14 +648,18 @@ on(method: string, callback: CalleeCallBack): void; return new MyMessageAble(10, "Callee test"); } export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.on(method, funcCallBack); + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); } + } } ``` - ## Callee.off off(method: string): void; @@ -621,20 +674,34 @@ off(method: string): void; | -------- | -------- | -------- | -------- | | method | string | 是 | 已注册的通知事件字符串。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200005 | Method not registered. The method has not registered. | +| 16000050 | Internal Error. | + + **示例:** - ```js - import Ability from '@ohos.application.Ability'; + ```ts + import Ability from '@ohos.app.ability.UIAbility'; var method = 'call_Function'; export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.off(method); + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.off(method); + } catch (error) { + console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); } + } } ``` -## OnReleaseCallBack +## OnReleaseCallback (msg: string): void; @@ -644,7 +711,7 @@ off(method: string): void; | -------- | -------- | -------- | -------- | -------- | | (msg: string) | function | 是 | 否 | 调用者注册的侦听器函数接口的原型。 | -## CalleeCallBack +## CalleeCallback (indata: rpc.MessageParcel): rpc.Sequenceable; diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..86a2559be56c47798384d2e958dc366afaf05ce5 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configuration.md @@ -0,0 +1,34 @@ +# Configuration + +定义环境变化信息。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + + | 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| language8+ | string | 是 | 是 | 表示应用程序的当前语言。 | +| colorMode8+ | [ColorMode](js-apis-configurationconstant.md#configurationconstantcolormode) | 是 | 是 | 表示深浅色模式,取值范围:浅色模式(COLOR_MODE_LIGHT),深色模式(COLOR_MODE_DARK)。默认为浅色。 | +| direction9+ | Direction | 是 | 否 | 表示屏幕方向,取值范围:水平方向(DIRECTION_HORIZONTAL),垂直方向(DIRECTION_VERTICAL)。 | +| screenDensity9+ | ScreenDensity | 是 | 否 | 表示屏幕分辨率,取值范围:SCREEN_DENSITY_SDPI(120)、SCREEN_DENSITY_MDPI(160)、SCREEN_DENSITY_LDPI(240)、SCREEN_DENSITY_XLDPI(320)、SCREEN_DENSITY_XXLDPI(480)、SCREEN_DENSITY_XXXLDPI(640)。 | +| displayId9+ | number | 是 | 否 | 表示应用所在的物理屏幕Id。 | +| hasPointerDevice9+ | boolean | 是 | 否 | 指示指针类型设备是否已连接,如键鼠、触控板等。 | + +具体字段描述参考ohos.application.Configuration.d.ts文件 + +**示例:** + + ```ts + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + var callbackId = applicationContext.registerEnvironmentCallback(envCallback); + ``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md b/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..52a2e191ea4c8095ab0479ed2f2bdefbbe1a172f --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -0,0 +1,55 @@ +# ConfigurationConstant + +ConfigurationConstant模块提供配置信息枚举值定义的能力。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; +``` + +## ConfigurationConstant.ColorMode + +使用时通过ConfigurationConstant.ColorMode获取。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| COLOR_MODE_NOT_SET | -1 | 未设置颜色模式。 | +| COLOR_MODE_DARK | 0 | 深色模式。 | +| COLOR_MODE_LIGHT | 1 | 浅色模式。 | + + +## ConfigurationConstant.Direction9+ + +使用时通过ConfigurationConstant.Direction获取。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| DIRECTION_NOT_SET | -1 | 未设置方向。 | +| DIRECTION_VERTICAL | 0 | 垂直方向。 | +| DIRECTION_HORIZONTAL | 1 | 水平方向。 | + + +## ConfigurationConstant.ScreenDensity9+ + +使用时通过ConfigurationConstant.ScreenDensity获取。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase + +| 名称 | 值 | 说明 | +| -------- | -------- | -------- | +| SCREEN_DENSITY_NOT_SET | 0 | 未设置屏幕分辨率。 | +| SCREEN_DENSITY_SDPI | 120 | 屏幕分辨率为"sdpi"。 | +| SCREEN_DENSITY_MDPI | 160 | 屏幕分辨率为"mdpi"。 | +| SCREEN_DENSITY_LDPI | 240 | 屏幕分辨率为"ldpi"。 | +| SCREEN_DENSITY_XLDPI | 320 | 屏幕分辨率为"xldpi"。 | +| SCREEN_DENSITY_XXLDPI | 480 | 屏幕分辨率为"xxldpi"。 | +| SCREEN_DENSITY_XXXLDPI | 640 | 屏幕分辨率为"xxxldpi"。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md index 3914df193cee7647614ef2dee59689654c094bce..e606858a69136fd82c6d08a3e38394c86e2626c9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -96,9 +96,10 @@ add(element: T): boolean let b = [1, 2, 3]; let result2 = arrayList.add(b); let c = {name: "Dylon", age: "13"}; - let result3 = arrayList.add(false); + let result3 = arrayList.add(c); + let result4 = arrayList.add(false); try { - arraylist.add.bind({}, "b")(); + arrayList.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -136,17 +137,17 @@ arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); try { - arraylist.insert.bind({}, 1, 2)(); + arrayList.insert.bind({}, 1, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - let res = arrayList.insert(8, 11); + let res = arrayList.insert(8, 11); // 测试越界异常 } catch (err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - let res = arrayList.insert("a", "b"); + let res = arrayList.insert("a", "b"); // 测试类型异常 } catch (err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -188,7 +189,7 @@ let result = arrayList.has("squirrel"); arrayList.add("squirrel"); let result1 = arrayList.has("squirrel"); try { - arraylist.has.bind({}, "squirrel")(); + arrayList.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -235,7 +236,7 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.getIndexOf(2); try { - arraylist.getIndexOf.bind({}, 2)(); + arrayList.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -282,7 +283,7 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.getLastIndexOf(2); try { - arraylist.getLastIndexOf.bind({}, 2)(); + arrayList.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -328,17 +329,17 @@ arrayList.add(2); arrayList.add(4); let result = arrayList.removeByIndex(2); try { - arraylist.removeByIndex.bind({}, 2)(); + arrayList.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByIndex("a"); + arrayList.removeByIndex("a"); // 测试类型异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByIndex(8); + arrayList.removeByIndex(8); // 测试越界异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -382,7 +383,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.remove(2); try { - arraylist.remove.bind({}, 2)(); + arrayList.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -421,15 +422,13 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.removeByRange(2, 4); -arrayList.removeByRange(4, 3); -arrayList.removeByRange(2, 6); try { - arraylist.removeByRange.bind({}, 2, 4)(); + arrayList.removeByRange.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.removeByRange(8, 4); + arrayList.removeByRange(8, 4); // 测试越界异常 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -482,9 +481,9 @@ arrayList.replaceAllElements((value: number, index: number) => { return value = value - 2; }); try { - arraylist.replaceAllElements.bind({}, (value: number, index: number)=> { + arrayList.replaceAllElements.bind({}, (value: number, index: number)=> { return value = 2 * value; - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -534,9 +533,9 @@ arrayList.forEach((value, index) => { console.log(`value:${value}`, index); }); try { - arraylist.forEach.bind({}, (value, index) => { + arrayList.forEach.bind({}, (value, index) => { console.log(`value:${value}`, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -583,7 +582,7 @@ arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => b - a); arrayList.sort(); try { - arraylist.sort.bind({})(); + arrayList.sort.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -631,12 +630,12 @@ let result1 = arrayList.subArrayList(2, 4); let result2 = arrayList.subArrayList(4, 3); let result3 = arrayList.subArrayList(2, 6); try { - arraylist.subArrayList.bind({}, 2, 4)(); + arrayList.subArrayList.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - arraylist.subArrayList(6, 4); + arrayList.subArrayList(6, 4); } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -668,7 +667,7 @@ arrayList.add(5); arrayList.add(4); arrayList.clear(); try { - arraylist.clear.bind({})(); + arrayList.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -707,7 +706,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.clone(); try { - arraylist.clone.bind({})(); + arrayList.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -745,7 +744,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.getCapacity(); try { - arraylist.getCapacity.bind({})(); + arrayList.getCapacity.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -783,7 +782,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.convertToArray(); try { - arraylist.convertToArray.bind({})(); + arrayList.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -821,7 +820,7 @@ arrayList.add(5); arrayList.add(4); let result = arrayList.isEmpty(); try { - arraylist.isEmpty.bind({})(); + arrayList.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -860,7 +859,7 @@ arrayList.add(4); arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(8); try { - arraylist.increaseCapacityTo.bind({}, 5)(); + arrayList.increaseCapacityTo.bind({}, 5)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -892,7 +891,7 @@ arrayList.add(5); arrayList.add(4); arrayList.trimToCurrentLength(); try { - arraylist.trimToCurrentLength.bind({})(); + arrayList.trimToCurrentLength.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -942,7 +941,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - arraylist[Symbol.iterator].bind({})(); + arrayList[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 83ee7b3ef188b7aab26be93dbdce6cec416d79ed..024f89dd62face1472b5cc5dd6cc0f95e5177cc1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -716,6 +716,14 @@ async function createTonePlayer(){ | CONNECT_TYPE_LOCAL | 1 | 本地设备。 | | CONNECT_TYPE_DISTRIBUTED | 2 | 分布式设备。 | +## VolumeGroupInfos9+ + +音量组信息,数组类型,为[VolumeGroupInfo](#volumegroupinfo9)的数组,只读。 + +**系统接口:** 该接口为系统接口 + +**系统能力:** SystemCapability.Multimedia.Audio.Volume + ## VolumeGroupInfo9+ 音量组信息。 @@ -732,26 +740,6 @@ async function createTonePlayer(){ | groupName9+ | number | 是 | 否 | 组名。 | | type9+ | [ConnectType](#connecttype9)| 是 | 否 | 连接设备类型。 | -## VolumeGroupInfos9+ - -音量组信息,数组类型,为[VolumeGroupInfo](#volumegroupinfo9)的数组,只读。 - -**系统接口:** 该接口为系统接口 - -**系统能力:** SystemCapability.Multimedia.Audio.Volume - -**示例:** - -```js -import audio from '@ohos.multimedia.audio'; - -async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} -getVolumeGroupInfos(); -``` - ## DeviceChangeAction 描述设备连接状态变化和设备信息。 @@ -2773,6 +2761,12 @@ async function selectOutputDeviceByFilter(){ } ``` +## AudioRendererChangeInfoArray9+ + +数组类型,AudioRenderChangeInfo数组,只读。 + +**系统能力:** SystemCapability.Multimedia.Audio.Renderer + ## AudioRendererChangeInfo9+ 描述音频渲染器更改信息。 @@ -2786,12 +2780,6 @@ async function selectOutputDeviceByFilter(){ | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | 是 | 否 | 音频渲染器信息。 | | rendererState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| -## AudioRendererChangeInfoArray9+ - -AudioRenderChangeInfo数组,只读。 - -**系统能力:** SystemCapability.Multimedia.Audio.Renderer - **示例:** ```js @@ -2838,6 +2826,13 @@ audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => }); ``` + +## AudioCapturerChangeInfoArray9+ + +数组类型,AudioCapturerChangeInfo数组,只读。 + +**系统能力:** SystemCapability.Multimedia.Audio.Capturer + ## AudioCapturerChangeInfo9+ 描述音频采集器更改信息。 @@ -2851,12 +2846,6 @@ audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => | capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 否 | 音频采集器信息。 | | capturerState | [AudioState](#audiostate) | 是 | 否 | 音频状态。
此接口为系统接口。| -## AudioCapturerChangeInfoArray9+ - -AudioCapturerChangeInfo数组,只读。 - -**系统能力:** SystemCapability.Multimedia.Audio.Capturer - **示例:** ```js @@ -2901,6 +2890,10 @@ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => }); ``` +## AudioDeviceDescriptors + +设备属性数组类型,为[AudioDeviceDescriptor](#audiodevicedescriptor)的数组,只读。 + ## AudioDeviceDescriptor 描述音频设备。 @@ -2921,10 +2914,6 @@ audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => | interruptGroupId9+ | number | 是 | 否 | 设备所处的焦点组ID。
此接口为系统接口。 | | volumeGroupId9+ | number | 是 | 否 | 设备所处的音量组ID。
此接口为系统接口。 | -## AudioDeviceDescriptors - -设备属性数组类型,为[AudioDeviceDescriptor](#audiodevicedescriptor)的数组,只读。 - **示例:** ```js @@ -3798,6 +3787,8 @@ on(type: 'audioInterrupt', callback: Callback\): void 监听音频中断事件。使用callback获取中断事件。 +与[on('interrupt')](#oninterruptdeprecated)一致,该接口在AudioRenderer对象start、pause、stop等事件发生前已经主动获取焦点,不需要开发者主动发起焦点申请。 + **系统能力:** SystemCapability.Multimedia.Audio.Interrupt **参数:** @@ -3916,7 +3907,7 @@ audioRenderer.off('markReach'); on(type: "periodReach", frame: number, callback: Callback<number>): void -订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,回调被循环调用。 +订阅到达标记的事件。 当渲染的帧数达到 frame 参数的值时,触发回调并返回设定的值。 **系统能力:** SystemCapability.Multimedia.Audio.Renderer @@ -4558,7 +4549,7 @@ audioCapturer.off('markReach'); on(type: "periodReach", frame: number, callback: Callback<number>): void -订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,回调被循环调用。 +订阅到达标记的事件。 当采集的帧数达到 frame 参数的值时,触发回调并返回设定的值。 **系统能力:** SystemCapability.Multimedia.Audio.Capturer @@ -4628,7 +4619,7 @@ audioCapturer.on('stateChange', (state) => { }); ``` -## ToneType 9+ +## ToneType9+ 枚举,播放器的音调类型。 @@ -4684,7 +4675,7 @@ load(type: ToneType, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | :--------------| :-------------------------- | :-----| :------------------------------ | -| type | ToneType(#tonetype9) | 是 | 配置的音调类型。 | +| type | [ToneType](#tonetype9) | 是 | 配置的音调类型。 | | callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** @@ -4712,7 +4703,7 @@ load(type: ToneType): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | :------------- | :--------------------- | :--- | ---------------- | -| type | ToneType(#tonetype9) | 是 | 配置的音调类型。 | +| type | [ToneType](#tonetype9) | 是 | 配置的音调类型。 | **返回值:** @@ -4836,7 +4827,7 @@ tonePlayer.stop().then(() => { release(callback: AsyncCallback<void>): void -释放与此TonePlay对象关联的资源。使用callback方式异步返回结果。 +释放与此TonePlayer对象关联的资源。使用callback方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Tone @@ -4863,7 +4854,7 @@ tonePlayer.release((err) => { release(): Promise<void> -释放与此TonePlay对象关联的资源。使用Promise方式异步返回结果。 +释放与此TonePlayer对象关联的资源。使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Multimedia.Audio.Tone @@ -5942,6 +5933,8 @@ on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\ **说明:** > 从 API version 7 开始支持,从 API version 9 开始废弃。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-avsession.md b/zh-cn/application-dev/reference/apis/js-apis-avsession.md index 386f4d3a57c32465f09a6fd72b6efb0ac1e29aa3..759d35fcee934925e33ed2a7409bb8bd2a263a3b 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-avsession.md +++ b/zh-cn/application-dev/reference/apis/js-apis-avsession.md @@ -1,4 +1,4 @@ - # 媒体会话管理 +# 媒体会话管理 媒体会话管理提供媒体播控相关功能的接口,目的是让应用接入播控中心。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index fe38cfdda6ca2e31db35d5287607d23b327a388c..b363572eecbea607524e9ef94f5a5794df03f124 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -28,7 +28,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen 后台应用申请延迟挂起。 -延迟挂起时间一般情况下默认值为180000毫秒,低电量(依据系统低电量广播)时默认值为60000毫秒。 +延迟挂起时间一般情况下默认值为3分钟,低电量(依据系统低电量广播)时默认值为1分钟。 **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -452,14 +452,14 @@ export default class MainAbility extends Ability { **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| 参数名 | 参数值 | 描述 | -| ----------------------- | ---- | --------------------- | -| DATA_TRANSFER | 1 | 数据传输。 | -| AUDIO_PLAYBACK | 2 | 音频播放。 | -| AUDIO_RECORDING | 3 | 录音。 | -| LOCATION | 4 | 定位导航。 | -| BLUETOOTH_INTERACTION | 5 | 蓝牙相关。 | -| MULTI_DEVICE_CONNECTION | 6 | 多设备互联。 | -| WIFI_INTERACTION | 7 | WLAN相关
此接口为系统接口。 | -| VOIP | 8 | 音视频通话
此接口为系统接口。 | -| TASK_KEEPING | 9 | 计算任务(仅在特定设备生效)。 | \ No newline at end of file +| 参数名 | 描述 | +| ----------------------- | --------------------- | +| DATA_TRANSFER | 数据传输。 | +| AUDIO_PLAYBACK | 音频播放。 | +| AUDIO_RECORDING | 录音。 | +| LOCATION | 定位导航。 | +| BLUETOOTH_INTERACTION | 蓝牙相关。 | +| MULTI_DEVICE_CONNECTION | 多设备互联。 | +| WIFI_INTERACTION | WLAN相关(此接口为系统接口)。 | +| VOIP | 音视频通话(此接口为系统接口)。 | +| TASK_KEEPING | 计算任务(仅在特定设备生效)。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-buffer.md b/zh-cn/application-dev/reference/apis/js-apis-buffer.md index e96a0be8ea126341ca717dc3293c9919f4031415..92039a463703da7dc632367d8b321d9f26d1047d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-buffer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-buffer.md @@ -371,6 +371,13 @@ import buffer from '@ohos.buffer'; let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); +let arrayBuffer = new ArrayBuffer(5); +let array = new Int8Array(arrayBuffer); +array[0] = '1'; +array[1] = '2'; +array[2] = '3'; +array[3] = '4'; +array[4] = '5'; try { const buf = buffer.from(arrayBuffer, 6, 1); } catch (err) { @@ -1644,10 +1651,10 @@ let buf = buffer.from([1, -2]); console.log(buf.readUInt8(0).toString()); console.log(buf.readUInt8(1).toString()); -let buf = buffer.allocUninitializedFromPool(4); -buf.writeUInt8(0x42); +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt8(0x42); try { - let ref = buf.readUInt8(4).toString(16); + let ref = buf1.readUInt8(4).toString(16); } catch (err) { console.log("readUInt8 exception: " + JSON.stringify(err)); } @@ -2430,9 +2437,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeBigUInt64LE(0xdecafafecacefaden, 0); -let buf = buffer.allocUninitializedFromPool(8); +let buf1 = buffer.allocUninitializedFromPool(8); try { - let ref = buf.writeBigUInt64LE(0xdecafafecacefaden, 1); + let ref = buf1.writeBigUInt64LE(0xdecafafecacefaden, 1); } catch (err) { console.log("writeBigUInt64LE exception: " + JSON.stringify(err)); } @@ -2522,9 +2529,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.allocUninitializedFromPool(8); buf.writeDoubleLE(123.456, 0); -let buf = buffer.allocUninitializedFromPool(8); +let buf1 = buffer.allocUninitializedFromPool(8); try { - let ref = buf.writeDoubleLE(123.456, 1); + let ref = buf1.writeDoubleLE(123.456, 1); } catch (err) { console.log("writeDoubleLE exception: " + JSON.stringify(err)); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 63f8bccac119926565f26255908d60c15c88c489..2fa78df889c3b29a0c2b7c3e993e5ff22233b778 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,7 +1,5 @@ # AbilityInfo - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -9,7 +7,9 @@ Ability信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取 -## AbilityInfo +## AbilityInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[AbilityInfo](js-apis-bundleManager-abilityInfo.md)替代。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework @@ -28,7 +28,7 @@ Ability信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取 | backgroundModes | number | 是 | 否 | 表示后台服务的类型
此属性仅可在FA模型下使用 | | isVisible | boolean | 是 | 否 | 判断Ability是否可以被其他应用调用 | | formEnabled | boolean | 是 | 否 | 判断Ability是否提供卡片能力
此属性仅可在FA模型下使用 | -| type | AbilityType | 是 | 否 | Ability类型
此属性仅可在FA模型下使用 | +| type | AbilityType | 是 | 否 | Ability类型
此属性仅可在FA模型下使用 | | orientation | DisplayOrientation | 是 | 否 | Ability的显示模式 | | launchMode | LaunchMode | 是 | 否 | Ability的启动模式 | | permissions | Array\ | 是 | 否 | 被其他应用Ability调用时需要申请的权限集合
通过传入GET_ABILITY_INFO_WITH_PERMISSION获取 | @@ -40,13 +40,5 @@ Ability信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取 | uri | string | 是 | 否 | 获取Ability的统一资源标识符(URI)
此属性仅可在FA模型下使用 | | labelId | number | 是 | 否 | Ability的标签id | | subType | AbilitySubType | 是 | 否 | Ability中枚举使用的模板的子类型
此属性仅可在FA模型下使用 | -| metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | 是 | 否 | ability的自定义信息
通过传入GET_ABILITY_INFO_WITH_METADATA获取 | -| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | 是 | 否 | ability的元信息
通过传入GET_ABILITY_INFO_WITH_METADATA获取 | -| enabled8+ | boolean | 是 | 否 | ability是否可用 | -| supportWindowMode9+ | Array\<[SupportWindowMode](js-apis-Bundle.md)> | 是 | 否 | ability支持的窗口模式 | -| maxWindowRatio9+ | number | 是 | 否 | ability支持的最大的窗口比例 | -| minWindowRatio9+ | number | 是 | 否 | ability支持的最小的窗口比 | -| maxWindowWidth9+ | number | 是 | 否 | ability支持的最大的窗口宽度 | -| minWindowWidth9+ | number | 是 | 否 | ability支持的最小的窗口宽度 | -| maxWindowHeight9+ | number | 是 | 否 | ability支持的最大的窗口高度 | -| minWindowHeight9+ | number | 是 | 否 | ability支持的最小的窗口高度 | \ No newline at end of file +| metadata8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | 是 | 否 | ability的元信息
通过传入GET_ABILITY_INFO_WITH_METADATA获取 | +| enabled8+ | boolean | 是 | 否 | ability是否可用 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 0df396ac7138d98d5ab097dab6cc4144a10d3f78..22be837c08a46a449ff5c101abe1b8965c44e667 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -5,7 +5,9 @@ 应用程序信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取 -## ApplicationInfo +## ApplicationInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)替代。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework @@ -20,10 +22,8 @@ | enabled | boolean | 是 | 否 | 判断应用程序是否可以使用,默认为true。 | | label | string | 是 | 否 | 应用程序的标签。 | | labelId(deprecated) | string | 是 | 否 | 应用程序的标签id。
\- **说明:** 从API version 9开始废弃,使用labelIndex。 | -| labelIndex9+ | number | 是 | 否 | 应用程序的标签索引。 | | icon | string | 是 | 否 | 应用程序的图标。 | | iconId(deprecated) | string | 是 | 否 | 应用程序的图标id。
\- **说明:** 从API version 9开始废弃,使用iconIndex。 | -| iconIndex9+ | number | 是 | 否 | 应用程序的图标索引。 | | process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称。 | | supportedModes | number | 是 | 否 | 应用程序支持的运行模式。 | | moduleSourceDirs | Array\ | 是 | 否 | 应用程序的资源存放的相对路径。 | @@ -32,14 +32,7 @@ | entryDir | string | 是 | 否 | 应用程序的文件保存路径。 | | codePath8+ | string | 是 | 否 | 应用程序的安装目录。 | | metaData8+ | Map\> | 是 | 否 | 应用程序的自定义元信息。
通过传入GET_APPLICATION_INFO_WITH_METADATA获取 | -| metadata9+ | Map\> | 是 | 否 | 应用程序的元信息。
通过传入GET_APPLICATION_INFO_WITH_METADATA获取 | | removable8+ | boolean | 是 | 否 | 应用程序是否可以被移除。 | | accessTokenId8+ | number | 是 | 否 | 应用程序的accessTokenId。 | | uid8+ | number | 是 | 否 | 应用程序的uid。 | -| entityType8+ | string | 是 | 否 | 应用程序的实体类型。 | -| fingerprint9+ | string | 是 | 否 | 应用程序的签名证书指纹信息,即开发者申请的签名证书的sha256值。
通过传入GET_APPLICATION_INFO_WITH_CERTIFICATE_FINGERPRINT获取 | -| iconResource9+ | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的图标资源信息。 | -| labelResource9+ | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的标签资源信息。 | -| descriptionResource9+ | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的描述资源信息。 | -| appDistributionType9+ | string | 是 | 否 | 应用程序签名证书的分发类型,分为:app_gallery、enterprise、os_integration和crowdtesting。 | -| appProvisionType9+ | string | 是 | 否 | 应用程序签名证书文件的类型,分为debug和release两种类型。| \ No newline at end of file +| entityType8+ | string | 是 | 否 | 应用程序的实体类型。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md index 7f02dae5ef699282f86ca9a9f996cf1460fce963..e70bddfecca21131c06e4189a1f8716b609a2290 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,15 +1,13 @@ # BundleInfo - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - - 应用包的信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取。 -## BundleInfo +## BundleInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[BundleInfo](js-apis-bundleManager-bundleInfo.md)替代。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework。 @@ -38,11 +36,12 @@ | minCompatibleVersionCode | number | 是 | 否 | 分布式场景下的应用包兼容的最低版本。 | | entryInstallationFree | boolean | 是 | 否 | Entry是否支持免安装。 | | reqPermissionStates8+ | Array\ | 是 | 否 | 申请权限的授予状态。 | -| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | 是 | 否 | ability的可扩展信息
通过传入GET_BUNDLE_WITH_EXTENSION_ABILITY获取。 | -## ReqPermissionDetail +## ReqPermissionDetail(deprecated) + +> 从API version 9开始不再维护,建议使用[ReqPermissionDetail](js-apis-bundleManager-bundleInfo.md)替代。 应用运行时需向系统申请的权限集合的详细信息。 @@ -52,12 +51,13 @@ | --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | 是 | 是 | 需要使用的权限名称。 | | reason | string | 是 | 是 | 描述申请权限的原因。 | -| reasonId9+ | number | 是 | 是 | 描述申请权限的原因ID。 | | usedScene | [UsedScene](#usedscene) | 是 | 是 | 权限使用的场景和时机。 | -## UsedScene +## UsedScene(deprecated) + +> 从API version 9开始不再维护,建议使用[UsedScene](js-apis-bundleManager-bundleInfo.md)替代。 描述权限使用的场景和时机。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index eee0ad7c629dfc3250e20aaaf144251294b07f01..8a92eae11a38500e03159f86a522f28d0124c94f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -1,17 +1,13 @@ # BundleInstaller - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +在设备上安装、升级和卸载应用 +## BundleInstaller.install(deprecated) -在设备上安装、升级和删除捆绑包 - - - -## BundleInstaller.install +> 从API version 9开始不再维护,建议使用[install](js-apis-installer.md)替代。 install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -35,7 +31,9 @@ SystemCapability.BundleManager.BundleFramework | param | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | | callback | AsyncCallback<[InstallStatus](#installstatus)> | 是 | 程序启动作为入参的回调函数,返回安装状态信息。 | -## BundleInstaller.uninstall +## BundleInstaller.uninstall(deprecated) + +> 从API version 9开始不再维护,建议使用[uninstall](js-apis-installer.md)替代。 uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -59,7 +57,9 @@ SystemCapability.BundleManager.BundleFramework | param | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | | callback | AsyncCallback<[InstallStatus](#installstatus)> | 是 | 程序启动作为入参的回调函数,返回安装状态信息。 | -## BundleInstaller.recover8+ +## BundleInstaller.recover(deprecated) + +> 从API version 9开始不再维护,建议使用[recover](js-apis-installer.md)替代。 recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; @@ -83,20 +83,7 @@ SystemCapability.BundleManager.BundleFramework | param | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数。 | | callback | AsyncCallback<[InstallStatus](#installstatus)> | 是 | 程序启动作为入参的回调函数,返回安装状态信息。 | -## HashParam9+ - -应用程序安装卸载信息 - - **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - - **系统API:** 此接口为系统接口,三方应用不支持调用 - -| 名称 | 类型 | 说明 | -| ---------- | ------ | ---------------- | -| moduleName | string | 应用程序模块名称 | -| hashValue | string | 哈希值 | - -## InstallParam +## InstallParam(deprecated) 应用程序安装卸载信息 @@ -109,10 +96,8 @@ SystemCapability.BundleManager.BundleFramework | userId | number | 指示用户id | | installFlag | number | 指示安装标志 | | isKeepData | boolean | 指示参数是否有数据 | -| hashParams9+ | Array<[HashParam](#hashparam)> | 哈希值参数 | -| crowdtestDeadline9+ | number | 测试包的被杀死时间 | -## InstallStatus +## InstallStatus(deprecated) 应用程序安装状态 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md index a8422df7d701782aa7e9e492601f66bbc13b4639..2133578c207d3a0f7fbae3378179d3f5cb57d3bd 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -21,5 +21,4 @@ ElementName信息,通过接口[Context.getElementName](js-apis-Context.md)获 | bundleName | string | 是 | 是 | 应用包名。 | | abilityName | string | 是 | 是 | Ability名称。 | | uri | string | 是 | 是 | 资源标识符。 | -| shortName | string | 是 | 是 | Ability短名称。 | -| moduleName9+ | string | 是 | 是 | Ability所属的HAP包的名称。 | \ No newline at end of file +| shortName | string | 是 | 是 | Ability短名称。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md deleted file mode 100644 index e5931cdb591f2bd095b77a7c47980a1ecd8febf0..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md +++ /dev/null @@ -1,31 +0,0 @@ -# ExtensionAbilityInfo - - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - - - -ExtensionAbility信息,未做特殊说明的属性,均通过[getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfo)获取,flag使用[GET_BUNDLE_DEFAULT](js-apis-Bundle.md#bundleflag)获取 - -## ExtensionAbilityInfo - -**系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------------------- | -| bundleName | string | 是 | 否 | 应用包名 | -| moduleName | string | 是 | 否 | ExtensionAbility所属的HAP包的名称 | -| name | string | 是 | 否 | ExtensionAbility名称 | -| labelId | number | 是 | 否 | ExtensionAbility的标签id | -| descriptionId | number | 是 | 否 | ExtensionAbility的描述id | -| iconId | number | 是 | 否 | ExtensionAbility的图标id | -| isVisible | boolean | 是 | 否 | 判断ExtensionAbility是否可以被其他应用调用 | -| extensionAbilityType | bundle.ExtensionAbilityType | 是 | 否 | ExtensionAbility类型 | -| permissions | Array\ | 是 | 否 | 被其他应用ExtensionAbility调用时需要申请的权限集合 | -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | 应用程序的配置信息 | -| metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | 是 | 否 | ExtensionAbility的元信息 | -| enabled | boolean | 是 | 否 | ExtensionAbility是否可用 | -| readPermission | string | 是 | 否 | 读取ExtensionAbility数据所需的权限 | -| writePermission | string | 是 | 否 | 向ExtensionAbility写数据所需的权限 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 8cb5642e31bd0805ae7b5f0424406506c1df763d..fdb7fdbd8aa2d179dc5a37e224e5d765cd12551b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -9,7 +9,9 @@ Hap模块信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取 -## HapModuleInfo +## HapModuleInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)替代。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework @@ -32,8 +34,4 @@ Hap模块信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获 | moduleName | string | 是 | 否 | 模块名 | | mainAbilityName | string | 是 | 否 | 入口Ability名称 | | installationFree | boolean | 是 | 否 | 是否支持免安装 | -| mainElementName9+ | string | 是 | 否 | 入口ability信息 | -| extensionAbilityInfo9+ | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | 是 | 否 | extensionAbility信息 | -| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | 是 | 否 | Ability的元信息 | -| hashValue9+ | string | 是 | 否 | Module的Hash值
通过传入GET_BUNDLE_WITH_HASH_VALUE获取 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md index 845e0fadda68e90bc71abb3efd0409c8947e3c62..b4b0ddac773a668d6b6bb264b690d93ede117db9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -9,7 +9,9 @@ LauncherAbilityInfo信息,通过接口[innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager.md)获取。 -## LauncherAbilityInfo +## LauncherAbilityInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)替代。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 3e8cd9e8069be8f116527e831d7eadb6ec407124..6d43d101e93aefcdff8da4b7d102dea7ee7a9e92 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -1,20 +1,13 @@ # ModuleInfo - - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - - 应用程序的模块信息 -## ModuleInfo +## ModuleInfo(deprecated) +> 从API version 9开始不再维护,建议使用[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)替代。 **系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - - - | 名称 | 类型 | 可读 | 可写 | 说明 | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | 是 | 否 | 模块名称 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index 86621d7f8b6ae60fef3b10fcdc9b5ed9b461577f..83ea268a279b928a8cfca0969ab827b471341c37 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -9,7 +9,9 @@ 配置文件中定义的权限详细信息 -## **PermissionDef** +## **PermissionDef**(deprecated) + +> 从API version 9开始不再维护,建议使用[PermissionDef](js-apis-bundleManager-permissionDef.md)替代。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index e5460e4565189b78098c79ff7eaaf4820ecdd65d..f6f6c7f55cca6dd02909085134ae24c1723ba21a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -23,7 +23,6 @@ | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | 是 | 否 | 快捷方式的目标捆绑包 | -| targetModule9+ | string | 是 | 否 | 快捷方式的目标模块 | | targetClass | string | 是 | 否 | 快捷方式所需的目标类 | ## ShortcutInfo(deprecated) @@ -46,5 +45,4 @@ | wants | Array<[ShortcutWant](#shortcutwant)> | 是 | 否 | 快捷方式所需要的信息 | | isStatic | boolean | 是 | 否 | 快捷方式是否为静态 | | isHomeShortcut | boolean | 是 | 否 | 快捷方式是否为主页面快捷方式 | -| isEnabled | boolean | 是 | 否 | 是否启用快捷方式 | -| moduleName9+ | string | 是 | 否 | 快捷方式的模块名 | \ No newline at end of file +| isEnabled | boolean | 是 | 否 | 是否启用快捷方式 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..9a76c507f1878ded89530ef32d94b7b5dc363d92 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-abilityInfo.md @@ -0,0 +1,52 @@ +# AbilityInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +Ability信息,未做特殊说明的属性,均通过[GET_ABILITY_INFO_DEFAULT](js-apis-bundleManager.md)获取 + +## AbilityInfo + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | +| bundleName | string | 是 | 否 | 应用包名 | +| moduleName | string | 是 | 否 | Ability所属的HAP包的名称 | +| name | string | 是 | 否 | Ability名称 | +| label | string | 是 | 否 | Ability对用户显示的名称 | +| labelId | number | 是 | 否 | Ability的标签资源id | +| description | string | 是 | 否 | Ability的描述 | +| descriptionId | number | 是 | 否 | Ability的描述资源id | +| icon | string | 是 | 否 | Ability的图标资源文件索引 | +| iconId | number | 是 | 否 | Ability的图标资源id | +| process | string | 是 | 否 | Ability的进程,如果不设置,默认为包的名称 | +| isVisible | boolean | 是 | 否 | 判断Ability是否可以被其他应用调用 | +| type | AbilityType | 是 | 否 | Ability类型
此属性仅可在FA模型下使用 | +| orientation | DisplayOrientation | 是 | 否 | Ability的显示模式 | +| launchType | number | 是 | 否 | Ability的启动模式 | +| permissions | Array\ | 是 | 否 | 被其他应用Ability调用时需要申请的权限集合,通过传入GET_ABILITY_INFO_WITH_PERMISSION获取 | +| readPermission | string | 是 | 否 | 读取Ability数据所需的权限
此属性仅可在FA模型下使用 | +| writePermission | string | 是 | 否 | 向Ability写数据所需的权限
此属性仅可在FA模型下使用 | +| uri | string | 是 | 否 | 获取Ability的统一资源标识符(URI)
此属性仅可在FA模型下使用 | +| deviceTypes | Array\ | 是 | 否 | Ability支持的设备类型 | +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 是 | 否 | 应用程序的配置信息,通过传入GET_ABILITY_INFO_WITH_APPLICATION获取 | +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | 是 | 否 | ability的元信息,通过传入GET_ABILITY_INFO_WITH_METADATA获取 | +| enabled | boolean | 是 | 否 | ability是否可用 | +| supportWindowModes | Array\<[SupportWindowMode](js-apis-bundleManager.md)> | 是 | 否 | ability支持的窗口模式 | +| windowSize|[WindowSize](#windowsize) | 是 | 否 | 表示窗口尺寸| + +## WindowSize + +描述窗口尺寸。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------| ------- | ---- | ---- | ---------------------------------- | +| maxWindowRatio | number | 是 | 否 | 表示自由窗口状态下窗口的最大宽高比;取值范围0-1 | +| minWindowRatio | number | 是 | 否 | 表示自由窗口状态下窗口的最小宽高比;取值范围0-1 | +| maxWindowWidth | number | 是 | 否 | 表示自由窗口状态下窗口的最大宽度,宽度单位为vp | +| minWindowWidth | number | 是 | 否 | 表示自由窗口状态下窗口的最小宽度,宽度单位为vp | +| maxWindowHeight | number | 是 | 否 | 表示自由窗口状态下窗口的最大高度,宽度单位为vp | +| minWindowHeight | number | 是 | 否 | 表示自由窗口状态下窗口的最小高度,宽度单位为vp | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..3ebe7650691d6bf1bb03bd18f55a16c98b70b12d --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-applicationInfo.md @@ -0,0 +1,33 @@ +# ApplicationInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +应用程序信息,未做特殊说明的属性,均通过[GET_APPLICATION_INFO_DEFAULT](js-apis-bundleManager.md)获取 + +## ApplicationInfo + +**系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| name | string | 是 | 否 | 应用程序的名称 | +| description | string | 是 | 否 | 标识应用的描述信息 | +| descriptionId | number | 是 | 否 | 标识应用的描述信息的资源id | +| enabled | boolean | 是 | 否 | 判断应用程序是否可以使用,默认为true | +| label | string | 是 | 否 | 标识应用的名称 | +| labelId | number | 是 | 否 | 标识应用名称的资源id | +| icon | string | 是 | 否 | 应用程序的图标 | +| iconId | number | 是 | 否 | 应用程序图标的资源id | +| process | string | 是 | 否 | 应用程序的进程,如果不设置,默认为包的名称。 | +| permissions | Array\ | 是 | 否 | 访问应用程序所需的权限,通过传入GET_APPLICATION_INFO_WITH_PERMISSION获取 | +| entryDir | string | 是 | 否 | 应用程序的文件保存路径 | +| codePath | string | 是 | 否 | 应用程序的安装目录 | +| metadata | Map\> | 是 | 否 | 应用程序的元信息,通过传入GET_APPLICATION_INFO_WITH_METADATA获取 | +| removable | boolean | 是 | 否 | 应用程序是否可以被移除 | +| accessTokenId | number | 是 | 否 | 应用程序的accessTokenId | +| uid | number | 是 | 否 | 应用程序的uid | +| iconResource | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的图标资源信息 | +| labelResource | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的标签资源信息 | +| descriptionResource | [Resource](js-apis-resource-manager.md#resource9) | 是 | 否 | 应用程序的描述资源信息 | +| appDistributionType | string | 是 | 否 | 应用程序签名证书的分发类型,分为:app_gallery、enterprise、os_integration和crowdtesting | +| appProvisionType | string | 是 | 否 | 应用程序签名证书文件的类型,分为debug和release两种类型 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..def8a62f80647ecb7f4071785990e41cc6122acd --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-bundleInfo.md @@ -0,0 +1,63 @@ +# BundleInfo +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +应用包的信息,未做特殊说明的属性,均通过[GET_BUNDLE_INFO_DEFAULT](js-apis-bundle-bundleManager)获取。 + +## BundleInfo + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| name | string | 是 | 否 | 应用包的名称 | +| vendor | string | 是 | 否 | 应用包的供应商 | +| versionCode | number | 是 | 否 | 应用包的版本号 | +| versionName | string | 是 | 否 | 应用包的版本文本描述信息 | +| minCompatibleVersionCode | number | 是 | 否 | 分布式场景下的应用包兼容的最低版本 | +| targetVersion | number | 是 | 否 | 该标签标识应用运行目标版本 | +| appInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 是 | 否 | 应用程序的配置信息,通过传入GET_BUNDLE_INFO_WITH_APPLICATION获取 | +| hapModulesInfo | Array\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | 是 | 否 | 模块的配置信息,通过传入GET_BUNDLE_INFO_WITH_HAP_MODULE获取 | +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | 是 | 否 | 应用运行时需向系统申请的权限集合的详细信息,通过传入GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION获取| +| permissionGrantStates | Array\<[PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate)> | 是 | 否 | 申请权限的授予状态,通过传入GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION获取 | +| signatureInfo | [SignatureInfo](#signatureinfo) | 是 | 否 | 应用包的签名信息,通过传入GET_BUNDLE_INFO_WITH_SIGNATURE_INFO获取 | +| installTime | number | 是 | 否 | 应用包安装时间 | +| updateTime | number | 是 | 否 | 应用包更新时间 | + + +## ReqPermissionDetail + +应用运行时需向系统申请的权限集合的详细信息。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------- | ----------------------- | ---- | ---- | ---------------------| +| name | string | 是 | 是 | 需要使用的权限名称 | +| reason | string | 是 | 是 | 描述申请权限的原因 | +| reasonId | number | 是 | 是 | 描述申请权限的原因ID | +| usedScene | [UsedScene](#usedscene) | 是 | 是 | 权限使用的场景和时机 | + + + +## UsedScene + +描述权限使用的场景和时机。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | -------------- | ---- | ---- | --------------------------- | +| abilities | Array\ | 是 | 是 | 使用到该权限的Ability集合 | +| when | string | 是 | 是 | 使用该权限的时机。 | + +## SignatureInfo + +描述应用包的签名信息。 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | -------------- | ---- | ---- | --------------------------- | +| appId | string | 是 | 否 | 应用的appId | +|fingerprint| string | 是 | 否 | 应用包的指纹信息 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-dispatchInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-dispatchInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..c0efbfc7b07ccf28d872980cb2b000e8606dc5eb --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-dispatchInfo.md @@ -0,0 +1,17 @@ +# DispatchInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +免安装结构体和接口版本信息类,通过接口[freeInstall.getDispatchInfo](js-apis-freeInstall.md)获取。 + +## DispatchInfo + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- | ------------------------ | +| version | string | 是 | 否 | dispatchInfo结构体版本信息 | +| dispatchAPIVersion | string | 是 | 否 | 免安装接口版本信息 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 7c8e9520a08430cc709a9731c16f72dc7b8412c2..6f97ffb60f13bc93bcb7d8b371e9f437695775fb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -1,13 +1,13 @@ # ElementName -ElementName信息,通过接口[Context.getElementName](js-apis-Context.md)获取。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +ElementName信息,通过接口[Context.getElementName](js-apis-Context.md)获取。 ## ElementName - **系统能力:** SystemCapability.BundleManager.BundleFramework + **系统能力:** SystemCapability.BundleManager.BundleFramework.Core | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------------------- | ---------| ---- | ---- | ------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..7df10c9c6138beebf7e3f9d65325c6b26c8cd4f6 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-extensionAbilityInfo.md @@ -0,0 +1,26 @@ +# ExtensionAbilityInfo +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +ExtensionAbility信息,未做特殊说明的属性,均通过[getBundleInfo](js-apis-bundleManager.md)获取,flag使用[GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY](js-apis-bundleManager.md#bundleflag)获取 + +## ExtensionAbilityInfo + +**系统能力**: SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------------- | ----------------------------------------------------------- | ---- | ---- | -------------------------------------------------- | +| bundleName | string | 是 | 否 | 应用包名 | +| moduleName | string | 是 | 否 | ExtensionAbility所属的HAP包的名称 | +| name | string | 是 | 否 | ExtensionAbility名称 | +| labelId | number | 是 | 否 | ExtensionAbility的标签资源id | +| descriptionId | number | 是 | 否 | ExtensionAbility的描述资源id | +| iconId | number | 是 | 否 | ExtensionAbility的图标资源id | +| isVisible | boolean | 是 | 否 | 判断ExtensionAbility是否可以被其他应用调用 | +| extensionAbilityType | bundle.ExtensionAbilityType | 是 | 否 | ExtensionAbility类型 | +| permissions | Array\ | 是 | 否 | 被其他应用ExtensionAbility调用时需要申请的权限集合 | +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 是 | 否 | 应用程序的配置信息 | +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | 是 | 否 | ExtensionAbility的元信息 | +| enabled | boolean | 是 | 否 | ExtensionAbility是否可用 | +| readPermission | string | 是 | 否 | 读取ExtensionAbility数据所需的权限 | +| writePermission | string | 是 | 否 | 向ExtensionAbility写数据所需的权限 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..339c16a691e84344290f1ab09fa86836a1068732 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-hapModuleInfo.md @@ -0,0 +1,27 @@ +# HapModuleInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## HapModuleInfo + +**系统能力**: SystemCapability.BundleManager.BundleFramework.Core + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | +| name | string | 是 | 否 | 模块名称 | +| icon | string | 是 | 否 | 模块图标 | +| iconId | number | 是 | 否 | 模块图标资源id | +| label | string | 是 | 否 | 模块标签 | +| labelId | number | 是 | 否 | 模块标签资源id | +| description | string | 是 | 否 | 模块描述信息 | +| descriptionId | number | 是 | 否 | 描述信息资源id | +| mainElementName | string | 是 | 否 | 入口ability信息 | +| abilitiesInfo | Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | 是 | 否 | Ability信息 | +| extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | 是 | 否 | extensionAbility信息 | +| metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | 是 | 否 | Ability的元信息 | +| deviceTypes | Array\ | 是 | 否 | 支持运行的设备类型 | +| installationFree | boolean | 是 | 否 | 是否支持免安装 | +| hashValue | string | 是 | 否 | Module的Hash值 | +| moduleSourceDir | string | 是 | 否 | Module的路径| + diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..027a2c688da32fc8a2355f1b13b26f0503e04d81 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-launcherAbilityInfo.md @@ -0,0 +1,17 @@ +# LauncherAbilityInfo +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +## LauncherAbilityInfo + + **系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher。 + + **系统:** 系统接口,三方应用不支持调用。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------ | +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 是 | 否 | launcher ability的应用程序的配置信息 | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | 否 | launcher ability的ElementName信息 | +| labelId | number | 是 | 否 | launcher ability的标签ID | +| iconId | number | 是 | 否 | launcher ability的图标ID | +| userId | number | 是 | 否 | launcher ability的用户ID | +| installTime | number | 是 | 否 | launcher ability的安装时间 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-metadata.md similarity index 59% rename from zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md rename to zh-cn/application-dev/reference/apis/js-apis-bundleManager-metadata.md index f592ab99dfbbdfb44a5b5c00eec76a26ce9df2eb..3babaf74d2acb75d33852b71933399ecdf5a3705 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-metadata.md @@ -1,22 +1,11 @@ -# Metadata - - - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - - - -元数据信息 - -## Metadata - -**系统能力**: 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework - - - -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | ------ | ---- | ---- | ---------- | -| name | string | 是 | 是 | 元数据名称 | -| value | string | 是 | 是 | 元数据值 | +# Metadata +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +描述的module、ability、extensionAbility配置信息,标签值为数组类型,该标签下的配置只对当前module、或者ability、或者extensionAbility生效。 +## Metadata +**系统能力**: SystemCapability.BundleManager.BundleFramework.Core +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ---------- | +| name | string | 是 | 是 | 元数据名称 | +| value | string | 是 | 是 | 元数据值 | | resource | string | 是 | 是 | 元数据资源 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-packInfo.md similarity index 66% rename from zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md rename to zh-cn/application-dev/reference/apis/js-apis-bundleManager-packInfo.md index 041c7d02357af4c4915cefa6faa0471aca2ee29a..76ca933ed0edd2ce0c882e153f8610834e02f3de 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-packInfo.md @@ -1,52 +1,41 @@ # PackInfo -> **说明:** -> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - -应用包信息,通过接口[bundle.getBundlePackInfo](js-apis-Bundle.md)获取。 - -## BundlePackFlag -**系统API:** 此接口为系统接口,三方应用不支持调用 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -| 名称 | 值 | 说明 | -| ------------------ | ---------- | ---------------------------------- | -| GET_PACK_INFO_ALL | 0x00000000 | 获取应用包pack.info的所有信息。 | -| GET_PACKAGES | 0x00000001 | 获取应用包pack.info的package信息。 | -| GET_BUNDLE_SUMMARY | 0x00000002 | 获取应用包pack.info的bundle摘要。 | -| GET_MODULE_SUMMARY | 0x00000004 | 获取应用包pack.info的module摘要。 | +应用包信息,通过接口[freeInstall.getBundlePackInfo](js-apis-freeInstall.md)获取。 ## BundlePackInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | --------------------------------------- | ---- | ---- | ----------------------------- | -| packages | Array\<[PackageConfig](#packageconfig)> | 是 | 否 | 获取pack.info的包信息。 | -| summary | [PackageSummary](#packagesummary) | 是 | 否 | 获取pack.info中的包摘要信息。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | --------------------------------------- | ---- | ---- | ------------------------- | +| packages | Array\<[PackageConfig](#packageconfig)> | 是 | 否 | pack.info的包信息。 | +| summary | [PackageSummary](#packagesummary) | 是 | 否 | pack.info中的包摘要信息。 | ## PackageConfig -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| deviceType | Array\ | 是 | 否 | 包支持的设备类型。 | +| deviceTypes | Array\ | 是 | 否 | 包支持的设备类型。 | | name | string | 是 | 否 | 包的名称。 | | moduleType | string | 是 | 否 | 包的module类型。 | | deliveryWithInstall | boolean | 是 | 否 | 是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | -## PackageSummary +## PackageSummary -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | --------------------------------------------- | ---- | ---- | -------------------- | @@ -55,9 +44,9 @@ ## BundleConfigInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ---------- | ------------------- | ---- | ---- | ---------------------------------- | @@ -66,60 +55,61 @@ ## ModuleConfigInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- | +| mainAbility | string | 是 | 否 | 应用主ability的名称。 | | apiVersion | [ApiVersion](#apiversion) | 是 | 否 | module的api版本。 | | deviceType | Array\ | 是 | 否 | module的设备类型。 | | distro | [ModuleDistroInfo](#moduledistroinfo) | 是 | 否 | module发行版信息。 | -| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | 是 | 否 | module的元能力信息。 | -| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | 是 | 否 | 描述extensionAbilities的配置信息。 | +| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | 是 | 否 | module包含的ability组件信息。 | +| extensionAbilities | Array\<[ExtensionAbilities](#extensionability)> | 是 | 否 | 描述extensionAbilities的配置信息。 | -## ModuleDistroInfo +## ModuleDistroInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | -| mainAbility | string | 是 | 否 | 主要能力的名称。 | | deliveryWithInstall | boolean | 是 | 否 | 是否在用户主动安装的时候安装,true表示主动安装时安装,false表示主动安装时不安装。 | | installationFree | boolean | 是 | 否 | 表示当前HAP是否支持免安装特性。true表示支持免安装特性,且符合免安装约束,false表示不支持免安装特性。 | | moduleName | string | 是 | 否 | module名称。 | | moduleType | string | 是 | 否 | module类型。 | -## ModuleAbilityInfo +## ModuleAbilityInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| name | string | 是 | 否 | 表示当前ability的逻辑名,该名称在整个应用要唯一。 | +| name | string | 是 | 否 | 表示当前ability的名称,该名称在整个应用要唯一。 | | label | string | 是 | 否 | 表示ability对用户显示的名称,标签值配置为该名称的资源索引以支持多语言。 | | visible | boolean | 是 | 否 | 表示ability是否可以被其它应用调用,true表示可以被其它应用调用,false表示不可以被其它应用调用。 | | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | 是 | 否 | 卡片信息。 | -## ExtensionAbilities +## ExtensionAbility -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| name | string | 是 | 否 | 表示该ExtensionAbility的名称 | | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | 是 | 否 | 表示form卡片的规格,form卡片是可以嵌入桌面上并接收定时更新的应用简要视图。 | ## AbilityFormInfo -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | @@ -128,29 +118,29 @@ | updateEnabled | boolean | 是 | 否 | 表示该卡片是否支持定时刷新,true表示卡片支持定时刷新,false表示不支持。 | | scheduledUpdateTime | string | 是 | 否 | 表示卡片定点刷新的时间,采用24小时计数,精确到分钟。 | | updateDuration | number | 是 | 否 | 表示卡片定时刷新的更新频率,单位为30分钟,取值为30的倍数值。卡片的最高频率为每30分钟刷新一次,和定点刷新二选一,二者都配置的情况下,定时优先。 | -| supportDimensions | Array\ | 是 | 否 | 表示卡片外观规格,取值为“1\*2”,“2\*2”,“2\*4”,“4\*4”,定义卡片时至少要指定一个卡片规格。 | -| defaultDimension | number | 是 | 否 | 表示卡片默认外观规格,取值必须在supportDimensions配置的列表中。 | +| supportDimensions | Array\ | 是 | 否 | 表示卡片外观规格,取值为“1\*2”,“2\*2”,“2\*4”,“4\*4”,定义卡片时至少要指定一个卡片规格。 | +| defaultDimension | string | 是 | 否 | 表示卡片默认外观规格,取值必须在supportDimensions配置的列表中。 | ## ApiVersion -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 系统接口,三方应用不支持调用。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | ------ | ---- | ---- | -------------------- | | releaseType | string | 是 | 否 | 版本的名称。 | | compatible | number | 是 | 否 | 版本的最小兼容代码。 | -| target | numbe | 是 | 否 | 目标版本号。 | +| target | number | 是 | 否 | 目标版本号。 | ## Version -**系统API:** 此接口为系统接口,三方应用不支持调用 +**系统接口:** 此接口为系统接口。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework +**系统能力:** SystemCapability.BundleManager.BundleFrameWork.FreeInstall | 名称 | 类型 | 可读 | 可写 | 说明 | | ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ | | minCompatibleVersionCode | number | 是 | 否 | 能够兼容的最低历史版本号,用于跨设备兼容性判断。该值为32位整型数值,非负整数。 | | name | string | 是 | 否 | 标识版本号的文字描述,用于向用户展示。 | -| code | number | 是 | 否 | 标识应用的版本号,值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。 | \ No newline at end of file +| code | number | 是 | 否 | 标识应用的版本号,值为32位非负整数。此数字仅用于确定某个版本是否比另一个版本更新,数值越大表示版本越高。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md new file mode 100644 index 0000000000000000000000000000000000000000..5e341eaadc5b689acd15a28e86bd798d50c37b42 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-permissionDef.md @@ -0,0 +1,19 @@ +# PermissionDef + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +配置文件中定义的权限详细信息,通过接口[bundleManager.getPermissionDef](js-apis-bundleManager.md)获取。配置文件中定义的权限详细信息。 + +## **PermissionDef** + + **系统能力:** SystemCapability.BundleManager.BundleFramework.Core + + **系统API:** 系统接口,三方应用不支持调用 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------------- | ------ | ---- | ---- | -------------- | +| permissionName | string | 是 | 否 | 用户权限名称 | +| grantMode | number | 是 | 否 | 权限的授予模式 | +| labelId | number | 是 | 否 | 权限的标签ID | +| descriptionId | number | 是 | 否 | 描述权限的ID | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md index 2ddcaff30332d16ef4cdba1e950a2ed3132a5f1d..6a8c9700871260e6071f78437a64e0b156385dd4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md @@ -1,11 +1,9 @@ # RemoteAbilityInfo -包含远程的ability信息,通过接口[distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md)获取。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -本模块接口为系统接口。 +包含远程的ability信息,通过接口[distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md)获取。 ## RemoteAbilityInfo diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 64632e0107e5766cac4eab9ca44e0b8344c0365f..9a71158f07bb069ff2f0a624a786a161e60fad5e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -1,11 +1,9 @@ # ShortcutInfo -应用配置文件中定义的快捷方式信息,FA模型配置在[config.json](../../quick-start/package-structure.md)文件中进行配置,Stage模型配置参考[shortcuts对象内部结构](../../quick-start/stage-structure.md#shortcuts对象内部结构) - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -本模块接口为系统接口。 +本应用配置文件中定义的快捷方式信息,FA模型配置在[config.json](../../quick-start/package-structure.md)文件中进行配置,Stage模型配置参考[shortcuts对象内部结构](../../quick-start/stage-structure.md#shortcuts对象内部结构) ## ShortcutWant diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md new file mode 100644 index 0000000000000000000000000000000000000000..fd627d159f2db1999f72e7cb23ce99517c93f18b --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md @@ -0,0 +1,2848 @@ +# bundleManager模块(JS端SDK接口) + +本模块提供应用信息查询能力,支持BundleInfo、ApplicationInfo、Ability、ExtensionAbility等信息的查询 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +``` +## 权限列表 + +| 权限 | 权限等级 | 描述 | +| ------------------------------------------ | ------------ | ------------------| +| ohos.permission.GET_BUNDLE_INFO | normal | 查询指定应用信息 | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 | +| ohos.permission.REMOVE_CACHE_FILES | system_basic | 清理应用缓存 | +|ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | 设置禁用使能所需的权限 | + +权限等级参考[权限等级说明](../../security/accesstoken-overview.md#权限等级说明)。 + +## 枚举 + +### BundleFlag + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | 说明 | +| ----------------------------------------- | ---------- | ------------------------------------------------------------ | +| GET_BUNDLE_INFO_DEFAULT | 0x00000000 | 用于获取默认bundleInfo,获取的bundleInfo不包含signatureInfo、applicationInfo、hapModuleInfo、ability、extensionAbility和permission的信息 | +| GET_BUNDLE_INFO_WITH_APPLICATION | 0x00000001 | 用于获取包含applicationInfo的bundleInfo,获取的bundleInfo不包含signatureInfo、hapModuleInfo、ability、extensionAbility和permission的信息 | +| GET_BUNDLE_INFO_WITH_HAP_MODULE | 0x00000002 | 用于获取包含hapModuleInfo的bundleInfo,获取的bundleInfo不包含signatureInfo、applicationInfo、ability、extensionAbility和permission的信息 | +| GET_BUNDLE_INFO_WITH_ABILITY | 0x00000004 | 用于获取包含ability的bundleInfo,获取的bundleInfo不包含signatureInfo、applicationInfo、extensionAbility和permission的信息。它不能单独使用,需要与GET_BUNDLE_INFO_WITH_HAP_MODULE一起使用 | +| GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY | 0x00000008 | 用于获取包含extensionAbility的bundleInfo,获取的bundleInfo不包含signatureInfo、applicationInfo、ability 和permission的信息。它不能单独使用,需要与GET_BUNDLE_INFO_WITH_HAP_MODULE一起使用。 | +| GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION | 0x00000010 | 用于获取包含permission的bundleInfo。获取的bundleInfo不包含signatureInfo、applicationInfo、hapModuleInfo、extensionAbility和ability的信息 | +| GET_BUNDLE_INFO_WITH_METADATA | 0x00000020 | 用于获取applicationInfo、moduleInfo和abilityInfo中包含的metadata。它不能单独使用,它需要与GET_BUNDLE_INFO_WITH_APPLICATION、GET_BUNDLE_INFO_WITH_HAP_MODULE、GET_BUNDLE_INFO_WITH_ABILITY、GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY一起使用 | +| GET_BUNDLE_INFO_WITH_DISABLE | 0x00000040 | 用于获取application被禁用的BundleInfo和被禁用的Ability信息。获取的bundleInfo不包含signatureInfo、applicationInfo、hapModuleInfo、ability、extensionAbility和permission的信息 | +| GET_BUNDLE_INFO_WITH_SIGNATURE_INFO | 0x00000080 | 用于获取包含signatureInfo的bundleInfo。获取的bundleInfo不包含applicationInfo、hapModuleInfo、extensionAbility、ability和permission的信息 | + +### ApplicationFlag + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + + **系统接口:** 系统接口,不支持三方应用调用。 + +| 名称 | 值 | 说明 | +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| GET_APPLICATION_INFO_DEFAULT | 0x00000000 | 用于获取默认的applicationInfo,获取的applicationInfo不包含permission和metadata信息 | +| GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000001 | 用于获取包含permission的applicationInfo | +| GET_APPLICATION_INFO_WITH_METADATA | 0x00000002 | 用于获取包含metadata的applicationInfo | +| GET_APPLICATION_INFO_WITH_DISABLE | 0x00000004 | 用于获取包含禁用应用程序的applicationInfo | + +### AbilityFlag + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + + **系统接口:** 系统接口,不支持三方应用调用。 + +| 名称 | 值 | 说明 | +| --------------------------------- | ---------- | ------------------------------------------------------------ | +| GET_ABILITY_INFO_DEFAULT | 0x00000000 | 用于获取默认abilityInfo,获取的abilityInfo不包含permission、metadata和禁用的abilityInfo | +| GET_ABILITY_INFO_WITH_PERMISSION | 0x00000001 | 用于获取包含permission的abilityInfo | +| GET_ABILITY_INFO_WITH_APPLICATION | 0x00000002 | 用于获取包含applicationInfo的abilityInfo | +| GET_ABILITY_INFO_WITH_METADATA | 0x00000004 | 用于获取包含metadata的abilityInfo | +| GET_ABILITY_INFO_WITH_DISABLE | 0x00000008 | 用于获取包含禁用的abilityInfo的abilityInfo | +| GET_ABILITY_INFO_ONLY_SYSTEM_APP | 0x00000010 | 用于仅为系统应用程序获取abilityInfo | + +### ExtensionAbilityFlag + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + + **系统接口:** 系统接口,不支持三方应用调用。 + +| 名称 | 值 | 说明 | +| ------------------------------------------- | ---------- | ------------------------------------------------------------ | +| GET_EXTENSION_ABILITY_INFO_DEFAULT | 0x00000000 | 用于获取默认extensionAbilityInfo。获取的extensionAbilityInfo不包含permission、metadata 和禁用的abilityInfo | +| GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION | 0x00000001 | 用于获取包含permission的extensionAbilityInfo | +| GET_EXTENSION_ABILITY_INFO_WITH_APPLICATION | 0x00000002 | 用于获取包含applicationInfo的extensionAbilityInfo | +| GET_EXTENSION_ABILITY_INFO_WITH_METADATA | 0x00000004 | 用于获取包含metadata的extensionAbilityInfo | + +### ExtensionAbilityType + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | +|:----------------:|:---:| +| FORM | 0 | +| WORK_SCHEDULER | 1 | +| INPUT_METHOD | 2 | +| SERVICE | 3 | +| ACCESSIBILITY | 4 | +| DATA_SHARE | 5 | +| FILE_SHARE | 6 | +| STATIC_SUBSCRIBER| 7 | +| WALLPAPER | 8 | +| BACKUP | 9 | +| WINDOW | 10 | +| ENTERPRISE_ADMIN | 11 | +| THUMBNAIL | 13 | +| PREVIEW | 14 | +| UNSPECIFIED | 255 | + + +### PermissionGrantState + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | +|:----------------:|:---:| +| PERMISSION_DENIED| -1 | +| PERMISSION_GRANTED | 0 | + +### SupportWindowMode + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | +|:----------------:|:---:| +| FULL_SCREEN | 0 | +| SPLIT | 1 | +| FLOATING | 2 | + +### LaunchType + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | +|:----------------:|:---:| +| SINGLETON | 0 | +| STANDARD | 1 | +| SPECIFIED | 2 | + +### AbilityType + + **模型约束:** 仅可在FA模型下使用 + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 | 值 | +|:----------------:|----| +| PAGE | 1 | +| SERVICE | 2 | +| DATA | 3 | + +### DisplayOrientation + + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core。 + +| 名称 |值 | +|:----------------------------------|---| +| UNSPECIFIED |0 | +| LANDSCAPE |1 | +| PORTRAIT |2 | +| FOLLOW_RECENT |3 | +| LANDSCAPE_INVERTED |4 | +| PORTRAIT_INVERTED |5 | +| AUTO_ROTATION |6 | +| AUTO_ROTATION_LANDSCAPE |7 | +| AUTO_ROTATION_PORTRAIT |8 | +| AUTO_ROTATION_RESTRICTED |9 | +| AUTO_ROTATION_LANDSCAPE_RESTRICTED |10| +| AUTO_ROTATION_PORTRAIT_RESTRICTED |11| +| LOCKED |12| + +## 方法 + +### bundleManager.getBundleInfoForSelf + +getBundleInfoForSelf(bundleFlags: [number](#bundleflag)): Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>; + +以异步方法根据给定的bundleFlags获取当前应用的BundleInfo,使用Promise形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------- | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | ------------------------------------- | +| Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Promise对象,返回当前应用的BundleInfo | + +**错误码:** + +错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; +try { + bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { + console.info('getBundleInfoForSelf successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getBundleInfoForSelf failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInfoForSelf failed:' + error.message); +} +``` + +### bundleManager.getBundleInfoForSelf + +getBundleInfoForSelf(bundleFlags: [number](#bundleflag), callback: AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>): void; + +以异步方法根据给定的bundleFlags获取当前应用的BundleInfo,使用callback形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | --------------------- | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的当前应用的BundleInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getBundleInfoForSelf(bundleFlags, (err, data) => { + if (err) { + console.error('getBundleInfoForSelf failed:' + err.message); + } else { + console.info('getBundleInfoForSelf successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getBundleInfoForSelf failed:' + err.message); +} +``` + +### bundleManager.getBundleInfo + +getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void; + +以异步方法根据给定的bundleName、bundleFlags和userId获取BundleInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息| +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的bundleInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; +let userId = 100; + +try { + bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { + if (err) { + console.error('getBundleInfo failed:' + err.message); + } else { + console.info('getBundleInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getBundleInfo failed:' + err.message); +} +``` + +### bundleManager.getBundleInfo + +getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void; + +以异步方法根据给定的bundleName和bundleFlags获取BundleInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的BundleInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getBundleInfo(bundleName, bundleFlags, (err, data) => { + if (err) { + console.error('getBundleInfo failed:' + err.message); + } else { + console.info('getBundleInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getBundleInfo failed:' + err.message); +} +``` + +### bundleManager.getBundleInfo + +getBundleInfo(bundleName: string, bundleFlags: [number](#bundleflag), userId?: number): Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>; + +以异步方法根据给定的bundleName、bundleFlags和userId获取BundleInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | --------------------------- | +| Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Promise对象,返回BundleInfo | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; +let userId = 100; + +try { + bundleManager.getBundleInfo(bundleName, bundleFlags, userId).then((data) => { + console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getBundleInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInfo failed. Cause: ' + error.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getBundleInfo(bundleName, bundleFlags).then((data) => { + console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getBundleInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInfo failed. Cause: ' + error.message); +} + +``` + +### bundleManager.getApplicationInfo + +getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>): void; + +以异步方法根据给定的bundleName、appFlags和userId获取ApplicationInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的ApplicationInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; +let userId = 100; + +try { + bundleManager.getApplicationInfo(bundleName, appFlags, userId, (err, data) => { + if (err) { + console.error('getApplicationInfo failed:' + err.message); + } else { + console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getApplicationInfo failed:' + err.message); +} +``` + +### bundleManager.getApplicationInfo + +getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), callback: AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>): void; + +以异步方法根据给定的bundleName和appFlags获取ApplicationInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的ApplicationInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; + +try { + bundleManager.getApplicationInfo(bundleName, appFlags, (err, data) => { + if (err) { + console.error('getApplicationInfo failed:' + err.message); + } else { + console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getApplicationInfo failed:' + err.message); +} +``` + +### bundleManager.getApplicationInfo + +getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), userId?: number): Promise\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>; + +以异步方法根据给定的bundleName、appFlags和userId获取ApplicationInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | ---------------------------- | +| bundleName | string | 是 | 表示要查询的应用程序包名称 | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | -------------------------------- | +| Promise\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Promise对象,返回ApplicationInfo | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; +let userId = 100; + +try { + bundleManager.getApplicationInfo(bundleName, appFlags, userId).then((data) => { + console.info('getApplicationInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getApplicationInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getApplicationInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getAllBundleInfo + +getAllBundleInfo(bundleFlags: [number](#bundleflag), userId: number, callback: AsyncCallback>): void; + +以异步方法根据给定的bundleFlags和userId获取多个BundleInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | -------------------------------------------------- | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------- | +| 17700004 | The specified userId is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; +let userId = 100; + +try { + bundleManager.getAllBundleInfo(bundleFlags, userId, (err, data) => { + if (err) { + console.error('getAllBundleInfo failed:' + err.message); + } else { + console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAllBundleInfo failed:' + err.message); +} +``` + +### bundleManager.getAllBundleInfo + +getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback>): void; + +以异步方法根据给定的bundleFlags获取多个BundleInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | -------------------------------------------------- | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getAllBundleInfo(bundleFlags, (err, data) => { + if (err) { + console.error('getAllBundleInfo failed:' + err.message); + } else { + console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAllBundleInfo failed:' + err.message); +} +``` + +### bundleManager.getAllBundleInfo + +getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise>; + +以异步方法根据给定的bundleFlags和userId获取多个BundleInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | -------------------------------------------------- | +| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ----------------------------------- | +| Promise> | Promise对象,返回Array\ | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------- | +| 17700004 | The specified userId is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getAllBundleInfo(bundleFlags).then((data) => { + console.info('getAllBundleInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getAllBundleInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getAllBundleInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getAllApplicationInfo + +getAllApplicationInfo(appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback>): void; + +以异步方法根据给定的appFlags和userId获取多个ApplicationInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ------ | ---- | ----------------------------------------------------------- | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------- | +| 17700004 | The specified userId is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; +let userId = 100; + +try { + bundleManager.getAllApplicationInfo(appFlags, userId, (err, data) => { + if (err) { + console.error('getAllApplicationInfo failed:' + err.message); + } else { + console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAllApplicationInfo failed:' + err.message); +} +``` + +### bundleManager.getAllApplicationInfo + +getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallback>): void; + +以异步方法根据给定的appFlags获取多个ApplicationInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ------ | ---- | ----------------------------------------------------------- | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; + +try { + bundleManager.getAllApplicationInfo(appFlags, (err, data) => { + if (err) { + console.error('getAllApplicationInfo failed:' + err.message); + } else { + console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAllApplicationInfo failed:' + err.message); +} +``` + +### bundleManager.getAllApplicationInfo + +getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Promise>; + +以异步方法根据给定的appFlags和userId获取多个ApplicationInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ------ | ---- | ---------------------------------------------------------- | +| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ---------------------------------------- | +| Promise> | Promise对象,返回Array\ | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------- | +| 17700004 | The specified userId is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; + +try { + bundleManager.getAllApplicationInfo(appFlags).then((data) => { + console.info('getAllApplicationInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getAllApplicationInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getAllApplicationInfo failed. Cause: ' + error.message); +} + +``` + +### bundleManager.queryAbilityInfo + +queryAbilityInfo(want: Want, abilityFlags: [number](#abilityflag), userId: number, callback: AsyncCallback>): void; + +以异步方法根据给定的want、abilityFlags和userId获取多个AbilityInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------ | ---- | ------------------------------------------------------- | +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| abilityFlags | [number](#abilityflag) | 是 | 指定返回的AbilityInfo所包含的信息 | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified ability is not found | +| 17700004 | The specified userId is invalid | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId, (err, data) => { + if (err) { + console.error('queryAbilityInfo failed:' + err.message); + } else { + console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('queryAbilityInfo failed:' + err.message); +} +``` + +### bundleManager.queryAbilityInfo + +queryAbilityInfo(want: Want, abilityFlags: [number](#abilityflag), callback: AsyncCallback>): void; + +以异步方法根据给定的want和abilityFlags获取一个或多个AbilityInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------ | ---- | -------------------------------------------------------| +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| abilityFlags | [number](#abilityflag) | 是 | 指定返回的AbilityInfo所包含的信息 | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified ability is not found | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, (err, data) => { + if (err) { + console.error('queryAbilityInfo failed:' + err.message); + } else { + console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('queryAbilityInfo failed:' + err.message); +} +``` + +### bundleManager.queryAbilityInfo + +queryAbilityInfo(want: Want, abilityFlags: [number](#abilityflag), userId?: number): Promise>; + +以异步方法根据给定的want、abilityFlags和userId获取一个或多个AbilityInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------ | ---- | ------------------------------------------------------- | +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| abilityFlags | [number](#abilityflag) | 是 | 表示指定返回的AbilityInfo所包含的信息 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------ | +| Promise> | Promise对象,返回Array\ | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified ability is not found | +| 17700004 | The specified userId is invalid | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((data) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags).then((data) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }) +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.queryExtensionAbilityInfo + +queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId: number, callback: AsyncCallback>): void; + +以异步方法根据给定的want、extensionAbilityType、extensionAbilityFlags和userId获取一个或多个ExtensionAbilityInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型 | +| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志 | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified extensionAbility is not found | +| 17700004 | The specified userId is invalid | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId, (err, data) => { + if (err) { + console.error('queryExtensionAbilityInfo failed:' + err.message); + } else { + console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('queryExtensionAbilityInfo failed:' + err.message); +} +``` + +### bundleManager.queryExtensionAbilityInfo + +queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), callback: AsyncCallback>): void; + +以异步方法根据给定的want、extensionAbilityType和extensionAbilityFlags获取一个或多个ExtensionAbilityInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型 | +| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志 | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified extensionAbility is not found| +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, (err, data) => { + if (err) { + console.error('queryExtensionAbilityInfo failed:' + err.message); + } else { + console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('queryExtensionAbilityInfo failed:' + err.message); +} +``` + +### bundleManager.queryExtensionAbilityInfo + +queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId?: number): Promise>; + +以异步方法根据给定的want、extensionAbilityType、extensionAbilityFlags和userId获取ExtensionAbilityInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| --------------------- | -------------------- | ---- | ------------------------------------------------------ | +| want | Want | 是 | 表示包含要查询的应用程序包名称的Want | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型 | +| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志 | +| userId | number | 否 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------------------- | +| Promise> | Promise对象,返回Array\ | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified extensionAbility is not found | +| 17700004 | The specified userId is invalid | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' + +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId).then((data) => { + console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} +``` + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; +let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +try { + bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags).then((data) => { + console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + }) +} catch (error) { + console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getBundleNameByUid + +getBundleNameByUid(uid: number, callback: AsyncCallback\): void; + +以异步方法根据给定的uid获取bundleName,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| uid | number | 是 | 表示应用程序的UID | +| callback | AsyncCallback\ | 是 | 回调函数,当获取成功时,err为null,data为获取到的BundleName;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------- | +| 17700021 | The uid is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let uid = 20010005; +try { + bundleManager.getBundleNameByUid(uid, (err, data) => { + if (err) { + console.error('getBundleNameByUid failed:' + err.message); + } else { + console.info('getBundleNameByUid successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getBundleNameByUid failed:' + err.message); +} +``` + +### bundleManager.getBundleNameByUid + +getBundleNameByUid(uid: number): Promise\; + +以异步方法根据给定的uid获取bundleName,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---- | ------ | ---- | ------------------ | +| uid | number | 是 | 表示应用程序的UID | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | --------------------------- | +| Promise\ | Promise对象,返回bundleName | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------| +| 17700021 | The uid is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let uid = 20010005; +try { + bundleManager.getBundleNameByUid(uid).then((data) => { + console.info('getBundleNameByUid successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getBundleNameByUid failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleNameByUid failed. Cause: ' + error.message); +} +``` + +### bundleManager.getBundleArchiveInfo + +getBundleArchiveInfo(hapFilePath: string, bundleFlags: [number](#bundleflag), callback: AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>): void; + +以异步方法根据给定的hapFilePath和bundleFlags获取BundleInfo,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ----------------------------------------------------------- | +| hapFilePath | string | 是 | 表示存储HAP的路径,路径应该是当前应用程序数据目录的相对路径 | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定要返回的BundleInfo对象中包含的信息的标志 | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的BundleInfo;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------- | +| 17700022 | The hapFilePath is invalid | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let hapFilePath = "/data/xxx/test.hap"; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { + if (err) { + console.error('getBundleArchiveInfo failed:' + err.message); + } else { + console.info('getBundleArchiveInfo successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getBundleArchiveInfo failed:' + err.message); +} +``` + +### bundleManager.getBundleArchiveInfo + +getBundleArchiveInfo(hapFilePath: string, bundleFlags: [number](#bundleflag)): Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>; + +以异步方法根据给定的hapFilePath和bundleFlags获取BundleInfo,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| hapFilePath | string | 是 | 表示存储HAP的路径,路径应该是当前应用程序数据目录的相对路径 | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定要返回的BundleInfo对象中包含的信息的标志 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | --------------------------- | +| Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Promise对象,返回BundleInfo | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------- | +| 17700022 | The hapFilePath is invalid | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let hapFilePath = "/data/xxx/test.hap"; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; + +try { + bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags).then((data) => { + console.info('getBundleArchiveInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getBundleArchiveInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleArchiveInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.cleanBundleCacheFiles + +cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void; + +以异步方法根据给定的bundleName清理BundleCache,并获取清理结果,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.REMOVE_CACHE_FILES + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示要清理其缓存数据的应用程序的bundleName | +| callback | AsyncCallback\ | 是 | 回调函数,当清理应用缓存目录数据成功,err为null,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found | +| 17700030 | The specified bundleName does not support cleaning cache files | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.cleanBundleCacheFiles(bundleName, err => { + if (err) { + console.error('cleanBundleCacheFiles failed:' + err.message); + } else { + console.info('cleanBundleCacheFiles successfully.'); + } + }); +} catch (err) { + console.error('cleanBundleCacheFiles failed:' + err.message); +} +``` + +### bundleManager.cleanBundleCacheFiles + +cleanBundleCacheFiles(bundleName: string): Promise\; + +以异步方法根据给定的bundleName清理BundleCache,并获取清理结果,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.REMOVE_CACHE_FILES + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------------------------------------- | +| bundleName | string | 是 | 表示要清理其缓存数据的应用程序的bundleName | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回true表示清理应用缓存目录数据成功,返回false表示清理应用缓存目录数据失败 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700001 | The specified bundleName is not found | +| 17700030 | The specified bundle does not support cleaning cache files | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.cleanBundleCacheFiles(bundleName).then(()=> { + console.info('cleanBundleCacheFiles successfully.'); + }).catch(err=> { + console.error('cleanBundleCacheFiles failed:' + err.message); + }); +} catch (err) { + console.error('cleanBundleCacheFiles failed:' + err.message); +} +``` + +### bundleManager.setApplicationEnabled + +setApplicationEnabled(bundleName: string, isEnabled: boolean, callback: AsyncCallback\): void; + +设置指定应用的禁用使能状态,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------- | ---- | ------------------------------------- | +| bundleName | string | 是 | 指定应用的bundleName | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用 | +| callback | AsyncCallback\ | 是 | 回调函数,当设置应用禁用使能状态成功时,err为null,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.setApplicationEnabled(bundleName, false, err => { + if (err) { + console.error('setApplicationEnabled failed:' + err.message); + } else { + console.info('setApplicationEnabled successfully.'); + } + }); +} catch (err) { + console.error('setApplicationEnabled failed:' + err.message); +} +``` + +### bundleManager.setApplicationEnabled + +setApplicationEnabled(bundleName: string, isEnabled: boolean): Promise\; + +设置指定应用的禁用使能状态,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------- | ---- | ------------------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| isEnabled | boolean | 是 | 值为true表示使能,值为false表示禁用 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = "com.ohos.myapplication"; + +try { + bundleManager.setApplicationEnabled(bundleName, false).then(()=> { + console.info('setApplicationEnabled successfully.'); + }).catch(err=> { + console.error('setApplicationEnabled failed:' + err.message); + }); +} catch (err) { + console.error('setApplicationEnabled failed:' + err.message); +} +``` + +### bundleManager.setAbilityEnabled + +setAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), isEnabled: boolean, callback: AsyncCallback\): void; + +设置指定组件的禁用使能状态,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ----------- | ---- | ------------------------------------- | +| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 需要被设置的组件 | +| isEnabled| boolean | 是 | 值为true表示使能,值为false表示禁用 | +| callback | AsyncCallback\ | | 回调函数,当设置组件禁用使能状态成功时,err为null,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified abilityInfo is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +var info; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + info = abilitiesInfo[0]; + + bundleManager.setAbilityEnabled(info, false, err => { + if (err) { + console.error('setAbilityEnabled failed:' + err.message); + } else { + console.info('setAbilityEnabled successfully.'); + } + }); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.setAbilityEnabled + +setAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), isEnabled: boolean): Promise\; + +设置指定组件的禁用使能状态,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.CHANGE_ABILITY_ENABLED_STATE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ----------- | ---- | ------------------------------------- | +| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 需要被设置的组件 | +| isEnabled| boolean | 是 | 值为true表示使能,值为false表示禁用 | + +**返回值:** + +| 类型 | 说明 | +| -------------- | --------------------------------- | +| Promise\ | Promise对象。无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified abilityInfo is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +var info; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + info = abilitiesInfo[0]; + + bundleManager.setAbilityEnabled(info, false).then(()=> { + console.info('setAbilityEnabled successfully.'); + }).catch(err=> { + console.error('setAbilityEnabled failed:' + err.message); + }); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.isApplicationEnabled + +isApplicationEnabled(bundleName: string, callback: AsyncCallback\): void; + +以异步的方法获取指定应用的禁用使能状态,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| callback | AsyncCallback\ | 是 | 回调函数,返回true表示当前应用为使能状态,返回false表示应用为禁用状态 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; + +try { + bundleManager.isApplicationEnabled(bundleName, (err, data) => { + if (err) { + console.error('isApplicationEnabled failed:' + err.message); + } else { + console.info('isApplicationEnabled successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('isApplicationEnabled failed:' + err.message); +} +``` + +### bundleManager.isApplicationEnabled + +isApplicationEnabled(bundleName: string): Promise\; + +以异步的方法获取指定应用的禁用使能状态,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回true表示当前应用为使能状态,返回false表示当前应用为禁用状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; + +try { + bundleManager.isApplicationEnabled(bundleName).then((data) => { + console.info('isApplicationEnabled successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('isApplicationEnabled failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('isApplicationEnabled failed. Cause: ' + error.message); +} +``` + +### bundleManager.isAbilityEnabled + +isAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md), callback: AsyncCallback\): void; + +以异步的方法获取指定组件的禁用使能状态,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---- | ----------- | ---- | --------------------------- | +| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 表示关于检查ability的信息 | +| callback | AsyncCallback\ | 是 | 回调函数,返回true表示当前应用组件为使能状态,返回false表示应用组件为禁用状态 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified abilityName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +var info; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + info = abilitiesInfo[0]; + + bundleManager.isAbilityEnabled(info, (err, data) => { + if (err) { + console.error('isAbilityEnabled failed:' + err.message); + } else { + console.info('isAbilityEnabled successfully:' + JSON.stringify(data)); + } + }); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.isAbilityEnabled + +isAbilityEnabled(info: [AbilityInfo](js-apis-bundleManager-abilityInfo.md)): Promise\; + +以异步的方法获取指定组件的禁用使能状态,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---- | ----------- | ---- | --------------------------- | +| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | 是 | 表示关于检查ability的信息 | + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回true表示当前应用组件为使能状态,返回false表示当前应用组件为禁用状态。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700003 | The specified abilityName is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; +var info; + +try { + bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { + console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + info = abilitiesInfo[0]; + + bundleManager.isAbilityEnabled(info).then((data) => { + console.info('isAbilityEnabled successfully. Data: ' + JSON.stringify(data)); + }).catch(err => { + console.error('isAbilityEnabled failed. Cause: ' + err.message); + }); + }).catch(error => { + console.error('queryAbilityInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('queryAbilityInfo failed. Cause: ' + error.message); +} +``` + +### bundleManager.getLaunchWantForBundle + +getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\): void; + +以异步方法根据给定的bundleName和userId获取用于启动应用程序主要功能,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName | +| userId | number | 是 | 表示用户ID | +| callback | AsyncCallback\ | 是 | 回调函数,当获取成功时,err为null,data为获取到的Want;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let userId = 100; + +try { + bundleManager.getLaunchWantForBundle(bundleName, userId, (err, data) => { + if (err) { + console.error('getLaunchWantForBundle failed:' + err.message); + } else { + console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getLaunchWantForBundle failed:' + err.message); +} +``` + +### bundleManager.getLaunchWantForBundle + +getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; + +以异步方法根据给定的bundleName获取用于启动应用程序主要功能,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName | +| callback | AsyncCallback\ | 是 | 回调函数,当获取成功时,err为null,data为获取到的Want;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; + +try { + bundleManager.getLaunchWantForBundle(bundleName, (err, data) => { + if (err) { + console.error('getLaunchWantForBundle failed:' + err.message); + } else { + console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getLaunchWantForBundle failed:' + err.message); +} +``` + +### bundleManager.getLaunchWantForBundle + +getLaunchWantForBundle(bundleName: string, userId?: number): Promise\; + +以异步方法根据给定的bundleName和userId获取用于启动应用程序主要功能,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | ------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName | +| userId | number | 否 | 表示用户ID| + +**返回值:** + +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | Promise对象,返回Want对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let userId = 100; + +try { + bundleManager.getLaunchWantForBundle(bundleName, userId).then((data) => { + console.info('getLaunchWantForBundle successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getLaunchWantForBundle failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getLaunchWantForBundle failed. Cause: ' + error.message); +} +``` + +### bundleManager.getProfileByAbility + +getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback>): void; + +以异步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,使用callback形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | +| metadataName | string | 是 | 表示应用程序的metadataName | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed | +| 17700003 | The specified abilityName is not existed | +| 17700024 | The specified metadataName is not existed or the profile is not json-format | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let moduleName = 'entry'; +let abilityName = 'MainAbility'; +let metadataName = 'com.example.myapplication.metadata'; + +try { + bundleManager.getProfileByAbility(moduleName, abilityName, metadataName, (err, data) => { + if (err) { + console.error('getProfileByAbility failed:' + err.message); + } else { + console.info('getProfileByAbility successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getProfileByAbility failed:' + err.message); +} +``` + +### bundleManager.getProfileByAbility + +getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise>; + +以异步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,使用Promise形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------ | ---- | -------------------------- | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | +| metadataName | string | 否 | 表示应用程序的metadataName | + +**返回值:** + +| 类型 | 说明 | +| ----------------------- | ------------------------------- | +| Promise> | Promise对象,返回Array\ | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed | +| 17700003 | The specified abilityName is not existed | +| 17700024 | The specified metadataName is not existed or the profile is not json-format | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let moduleName = 'entry'; +let abilityName = 'MainAbility'; +let metadataName = 'com.example.myapplication.metadata'; + +try { + bundleManager.getProfileByAbility(moduleName, abilityName).then((data) => { + console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getProfileByAbility failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getProfileByAbility failed. Cause: ' + error.message); +} + +try { + bundleManager.getProfileByAbility(moduleName, abilityName, metadataName).then((data) => { + console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getProfileByAbility failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getProfileByAbility failed. Cause: ' + error.message); +} +``` + +### bundleManager.getProfileByExtensionAbility + +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback>): void; + +以异步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,使用callback形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| moduleName | string | 是 | 表示应用程序的moduleName | +| extensionAbilityName | string | 是 | 表示应用程序的extensionAbilityName | +| metadataName | string | 是 | 表示应用程序的metadataName | +| callback | AsyncCallback> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed | +| 17700003 | The specified extensionAbilityName is not existed | +| 17700024 | The specified metadataName is not existed or the profile is not json-format | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let moduleName = 'entry'; +let extensionAbilityName = 'com.example.myapplication.extension'; +let metadataName = 'com.example.myapplication.metadata'; + +try { + bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName, (err, data) => { + if (err) { + console.error('getProfileByExtensionAbility failed:' + err.message); + } else { + console.info('getProfileByExtensionAbility successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getProfileByExtensionAbility failed:' + err.message); +} +``` + +### bundleManager.getProfileByExtensionAbility + +getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise>; + +以异步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,使用Promise形式返回结果。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------------- | ------ | ---- | -----------------------------------| +| moduleName | string | 是 | 表示应用程序的moduleName | +| extensionAbilityName | string | 是 | 表示应用程序的extensionAbilityName | +| metadataName | string | 否 | 表示应用程序的metadataName | + +**返回值:** + +| 类型 | 说明 | +| ----------------------- | ----------------------------------- | +| Promise> | Promise对象,返回Array\对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------------------------------ | +| 17700002 | The specified moduleName is not existed | +| 17700003 | The specified extensionAbilityName is not existed | +| 17700024 | The specified metadataName is not existed or the profile is not json-format | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let moduleName = 'entry'; +let extensionAbilityName = 'com.example.myapplication.extension'; +let metadataName = 'com.example.myapplication.metadata'; + +try { + bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName).then((data) => { + console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} + +try { + bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName).then((data) => { + console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} +``` + +### bundleManager.getPermissionDef + +getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void; + +以异步方法根据给定的permissionName获取PermissionDef,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| permissionName | string | 是 | 表示权限名称 | +| callback | AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700006 | The specified permission is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let permission = "ohos.permission.GET_BUNDLE_INFO"; +try { + bundleManager.getPermissionDef(permission, (err, data) => { + if (err) { + console.error('getPermissionDef failed:' + err.message); + } else { + console.info('getPermissionDef successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getPermissionDef failed:' + err.message); +} +``` + +### bundleManager.getPermissionDef + +getPermissionDef(permissionName: string): Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>; + +以异步方法根据给定的permissionName获取PermissionDef,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------- | ------ | ---- | -------------------- | +| permissionName | string | 是 | 表示权限名称 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------------ | +| Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)> | Promise对象,返回Array\对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------| +| 17700006 | The specified permission is not found | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let permissionName = "ohos.permission.GET_BUNDLE_INFO"; +try { + bundleManager.getPermissionDef(permissionName).then((data) => { + console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getPermissionDef failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getPermissionDef failed. Cause: ' + error.message); +} +``` + +### bundleManager.getAbilityLabel + +getAbilityLabel(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void; + +以异步的方法获取指定bundleName、moduleName和abilityName的label,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ---------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | +| callback | AsyncCallback\ | 是 | 回调函数,当获取成功时,err为null,data为获指定组件的Label值;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------| +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not found | +| 17700003 | The specified abilityName is not found | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let abilityName = 'MainAbility'; + +try { + bundleManager.getAbilityLabel(bundleName, moduleName, abilityName, (err, data) => { + if (err) { + console.error('getAbilityLabel failed:' + err.message); + } else { + console.info('getAbilityLabel successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAbilityLabel failed:' + err.message); +} +``` + +### bundleManager.getAbilityLabel + +getAbilityLabel(bundleName: string, moduleName: string, abilityName: string): Promise\; + +以异步的方法获取指定bundleName、moduleName和abilityName的label,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ----------------------------------- | +| Promise\ | Promise对象,返回指定组件的Lablel值 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | --------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not found | +| 17700003 | The specified abilityName is not found | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let abilityName = 'MainAbility'; + +try { + bundleManager.getAbilityLabel(bundleName, moduleName, abilityName).then((data) => { + console.info('getAbilityLabel successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getAbilityLabel failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getAbilityLabel failed. Cause: ' + error.message); +} +``` + +### bundleManager.getAbilityIcon + +getAbilityIcon(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)>): void; + +以异步的方法获取指定bundleName、moduleName和abilityName的icon,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | 是 | 表示应用程序的bundleName | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调函数,当获取成功时,err为null,data为指定组件icon的PixelMap对象;否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not found | +| 17700003 | The specified abilityName is not found | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let abilityName = 'MainAbility'; + +try { + bundleManager.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { + if (err) { + console.error('getAbilityIcon failed:' + err.message); + } else { + console.info('getAbilityIcon successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getAbilityIcon failed:' + err.message); +} +``` + +### bundleManager.getAbilityIcon + +getAbilityIcon(bundleName: string, moduleName: string, abilityName: string): Promise<[image.PixelMap](js-apis-image.md#pixelmap7)>; + +以异步的方法获取指定bundleName、moduleName和abilityName的icon,使用Promise形式返回结果。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| moduleName | string | 是 | 表示应用程序的moduleName | +| abilityName | string | 是 | 表示应用程序的abilityName | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------- | ------------------------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise对象,返回指定组件icon的PixelMap对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700002 | The specified moduleName is not found | +| 17700003 | The specified abilityName is not found | +| 17700026 | The specified bundle is disabled | +| 17700029 | The specified ability is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let abilityName = 'MainAbility'; + +try { + bundleManager.getAbilityIcon(bundleName, moduleName, abilityName).then((data) => { + console.info('getAbilityIcon successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getAbilityIcon failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getAbilityIcon failed. Cause: ' + error.message); +} +``` + +### bundleManager.getApplicationInfoSync + +getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); + +以同步方法根据给定的bundleName、applicationFlags和userId获取ApplicationInfo + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ----------------------------------------------------------| +| bundleName | string | 是 | 表示应用程序的bundleName | +| applicationFlags | [number](#applicationflag) | 是 | 表示用于指定将返回的ApplicationInfo对象中包含的信息 | +| userId | number | 是 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| --------------- | ------------------------- | +| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 返回ApplicationInfo对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; +let userId = 100; + +try { + let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags, userId); + console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); +} catch (err) { + console.error('getApplicationInfoSync failed:' + err.message); +} +``` + +### bundleManager.getApplicationInfoSync + +getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); + +以同步方法根据给定的bundleName和applicationFlags获取ApplicationInfo + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | ----------------------------------------------------------| +| bundleName | string | 是 | 表示应用程序的bundleName | +| applicationFlags | [number](#applicationflag) | 是 | 表示用于指定将返回的ApplicationInfo对象中包含的信息 | + +**返回值:** + +| 类型 | 说明 | +| --------------- | ------------------------- | +| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | 返回ApplicationInfo对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; + +try { + let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags); + console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); +} catch (err) { + console.error('getApplicationInfoSync failed:' + err.message); +} +``` + +### bundleManager.getBundleInfoSync + +getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag), userId: number): [BundleInfo](js-apis-bundleManager-bundleInfo.md); + +以同步方法根据给定的bundleName、bundleFlags和userId获取BundleInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | -------------------------------------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定将返回的BundleInfo对象中包含的信息的标志 | +| userId | number | 是 | 表示用户ID | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | 返回BundleInfo对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700004 | The specified userId is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; +let userId = 100; + +try { + let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags, userId); + console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); +} catch (err) { + console.error('getBundleInfoSync failed:' + err.message); +} +``` + +### bundleManager.getBundleInfoSync + +getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); + +以同步方法根据给定的bundleName和bundleFlags获取BundleInfo。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------ | ---- | -------------------------------------------------------- | +| bundleName | string | 是 | 表示应用程序的bundleName | +| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定将返回的BundleInfo对象中包含的信息的标志 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------- | +| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | 返回BundleInfo对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ------------------------------------- | +| 17700001 | The specified bundleName is not found | +| 17700026 | The specified bundle is disabled | + +**示例:** + +```ts +import bundleManager from '@ohos.bundle.bundleManager' +let bundleName = 'com.example.myapplication'; +let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; +try { + let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags); + console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); +} catch (err) { + console.error('getBundleInfoSync failed:' + err.message); +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md b/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..f89f2c0a3bfd4647fa0771eaa9552fc5f689416e --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -0,0 +1,111 @@ +# Bundle.bundleMonitor模块(JS端sdk接口) + +本模块提供监听应用安装,卸载,更新的能力。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```javascript +import bundleMonitor from '@ohos.bundle.bundleMonitor'; +``` + +## 权限列表 + +| 权限 | 权限等级 | 描述 | +| ------------------------------------ | ----------- | ------------------------------ | +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | 可监听应用的安装,卸载,更新。 | + +权限等级参考[权限等级说明]([zh-cn/application-dev/security/accesstoken-overview.md · OpenHarmony/docs - Gitee.com](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md)) + +## BundleChangeInfo + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +系统接口:为系统接口,三方应用不可调用 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------- | ------ | ---- | ---- | -------------------------- | +| bundleName | string | 是 | 否 | 应用状态发生变化的应用包名 | +| userId | number | 是 | 否 | 应用状态发生变化的用户id | + +## bundleMonitor.on + +on(type: BundleChangedEvent, callback: Callback\): void; + +注册监听应用的安装,卸载,更新。 + +**需要权限:**ohos.permission.LISTEN_BUNDLE_CHANGE + +**系统接口:**此接口为系统接口 + +**系统能力:**SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ---------------------------- | -------- | ---- | ------------------ | +| BundleChangedEvent | string | 是 | 注册监听的事件类型 | +| Callback\ | callback | 是 | 注册监听的回调函数 | + +**相关错误码** + +| 错误码 | 错误信息(此处仅提供错误抛出的关键信息) | +| ------ | ---------------------------------------- | +| 201 | Permission denied. | +| 401 | The parameter check failed. | + +**示例:** + +```js +import bundleMonitor from '@ohos.bundle.bundleMonitor'; + +try { + bundleMonitor.on('add', (bundleChangeInfo) => { + console.info(`bundleName : ${bundleChangeInfo.bundleName} userId : ${bundleChangeInfo.userId}`); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +## bundleMonitor.off + +off(type: BundleChangedEvent, callback?: Callback\): void; + +注销监听应用的安装,卸载,更新。 + +**需要权限:**ohos.permission.LISTEN_BUNDLE_CHANGE + +**系统接口:**此接口为系统接口 + +**系统能力:**SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ---------------------------- | -------- | ---- | ---------------------------------------------------------- | +| BundleChangedEvent | string | 是 | 注销监听的事件类型 | +| Callback\ | callback | 否 | 注销监听的回调函数,当为空时表示注销当前事件的所有callback | + +**相关错误码** + +| 错误码 | 错误信息(此处仅提供错误抛出的关键信息) | +| ------ | ---------------------------------------- | +| 201 | Permission denied. | +| 401 | The parameter check failed. | + +**示例:** + +```js +import bundleMonitor from '@ohos.bundle.bundleMonitor'; + +try { + bundleMonitor.off('add'); +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index bfa69b21bc97b52c7a200e972c61bb831236ddd3..392fb9457b62af0d8e778ea47840b5e51daa9fba 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -194,7 +194,7 @@ getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback { +cameraManager.getSupportedOutputCapability(cameradevice, (err, CameraOutputCapability) => { if (err) { console.error(`Failed to get the cameras. ${err.message}`); return; @@ -250,7 +250,7 @@ isCameraMuted(): boolean **示例:** ```js -let ismuted = await cameraManager.isCameraMuted(); +let ismuted = cameraManager.isCameraMuted(); ``` ### isCameraMuteSupported @@ -270,7 +270,7 @@ isCameraMuteSupported(): boolean **示例:** ```js -let ismutesuppotred = await cameraManager.isCameraMuteSupported(); +let ismutesuppotred = cameraManager.isCameraMuteSupported(); ``` ### muteCamera @@ -1092,7 +1092,7 @@ cameraInput.on('error', camera, (cameraInputError) => { | -------------------------- | ---- | ------------ | | FOCUS_MODE_MANUAL | 0 | 手动对焦。 | | FOCUS_MODE_CONTINUOUS_AUTO | 1 | 连续自动对焦。 | -| FOCUS_MODE_AUTO | 2 | 自动变焦。 | +| FOCUS_MODE_AUTO | 2 | 自动对焦。 | | FOCUS_MODE_LOCKED | 3 | 对焦锁定。 | ## FocusState @@ -2106,8 +2106,8 @@ getExposureBiasRange(): Promise\> **示例:** ```js -captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { - console.log(`Promise returned with exposure mode supported : ${isSupported}`); +captureSession.getExposureBiasRange().then((biasRangeArray) => { + console.log('Promise returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); }) ``` @@ -3758,12 +3758,12 @@ getTimestamp(callback: AsyncCallback): void **示例:** ```js -metadataObject.getTimestamp((err) => { +metadataObject.getTimestamp((err,timestamp) => { if (err) { console.error(`Failed to get timestamp. ${err.message}`); return; } - console.log('Callback returned with timestamp getted.'); + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); }) ``` @@ -3784,8 +3784,8 @@ getTimestamp(): Promise **示例:** ```js -metadataObject.getTimestamp().then(() => { - console.log('Callback returned with timestamp getted.'); +metadataObject.getTimestamp().then((timestamp) => { + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md index 52dca7d46205ca13abd2a6857474d6c14af8b035..f5a241b2dbf92f80d280f13ae4f363cf46a458fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md @@ -30,8 +30,6 @@ isSupported(feature: number): boolean 是否支持某种类型的卡模拟。 -**需要权限**:ohos.permission.NFC_CARD_EMULATION - **系统能力**:SystemCapability.Communication.NFC.Core **参数:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md b/zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md index 8e1b9222850a83f8e9596a6314fbe1d6903ac51d..e6ff7755a77b867fe0b9ffa20c55e26497deb7a2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -33,7 +33,7 @@ import colorSpaceManager from '@ohos.graphics.colorSpaceManager'; **系统能力:** SystemCapability.Graphic.Graphic2D.ColorManager.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ---------------------------- | -------- | ---- | ---- | ----------------------------------------------------- | | redX | number | 是 | 是 | 标准红色在色彩空间的x坐标值。 | | redY | number | 是 | 是 | 标准红色在色彩空间的y坐标值。 | @@ -166,7 +166,7 @@ getColorSpaceName(): ColorSpace ```js try { - let csType = colorSpace.getColorSpaceName(); + colorSpace.getColorSpaceName(); } catch (err) { console.log(`Fail to get colorSpace's name. Cause: ` + JSON.stringify(err)); } @@ -198,7 +198,7 @@ getWhitePoint(): Array\ ```js try { - let wp = colorSpace.getWhitePoint(); + colorSpace.getWhitePoint(); } catch (err) { console.log(`Failed to get white point. Cause: ` + JSON.stringify(err)); } @@ -230,9 +230,8 @@ getGamma(): number ```js try { - let gamma = colorSpace.getGamma(); + colorSpace.getGamma(); } catch (err) { console.log(`Failed to get gamma. Cause: ` + JSON.stringify(err)); } -``` - +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md index bbde4a3e4780e0b2095107ed51474b0ff7a52210..013083338813b551529fadbedf2094c024079d02 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,6 +1,6 @@ # 公共事件模块 -本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。 +本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。本模块将被commonEventManager模块取代,建议优先使用[commonEventManager](js-apis-commonEventManager.md)模块。 > **说明:** > @@ -1237,6 +1237,8 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventData +公共事件数据体。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -1250,6 +1252,8 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventPublishData +公共事件发送的数据体,包含公共事件内容和属性。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -1259,11 +1263,13 @@ subscriber.finishCommonEvent().then(() => { | data | 是 | 否 | string | 表示公共事件的自定义结果数据。 | | subscriberPermissions | 是 | 否 | Array\ | 表示订阅者的权限。 | | isOrdered | 是 | 否 | boolean | 表示是否是有序事件。 | -| isSticky | 是 | 否 | boolean | 表示是否是粘性事件。 | +| isSticky | 是 | 否 | boolean | 表示是否是粘性事件。仅系统应用或系统服务允许发送粘性事件。 | | parameters | 是 | 否 | {[key: string]: any} | 表示公共事件的附加信息。 | ## CommonEventSubscribeInfo +订阅者信息。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent | 名称 | 可读 | 可写 | 类型 | 描述 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md new file mode 100644 index 0000000000000000000000000000000000000000..b656fe8a745dcdfaca409ad2ff30730290de1afa --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEventManager.md @@ -0,0 +1,1420 @@ +# 公共事件模块 + +本模块提供了公共事件的能力,包括公共事件的权限列表,发布公共事件,订阅或取消订阅公共事件,获取或修改公共事件结果代码、结果数据等。本模块将会取代[commonEvent](js-apis-commonEvent.md)模块,建议优先使用本模块。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import CommonEventManager from '@ohos.commonEventManager'; +``` + +## Support + +CommonEventManager模块支持的事件类型。名称指的是系统公共事件宏;值指的是系统公共事件。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +| 名称 | 值 | 订阅者所需权限 | 说明 | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导并加载系统的公共事件的操作。 | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示用户已完成引导,系统已加载,但屏幕仍锁定的公共事件的操作。 | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | 无 | 表示设备正在关闭并将继续最终关闭的公共事件的操作。 | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | 无 | 表示电池充电状态、电平和其他信息发生变化的公共事件的动作。 | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | 无 | 表示电池电量低的普通事件的动作。 | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | 无 | 表示电池退出低电平状态的公共事件的动作。 | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | 无 | 设备连接到外部电源的公共事件的动作。 | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | 无 | 设备与外部电源断开的公共事件的动作。 | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | 无 | 表示设备屏幕关闭且设备处于睡眠状态的普通事件的动作。 | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | 无 | 表示设备屏幕打开且设备处于交互状态的公共事件的操作。 | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | 无 | 表示设备热状态的公共事件的动作。 | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | 无 | 用户解锁设备的公共事件的动作。 | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | 无 | 表示系统时间更改的公共事件的动作。 | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | 无 | 设置系统时间的公共事件的动作。 | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | 无 | 表示系统日期已更改的公共事件的动作。 | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | 无 | 表示系统时区更改的公共事件的动作。 | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | 无 | 表示用户关闭临时系统对话框的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | 无 | 设备上已安装新应用包的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | 无 | 表示已安装的应用程序包的新版本已替换设备上的旧版本的公共事件的操作。 | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | 无 | 表示应用程序包的新版本已取代前一个版本的公共事件的操作。 +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | 无 | 表示已从设备卸载已安装的应用程序,但应用程序数据保留的公共事件的操作。 | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | 无 | 表示已从设备中卸载已安装的捆绑包,但应用程序数据仍保留的公共事件的操作。 | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | 无 | 表示已从设备中完全卸载已安装的应用程序(包括应用程序数据和代码)的公共事件的操作。 | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | 无 | 表示应用包已更改的公共事件的动作(例如,包中的组件已启用或禁用)。 | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | 无 | 表示用户重启应用包并杀死其所有进程的普通事件的动作。 | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | 无 | 用户清除应用包数据的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | 无 | 用户清除应用包缓存数据的公共事件的动作。 | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | 无 | 表示应用包已挂起的公共事件的动作。 | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | 无 | 表示应用包未挂起的公共事件的动作。 | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | 无 | 应用包被挂起的公共事件的动作。 | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | 无 | 表示应用包未挂起的公共事件的动作。 | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | 无 | 表示用户ID已从系统中删除的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | 无 | 表示首次启动已安装应用程序的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | 无 | 表示应用需要系统校验的公共事件的动作。 | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | 无 | 表示应用已被系统校验的公共事件的动作。 | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | 无 | 表示安装在外部存储上的应用程序对系统可用的公共事件的操作。 | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | 无 | 表示安装在外部存储上的应用程序对系统不可用的公共事件的操作。 | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | 无 | 表示设备状态(例如,方向和区域设置)已更改的公共事件的操作。 | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | 无 | 表示设备区域设置已更改的公共事件的操作。 | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | 无 | 设备存储空间不足的公共事件的动作。 | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | 无 | 表示系统处于驾驶模式的公共事件的动作。 | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | 无 | 表示系统处于HOME模式的公共事件的动作。 | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | 无 | 表示系统处于办公模式的公共事件的动作。 | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | 无 | 表示用户已启动的公共事件的动作。 | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | 无 | 表示用户已被带到后台的公共事件的动作。 | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | 无 | 表示用户已被带到前台的公共事件的动作。 | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户切换正在发生的公共事件的动作。 | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 表示要启动用户的公共事件的动作。 | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | 无 | 设备重启后解锁时,当前用户的凭据加密存储已解锁的公共事件的动作。 | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 表示要停止用户的公共事件的动作。 | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | 无 | 表示用户已停止的公共事件的动作。 | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | 无 | Wi-Fi状态公共事件的动作,如启用和禁用。 | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | 表示Wi-Fi接入点已被扫描并证明可用的公共事件的操作。 | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | 表示Wi-Fi信号强度(RSSI)改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | 无 | Wi-Fi连接状态发生改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | 无 | Wi-Fi热点状态的公共事件的动作,如启用或禁用。 | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | 客户端加入当前设备Wi-Fi热点的普通事件的动作。 | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |客户端已断开与当前设备Wi-Fi热点的连接的公共事件的动作。 | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | 表示MPLink(增强Wi-Fi功能)状态已更改的公共事件的动作。 | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Wi-Fi P2P连接状态改变的公共事件的动作。 | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P状态公共事件的动作,如启用和禁用。 | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P对等体状态变化。 | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P发现状态变化。 | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P当前设备状态变化。 | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Wi-Fi P2P群组信息已更改。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙免提通信连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示连接到蓝牙免提的设备处于活动状态的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示使用蓝牙A2DP连接的设备处于活动状态的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP播放状态改变的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP的AVRCP连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP音频编解码状态更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | 表示发现远程蓝牙设备的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的蓝牙类别已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | 表示已与远程蓝牙设备建立低级别(ACL)连接的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | 表示低电平(ACL)连接已从远程蓝牙设备断开的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的友好名称首次被检索或自上次检索以来被更改的公共事件的操作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | 远程蓝牙设备连接状态更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示远程蓝牙设备的电池电量首次被检索或自上次检索以来被更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | 无 | 远程蓝牙设备SDP状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | 远程蓝牙设备UUID连接状态公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | 表示远程蓝牙设备配对请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | 无 | 取消蓝牙配对的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | 无 | 表示远程蓝牙设备连接请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | 无 | 表示远程蓝牙设备连接请求响应的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | 无 | 表示取消与远程蓝牙设备的连接的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | 无 | 表示蓝牙免提连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | 无 | 表示蓝牙免提音频状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | 无 | 表示蓝牙免提音频网关状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | 无 | 表示蓝牙免提呼叫状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙适配器状态已更改的公共事件的操作,例如蓝牙已打开或关闭。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | 无 | 表示用户允许扫描蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | 表示用户打开蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | 表示用户关闭蓝牙请求的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | 设备蓝牙扫描模式更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | 设备上已启动蓝牙扫描的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | 设备上蓝牙扫描完成的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | 表示设备蓝牙适配器名称已更改的公共事件的操作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP宿连接状态已更改的公共事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 蓝牙A2DP宿播放状态改变的普通事件的动作。 | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | 表示蓝牙A2DP宿的音频状态已更改的公共事件的动作。 | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | 无 | 表示设备NFC适配器状态已更改的公共事件的操作。 | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | 检测到NFC RF字段处于使能状态的公共事件的动作。 | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | 检测到NFC RF字段处于关闭状态的公共事件的动作。 | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | 无 | 表示系统停止为电池充电的公共事件的动作。 | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | 无 | 表示系统开始为电池充电的公共事件的动作。 | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | 无 | 表示系统空闲模式已更改的公共事件的动作。 | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | 无 | 表示系统节能模式更改的公共事件的动作。 | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户已添加到系统中的公共事件的动作。 | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | 表示用户已从系统中删除的公共事件的动作。 | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示已添加能力的公共事件的动作。 | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示已删除能力的公共事件的动作。 | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | 表示能力已更新的公共事件的动作。 | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | 无 | 表示系统定位模式已更改的公共事件的动作。 | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | 无 | 表示表示车辆的车载信息娱乐(IVI)系统正在休眠的常见事件的动作。 | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | 无 | 表示IVI已休眠,并通知应用程序停止播放。 | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | 无 | 表示第三方应用暂停当前工作的公共事件的动作。 | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | 无 | 表示第三方应用保存其最后一个模式的公共事件的动作。 | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | 无 | 表示车辆电源系统电压异常的公共事件的动作。 | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | 无 | 表示IVI温度过高。 | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | 无 | 表示IVI温度极高。 | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | 无 | 表示车载系统具有极端温度的常见事件的动作。 | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | 无 | 表示车辆电源系统电压恢复正常的公共事件的动作。 | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | 无 | 表示车载系统温度恢复正常的公共事件的动作。 | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | 无 | 表示电池服务处于活动状态的公共事件的动作。 | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | 无 | 表示USB设备状态发生变化的公共事件。 | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | 无 | 表示用户设备的USB端口状态发生改变的公共事件。 | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | 无 | 当用户设备作为USB主机时,USB设备已挂载的公共事件的动作。 | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | 无 | 当用户设备作为USB主机时,USB设备被卸载的公共事件的动作。 | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | 无 | 表示已连接USB附件的公共事件的动作。 | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | 无 | 表示USB附件被卸载的公共事件的动作。 | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为插卡情况下无法挂载时发送此公共事件。 | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为移除时发送此公共事件。 | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为卸载时发送此公共事件。 | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载时发送此公共事件。 | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | 外部存储设备状态变更为挂载状态下移除时发送此公共事件。 | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | 用户已表示希望删除外部存储介质时发送此公共事件。 | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | 表示帐户可见更改的公共事件的动作。 | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | 删除帐户的公共事件的动作。 | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | 表示foundation已准备好的公共事件的动作。 | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | 无 | 表示设备飞行模式已更改的公共事件的动作。 | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | 表示分屏的公共事件的动作。 | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | 表示通知通道更新的动作。 | +| COMMON_EVENT_SPN_INFO_CHANGED 9+ | usual.event.SPN_INFO_CHANGED | 无 | 表示spn显示信息已更新的公共事件的动作。 | +| COMMON_EVENT_QUICK_FIX_APPLY_RESULT 9+ | usual.event.QUICK_FIX_APPLY_RESULT | 无 | 表示快速修复应用的动作。 | + + +## CommonEventManager.publish + +publish(event: string, callback: AsyncCallback\): void + +发布公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发送的公共事件。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +以下错误码详细介绍请参考[@ohos.commonEventManager(事件)](../errorcodes/errorcode-CommonEventService.md) + +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//发布公共事件回调 +function PublishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +//发布公共事件 +try { + CommonEventManager.publish("event", PublishCallBack); +} catch(err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + +## CommonEventManager.publish + +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +发布公共事件指定发布信息(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发布的公共事件。 | +| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| callback | syncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +//公共事件相关信息 +var options = { + code: 0, //公共事件的初始代码 + data: "initial data",//公共事件的初始数据 + isOrdered: true //有序公共事件 +} + +//发布公共事件回调 +function PublishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +//发布公共事件 +try { + CommonEventManager.publish("event", options, PublishCallBack); +} catch (err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void + +向指定用户发布公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | 是 | 表示要发送的公共事件。 | +| userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//发布公共事件回调 +function PublishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +//指定发送的用户 +var userId = 100; + +//发布公共事件 +try { + CommonEventManager.publishAsUser("event", userId, PublishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void + +向指定用户发布公共事件并指定发布信息(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**系统API**:此接口为系统接口,三方应用不支持调用。 + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | 是 | 表示要发布的公共事件。 | +| userId | number | 是 | 表示指定向该用户ID发送此公共事件。 | +| options | [CommonEventPublishData](#commoneventpublishdata) | 是 | 表示发布公共事件的属性。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +//公共事件相关信息 +var options = { + code: 0, //公共事件的初始代码 + data: "initial data",//公共事件的初始数据 +} + +//发布公共事件回调 +function PublishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +//指定发送的用户 +var userId = 100; + +//发布公共事件 +try { + CommonEventManager.publishAsUser("event", userId, options, PublishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +创建订阅者(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | 是 | 表示创建订阅者的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +创建订阅者(Promise形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | 是 | 表示订阅信息。 | + +**返回值:** +| 类型 | 说明 | +| --------------------------------------------------------- | ---------------- | +| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | 返回订阅者对象。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; +}).catch((err) => { + console.error("createSubscriber failed " + JSON.stringify(err)); +}); +} catch(err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} + +``` + + + +## CommonEventManager.subscribe + +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +订阅公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | 是 | 表示接收公共事件数据的回调函数。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +//订阅者信息 +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 + +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; + +//订阅公共事件回调 +function SubscribeCallBack(err, data) { + if (err.code) { + console.error("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe "); + } +} + +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + //订阅公共事件 + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch (err) { + console.error("createSubscriber failed " + JSON.stringify(err)); + } + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.unsubscribe + +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +取消订阅公共事件(callback形式)。 + +**系统能力:** SystemCapability.Notification.CommonEvent + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | 是 | 表示订阅者对象。 | +| callback | AsyncCallback\ | 否 | 表示取消订阅的回调方法。 | + +**错误码:** +|错误码ID |错误信息 | +|-----------|--------------------| +|1500001 |Want action is null | +|1500002 |sandbox application can not send common event| +|1500003 |common event send frequency too high| +|1500004 |not System services or System app| +|1500005 |subscriber can not found| +|1500006 |usreId is invalid| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**示例:** + +```ts +var subscriber; //用于保存创建成功的订阅者对象,后续使用其完成订阅及退订的动作 +//订阅者信息 +var subscribeInfo = { + events: ["event"] +}; +//订阅公共事件回调 +function SubscribeCallBack(err, data) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe"); + } +} +//创建订阅者回调 +function CreateSubscriberCallBack(err, commonEventSubscriber) { + if (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + //订阅公共事件 + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch(err) { + console.info("subscribe failed " + JSON.stringify(err)); + } + } +} +//取消订阅公共事件回调 +function UnsubscribeCallBack(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe"); + } +} +//创建订阅者 +try { + CommonEventManager.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +} catch (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); +} + +//取消订阅公共事件 +try { + CommonEventManager.unsubscribe(subscriber, UnsubscribeCallBack); +} catch (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); +} +``` + +## CommonEventSubscriber + +### getCode + +getCode(callback: AsyncCallback\): void + +获取公共事件的结果代码(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | 是 | 公共事件的结果代码。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取有序公共事件的结果代码回调 +function getCodeCallback(err, Code) { + if (err.code) { + console.error("getCode failed " + JSON.stringify(err)); + } else { + console.info("getCode " + JSON.stringify(Code)); + } +} +subscriber.getCode(getCodeCallback); +``` + +### getCode + +getCode(): Promise\ + +获取公共事件的结果代码(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 公共事件的结果代码。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getCode().then((Code) => { + console.info("getCode " + JSON.stringify(Code)); +}).catch((err) => { + console.error("getCode failed " + JSON.stringify(err)); +}); +``` + +### setCode + +setCode(code: number, callback: AsyncCallback\): void + +设置公共事件的结果代码(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果代码回调 +function setCodeCallback(err) { + if (err.code) { + console.error("setCode failed " + JSON.stringify(err)); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCallback); +``` + +### setCode + +setCode(code: number): Promise\ + +设置公共事件的结果代码(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | ------------------ | +| code | number | 是 | 公共事件的结果代码。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error("setCode failed " + JSON.stringify(err)); +}); +``` + +### getData + +getData(callback: AsyncCallback\): void + +获取公共事件的结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 公共事件的结果数据。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取有序公共事件的结果数据回调 +function getDataCallback(err, Data) { + if (err.code) { + console.error("getData failed " + JSON.stringify(err)); + } else { + console.info("getData " + JSON.stringify(Data)); + } +} +subscriber.getData(getDataCallback); +``` + +### getData + +getData(): Promise\ + +获取公共事件的结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ------------------ | +| Promise\ | 公共事件的结果数据。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getData().then((Data) => { + console.info("getData " + JSON.stringify(Data)); +}).catch((err) => { + console.error("getData failed " + JSON.stringify(err)); +}); +``` + +### setData + +setData(data: string, callback: AsyncCallback\): void + +设置公共事件的结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| data | string | 是 | 公共事件的结果数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果数据回调 +function setDataCallback(err) { + if (err.code) { + console.error("setData failed " + JSON.stringify(err)); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCallback); +``` + +### setData + +setData(data: string): Promise\ + +设置公共事件的结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------------- | +| data | string | 是 | 公共事件的结果数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error("setData failed " + JSON.stringify(err)); +}); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void + +设置公共事件的结果代码和结果数据(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| data | string | 是 | 公共事件的结果数据。 | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//设置有序公共事件的结果代码和结果数据回调 +function setCodeDataCallback(err) { + if (err.code) { + console.error("setCodeAndData failed " + JSON.stringify(err)); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string): Promise\ + +设置公共事件的结果代码和结果数据(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------------- | +| code | number | 是 | 公共事件的结果代码。 | +| data | string | 是 | 公共事件的结果数据。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.info("setCodeAndData failed " + JSON.stringify(err)); +}); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(callback: AsyncCallback\): void + +查询当前公共事件的是否为有序公共事件(callback形式)。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为有序事件的回调 +function isOrderedCallback(err, isOrdered) { + if (err.code) { + console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCallback); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(): Promise\ + +查询当前公共事件的是否为有序公共事件(Promise形式)。 + +返回true代表是有序公共事件,false代表不是有序公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为有序公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error("isOrdered failed " + JSON.stringify(err)); +}); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +检查当前公共事件是否为一个粘性事件(callback形式)。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前公共事件是否为粘性事件的回调 +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +检查当前公共事件是否为一个粘性事件(Promise形式)。 + +返回true代表是粘性公共事件,false代表不是粘性公共事件。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | -------------------------------- | +| Promise\ | 当前公共事件的是否为粘性公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + +### abortCommonEvent + +abortCommonEvent(callback: AsyncCallback\): void + +取消当前的公共事件,仅对有序公共事件有效,取消后,公共事件不再向下一个订阅者传递(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 取消当前的公共事件。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//取消当前有序公共事件的回调 +function abortCallback(err) { + if (err.code) { + console.error("abortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCallback); +``` + +### abortCommonEvent + +abortCommonEvent(): Promise\ + +取消当前的公共事件,仅对有序公共事件有效,取消后,公共事件不再向下一个订阅者传递(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error("abortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(callback: AsyncCallback\): void + +清除当前公共事件的取消状态,仅对有序公共事件有效(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | 是 | 表示被指定的回调方法。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//清除当前公共事件取消状态的回调 +function clearAbortCallback(err) { + if (err.code) { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCallback); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(): Promise\ + +清除当前公共事件的取消状态,仅对有序公共事件有效(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(callback: AsyncCallback\): void + +获取当前有序公共事件是否取消的状态(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | 是 | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取当前有序公共事件是否取消的回调 +function getAbortCallback(err, AbortCommonEvent) { + if (err.code) { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("AbortCommonEvent " + AbortCommonEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCallback); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(): Promise\ + +获取当前有序公共事件是否取消的状态(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ----------------- | ---------------------------------- | +| Promise\ | 表示当前有序公共事件是否取消的状态。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { + console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +}).catch((err) => { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getSubscribeInfo + +getSubscribeInfo(callback: AsyncCallback\): void + +获取订阅者的订阅信息(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 是 | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//获取订阅者信息回调 +function getSubscribeInfoCallback(err, SubscribeInfo) { + if (err.code) { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); + } else { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + } +} +subscriber.getSubscribeInfo(getSubscribeInfoCallback); +``` + +### getSubscribeInfo + +getSubscribeInfo(): Promise\ + +获取订阅者的订阅信息(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | 表示订阅者的订阅信息。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.getSubscribeInfo().then((SubscribeInfo) => { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +}).catch((err) => { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); +}); +``` + +### finishCommonEvent9+ + +finishCommonEvent(callback: AsyncCallback\): void + +结束当前有序公共事件(callback形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | 是 | 表示有序公共事件结束后的回调函数。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +//结束当前有序公共事件的回调 +function finishCommonEventCallback(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} +} +subscriber.finishCommonEvent(finishCommonEventCallback); +``` + +### finishCommonEvent9+ + +finishCommonEvent(): Promise\ + +结束当前有序公共事件(Promise形式)。 + +**系统能力**:SystemCapability.Notification.CommonEvent + +**返回值:** + +| 类型 | 说明 | +| ---------------- | -------------------- | +| Promise\ | 返回一个Promise的结果。 | + +**示例:** + +```ts +var subscriber; //创建成功的订阅者对象 + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +}); +``` + +## CommonEventData + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | +| event | 是 | 否 | string | 表示当前接收的公共事件名称。 | +| bundleName | 是 | 否 | string | 表示包名称。 | +| code | 是 | 否 | number | 表示公共事件的结果代码,用于传递int类型的数据。 | +| data | 是 | 否 | string | 表示公共事件的自定义结果数据,用于传递string类型的数据。 | +| parameters | 是 | 否 | {[key: string]: any} | 表示公共事件的附加信息。 | + + +## CommonEventPublishData + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| --------------------- | ---- | ---- | -------------------- | ---------------------------- | +| bundleName | 是 | 否 | string | 表示包名称。 | +| code | 是 | 否 | number | 表示公共事件的结果代码。 | +| data | 是 | 否 | string | 表示公共事件的自定义结果数据。 | +| subscriberPermissions | 是 | 否 | Array\ | 表示订阅者的权限。 | +| isOrdered | 是 | 否 | boolean | 表示是否是有序事件。 | +| isSticky | 是 | 否 | boolean | 表示是否是粘性事件。仅系统应用或系统服务允许发送粘性事件。 | +| parameters | 是 | 否 | {[key: string]: any} | 表示公共事件的附加信息。 | + +## CommonEventSubscribeInfo + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent + +| 名称 | 可读 | 可写 | 类型 | 描述 | +| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | +| events | 是 | 否 | Array\ | 表示要发送的公共事件。 | +| publisherPermission | 是 | 否 | string | 表示发布者的权限。 | +| publisherDeviceId | 是 | 否 | string | 表示设备ID,该值必须是同一ohos网络上的现有设备ID。 | +| userId | 是 | 否 | number | 表示用户ID。此参数是可选的,默认值当前用户的ID。如果指定了此参数,则该值必须是系统中现有的用户ID。 | +| priority | 是 | 否 | number | 表示订阅者的优先级。值的范围是-100到1000。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 0e05d31270de26c1943eabbe95bdee8cfb036b64..239575f71050935bd1815d69cfc30b3d18e4f6e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -2,7 +2,7 @@ continuationManager模块提供了流转/协同入口管理服务能力,包括连接/取消流转管理服务,注册/解注册设备连接变化监听,拉起设备选择模块,更新连接状态。 -本模块接口用于拉起系统中的设备选择模块,由于该模块功能暂不完备,因此**流转能力整体暂不支持用于应用开发**。 +本模块接口用于拉起系统中的设备选择模块,由于该模块功能暂不完备,因此流转能力整体暂不支持用于应用开发。 > **说明:** > @@ -20,7 +20,7 @@ register(callback: AsyncCallback\): void; 注册流转管理服务,并获取对应的注册token,无过滤条件,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 +> 从API version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -32,13 +32,13 @@ register(callback: AsyncCallback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | **示例:** @@ -60,7 +60,7 @@ register(options: ContinuationExtraParams, callback: AsyncCallback\): vo 连接流转管理服务,并获取对应的注册token,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 +> 从API version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -73,13 +73,13 @@ register(options: ContinuationExtraParams, callback: AsyncCallback\): vo **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | | 29360216 | Invalid continuation mode. | **示例:** @@ -105,7 +105,7 @@ register(options?: ContinuationExtraParams): Promise\; 连接流转管理服务,并获取对应的注册token,使用Promise方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 +> 从API version 9开始不再维护,建议使用[registerContinuation](#continuationmanagerregistercontinuation9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -123,13 +123,13 @@ register(options?: ContinuationExtraParams): Promise\; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | | 29360216 | Invalid continuation mode. | **示例:** @@ -167,12 +167,12 @@ registerContinuation(callback: AsyncCallback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **示例:** @@ -212,12 +212,12 @@ registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\< **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **示例:** @@ -265,12 +265,12 @@ registerContinuation(options?: ContinuationExtraParams): Promise\; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **示例:** @@ -301,7 +301,7 @@ on(type: "deviceConnect", callback: Callback\): void; 异步方法,监听设备连接状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceselected9)替代。 +> 从API version 9开始不再维护,建议使用[on](#continuationmanagerondeviceselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -314,14 +314,14 @@ on(type: "deviceConnect", callback: Callback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null | 7 | -| 29360208 | The token has not registered. | -| 29360209 | Callback has been registered. | +| 29360208 | The token is not registered. | +| 29360209 | The callback has been registered. | | 29360214 | The type of callback is not supported. | **示例:** @@ -340,7 +340,7 @@ on(type: "deviceDisconnect", callback: Callback\): void; 异步方法,监听设备断开状态,使用Callback形式返回断开的设备信息。 -> 从API Version 9开始不再维护,建议使用[on](#continuationmanagerondeviceunselected9)替代。 +> 从API version 9开始不再维护,建议使用[on](#continuationmanagerondeviceunselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -353,14 +353,14 @@ on(type: "deviceDisconnect", callback: Callback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360209 | Callback has been registered. | +| 29360208 | The token is not registered. | +| 29360209 | The callback has been registered. | | 29360214 | The type of callback is not supported. | **示例:** @@ -377,7 +377,7 @@ off(type: "deviceConnect", callback?: Callback\): void; 异步方法,取消监听设备连接状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceselected9)替代。 +> 从API version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -390,14 +390,14 @@ off(type: "deviceConnect", callback?: Callback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | | 29360214 | The type of callback is not supported. | **示例:** @@ -416,7 +416,7 @@ off(type: "deviceDisconnect", callback?: Callback\): void; 异步方法,取消监听设备断开状态,使用Callback形式返回连接的设备信息。 -> 从API Version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceunselected9)替代。 +> 从API version 9开始不再维护,建议使用[off](#continuationmanageroffdeviceunselected9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -429,14 +429,14 @@ off(type: "deviceDisconnect", callback?: Callback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | | 29360214 | The type of callback is not supported. | **示例:** @@ -467,13 +467,13 @@ on(type: "deviceSelected", token: number, callback: Callback\): void; 拉起设备选择模块,可显示组网内可选择设备列表信息,无过滤条件,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 +> 从API version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -639,15 +639,15 @@ startDeviceManager(token: number, callback: AsyncCallback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | | 29360216 | Invalid continuation mode. | **示例:** @@ -669,7 +669,7 @@ startDeviceManager(token: number, options: ContinuationExtraParams, callback: As 拉起设备选择模块,可显示组网内可选择设备列表信息,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 +> 从API version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -683,15 +683,15 @@ startDeviceManager(token: number, options: ContinuationExtraParams, callback: As **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | | 29360216 | Invalid continuation mode. | **示例:** @@ -716,7 +716,7 @@ startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ 从API Version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 +> 从API version 9开始不再维护,建议使用[startContinuationDeviceManager](#continuationmanagerstartcontinuationdevicemanager9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -735,15 +735,15 @@ startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\): v **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -826,13 +826,13 @@ startContinuationDeviceManager(token: number, options: ContinuationExtraParams, **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -879,13 +879,13 @@ startContinuationDeviceManager(token: number, options?: ContinuationExtraParams) **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -913,7 +913,7 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, 通知设备选择模块,更新当前的连接状态,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[updateContinuationState](#continuationmanagerupdatecontinuationstate9)替代。 +> 从API version 9开始不再维护,建议使用[updateContinuationState](#continuationmanagerupdatecontinuationstate9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -928,16 +928,16 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | -| 29360215 | Invalid connect state. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | +| 29360215 | Invalid connection state. | **示例:** @@ -959,7 +959,7 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState) 通知设备选择模块,更新当前的连接状态,使用Promise方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[updateContinuationState](#continuationmanagerupdatecontinuationstate9)替代。 +> 从API version 9开始不再维护,建议使用[updateContinuationState](#continuationmanagerupdatecontinuationstate9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -979,16 +979,16 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState) **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | -| 29360215 | Invalid connect state. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | +| 29360215 | Invalid connection state. | **示例:** @@ -1025,13 +1025,13 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -1077,13 +1077,13 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -1110,7 +1110,7 @@ unregister(token: number, callback: AsyncCallback\): void; 解注册流转管理服务,传入注册时获取的token进行解注册,使用AsyncCallback方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[unregisterContinuation](#continuationmanagerunregistercontinuation9)替代。 +> 从API version 9开始不再维护,建议使用[unregisterContinuation](#continuationmanagerunregistercontinuation9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -1123,13 +1123,13 @@ unregister(token: number, callback: AsyncCallback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | +| 29360208 | The token is not registered. | **示例:** @@ -1150,7 +1150,7 @@ unregister(token: number): Promise\; 解注册流转管理服务,传入注册时获取的token进行解注册,使用Promise方式作为异步方法。 -> 从API Version 9开始不再维护,建议使用[unregisterContinuation](#continuationmanagerunregistercontinuation9)替代。 +> 从API version 9开始不再维护,建议使用[unregisterContinuation](#continuationmanagerunregistercontinuation9)替代。 **系统能力**:SystemCapability.Ability.DistributedAbilityManager @@ -1168,13 +1168,13 @@ unregister(token: number): Promise\; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | +| 29360208 | The token is not registered. | **示例:** @@ -1208,13 +1208,13 @@ unregisterContinuation(token: number, callback: AsyncCallback\): void; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** @@ -1257,13 +1257,13 @@ unregisterContinuation(token: number): Promise\; **错误码:** -以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errorcode-DistributedSchedule.md)。 | 错误码ID | 错误信息 | | ------- | -------------------------------------------- | | 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md index ec0549cfff1c91b4395dbe479d6e4e418554e430..b9a2765552732a482ba053d47ec0751bb8a3c767 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md @@ -14,8 +14,53 @@ import convertxml from '@ohos.convertxml'; ## ConvertXML +### convertToJSObject9+ -### convert +convertToJSObject(xml: string, options?: ConvertOptions) : Object + +转换xml文本为JavaScript对象。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------------- | ---- | --------------- | +| xml | string | 是 | 传入的xml文本。 | +| options | [ConvertOptions](#convertoptions) | 否 | 转换选项。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| Object | 处理后返回的JavaScript对象。 | + +**示例:** + +```js +let xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let conv = new convertxml.convertToJSObject(); +let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} +let result = JSON.stringify(conv.convert(xml, options)); +console.log(result); +// 输出(宽泛型) +// {"_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"}]}]}]} +``` + +### convert(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[convertToJSObject9+](#converttojsobject9)替代。 convert(xml: string, options?: ConvertOptions) : Object @@ -23,7 +68,6 @@ convert(xml: string, options?: ConvertOptions) : Object **系统能力:** SystemCapability.Utils.Lang - **参数:** | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md index 32d7490e912276ab087ebb35ad7bae37d5b195de..638e6c9983501b14f9347eacde5f7401a75a84cc 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-cooperate.md +++ b/zh-cn/application-dev/reference/apis/js-apis-cooperate.md @@ -1,7 +1,6 @@ -# 键鼠穿越管理 +# 键鼠穿越 -键鼠穿越功能,即两台或多台设备组网协同后可以共用一套键盘鼠标。 -键鼠穿越管理模块,提供实现键盘、鼠标等外接输入设备的跨设备协同操作。在设备组网的情况下,提供多设备间共享键鼠的开关,设备穿越状态更新以及键鼠穿越光标自适应显示。 +键鼠穿越功能模块,提供两台或多台设备组网协同后键鼠共享能力,实现键鼠输入设备的跨设备协同操作。 > **说明** > @@ -15,18 +14,18 @@ import inputDeviceCooperate from '@ohos.multimodalInput.inputDeviceCooperate' ## inputDeviceCooperate.enable -enable(enable: boolean, callback: AsyncCallback\): void +enable(enable: boolean, callback: AsyncCallback<void>): void -键鼠穿越开关开启或关闭,使用callback异步回调。 +开启、关闭键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate **参数**: -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------------------------------- | -| enable | boolean | 是 | 键鼠穿越开关开启或关闭状态。true: 键鼠穿越开关开启; false: 键鼠穿越开关关闭。 -| callback | AsyncCallback\ | 是 | 异步回调函数。当键鼠穿越开关开启或关闭成功,err为undefined,否则为错误对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | --------------------------- | +| enable | boolean | 是 | 键鼠穿越使能状态。 | +| callback | AsyncCallback<void> | 是 |回调函数,异步返回键鼠穿越开启、关闭结果。 | @@ -34,23 +33,24 @@ enable(enable: boolean, callback: AsyncCallback\): void ```js try { - inputDeviceCooperate.enable(true, (err) => { - if (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.enable(true, (error) => { + if (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Turn on the key mouse crossing switch success.`); + console.log(`Keyboard mouse crossing enable success.`); }); -} catch (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## inputDeviceCooperate.enable -enable(enable: boolean): Promise\ +enable(enable: boolean): Promise<void> + +开启、关闭键鼠穿越,使用Promise异步方式返回结果。 -键鼠穿越开关开启或关闭,使用Promise方式作为异步方法。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -58,7 +58,7 @@ enable(enable: boolean): Promise\ | 参数名 | 类型 | 必填 | 说明 | | --------- | ------- | ---- | ------------------------------------------------------------------- | -| enable | boolean | 是 | 键鼠穿越开关开启或关闭状态。true: 键鼠穿越开关开启; false: 键鼠穿越开关关闭。 | +| enable | boolean | 是 | 键鼠穿越使能状态。 | @@ -66,7 +66,7 @@ enable(enable: boolean): Promise\ | 参数 | 说明 | | ------------------- | ------------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise<void> | Promise对象,异步返回键鼠穿越开启、关闭结果。 | @@ -74,13 +74,13 @@ enable(enable: boolean): Promise\ ```js try { - inputDeviceCooperate.enable(false).then((err) => { - console.log(`Turn on the key mouse crossing switch success`); - }, (err) => { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.enable(true).then(() => { + console.log(`Keyboard mouse crossing enable success.`); + }, (error) => { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Turn on the key mouse crossing switch failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Keyboard mouse crossing enable failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -88,7 +88,7 @@ try { start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback\): void -启动键鼠穿越,使用callback异步回调。 +启动键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -98,30 +98,32 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCal | -------- | ---------------------------- | ---- | ---------------------------- | | sinkDeviceDescriptor | string | 是 | 键鼠穿越目标设备描述符。 | | srcInputDeviceId | number | 是 | 键鼠穿越待穿越外设标识符。 | -| callback | AsyncCallback\ | 是 | 异步回调函数。当键鼠穿越启动成功,err为undefined,否则为错误对象。| +| callback | AsyncCallback\ | 是 | 回调函数,异步返回键鼠穿越启动、停止状态。| **错误码:** -以下错误码的详细介绍请参见[ohos.multimodalinput错误码](../errorcodes/errorcodes-multimodalinput.md)。 +以下错误码的详细介绍请参见[ohos.multimodalinput错误码](../errorcodes/errorcode-multimodalinput.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | Incorrect descriptor for the target device. | -| 4400002 | Failed to operate the input device. | +| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | +| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | **示例**: ```js +let sinkDeviceDescriptor = "descriptor"; +let srcInputDeviceId = 0; try { - inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (err) => { - if (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => { + if (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Start key mouse crossing success.`); + console.log(`Start Keyboard mouse crossing success.`); }); -} catch (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -129,7 +131,7 @@ try { start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ -启动键鼠穿越,使用Promise方式作为异步方法。 +启动键鼠穿越,使用Promise异步方式返回结果。 **系统能力**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -146,28 +148,30 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ | 参数名 | 说明 | | ---------------------- | ------------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise\ | Promise对象,异步返回键鼠穿越启动、关闭结果。 | **错误码:** -以下错误码的详细介绍请参见[ohos.multimodalinput错误码](../errorcodes/errorcodes-multimodalinput.md)。 +以下错误码的详细介绍请参见[ohos.multimodalinput错误码](../errorcodes/errorcode-multimodalinput.md)。 | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 4400001 | Incorrect descriptor for the target device. | -| 4400002 | Failed to operate the input device. | +| 4400001 | 当调用键鼠穿越接口传入无效的设备描述符参数时,系统会产生此错误码。 | +| 4400002 | 当调用键鼠穿越接口时穿越状态异常,系统会产生此错误码。 | **示例**: ```js +let sinkDeviceDescriptor = "descriptor"; +let srcInputDeviceId = 0; try { - inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then((err) => { - console.log(`Start key mouse crossing success.`); - }, (err) => { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => { + console.log(`Start Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Start key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Start Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -175,7 +179,7 @@ try { stop(callback: AsyncCallback\): void -停止键鼠穿越,使用callback异步回调。 +停止键鼠穿越,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -183,7 +187,7 @@ stop(callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback\ | 是 | 异步回调函数,返回查询结果。 | +| callback | AsyncCallback\ | 是 | 回调函数,异步返回停止键鼠穿越结果。 | @@ -191,15 +195,15 @@ stop(callback: AsyncCallback\): void ```js try { - inputDeviceCooperate.stop((err) => { - if (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.stop((error) => { + if (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Stop key mouse crossing success.`); + console.log(`Stop Keyboard mouse crossing success.`); }); -} catch (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -207,7 +211,7 @@ try { stop(): Promise\ -停止键鼠穿越,使用Promise异步回调。 +停止键鼠穿越,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -215,19 +219,19 @@ stop(): Promise\ | 参数名 | 说明 | | -------- | ---------------------------- | -| Promise\ | Promise实例,用于异步获取结果。 | +| Promise\ | Promise对象,异步返回停止键鼠穿越结果。 | **示例**: ```js try { - inputDeviceCooperate.stop().then((err) => { - console.log(`Stop key mouse crossing success.`); - }, (err) => { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.stop().then(() => { + console.log(`Stop Keyboard mouse crossing success.`); + }, (error) => { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Stop key mouse crossing failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Stop Keyboard mouse crossing failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -235,7 +239,7 @@ try { getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): void -获取键鼠穿越开关的状态,使用callback异步回调。 +获取键鼠穿越开关的状态,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -244,21 +248,22 @@ getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): | 参数名 | 类型 | 必填 | 说明 | | -------- | --------- | ---- | ---------------------------- | | deviceDescriptor | string | 是 | 键鼠穿越目标设备描述符。 | -| callback | AsyncCallback<{ state: boolean }> | 是 | 异步回调函数,接收键鼠穿越开关状态。 | +| callback | AsyncCallback<{ state: boolean }> | 是 | 回调函数,异步返回键鼠穿越开关状态。 | **示例**: ```js +let deviceDescriptor = "descriptor"; try { - inputDeviceCooperate.getState(deviceDescriptor, (err, data) => { - if (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.getState(deviceDescriptor, (error, data) => { + if (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } - console.log(`Get the status success. data=${JSON.stringify(data)}`); + console.log(`Get the status success, data: ${JSON.stringify(data)}`); }); -} catch (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -266,7 +271,7 @@ try { getState(deviceDescriptor: string): Promise<{ state: boolean }> -获取键鼠穿越开关的状态,使用Promise异步回调。 +获取键鼠穿越开关的状态,使用Promise异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDeviceCooperate @@ -282,21 +287,22 @@ getState(deviceDescriptor: string): Promise<{ state: boolean }> | 参数 | 说明 | | ------------------- | ------------------------------- | -| Promise<{ state: boolean }>| Promise实例,用于异步获取结果。 | +| Promise<{ state: boolean }>| Promise对象,异步返回键鼠穿越开关状态。 | **示例**: ```js +let deviceDescriptor = "descriptor"; try { inputDeviceCooperate.getState(deviceDescriptor).then((data) => { - console.log(`Get the status success. data=${JSON.stringify(data)}`); - }, (err) => { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + console.log(`Get the status success, data: ${JSON.stringify(data)}`); + }, (error) => { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); }); -} catch (err) { - console.log(`Get the status failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Get the status failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -312,8 +318,8 @@ on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, even | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| type | string | 是 | 注册类型,'cooperation'。 | -| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | 是 | 异步回调函数,接收键鼠穿越事件消息。 | +| type | string | 是 | 注册类型,取值”cooperation“。 | +| callback | AsyncCallback<{ deviceDescriptor: string, eventMsg: [EventMsg](#eventmsg) }> | 是 | 回调函数,异步返回键鼠穿越事件。 | @@ -322,14 +328,10 @@ on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, even ```js try { inputDeviceCooperate.on('cooperation', (data) => { - if (data) { - console.log(`error: ${JSON.stringify(data)}`); - } else { - console.log(`cooperation: ${JSON.stringify(data)}`); - } + console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); }); -} catch (err) { - console.log(`Registered failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); +} catch (error) { + console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -345,24 +347,37 @@ off(type: 'cooperation', callback?: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | ---------------------------- | -| type | string | 是 | 注册类型,'cooperation'。 | -| callback | AsyncCallback | 否 | 异步回调函数,用于返回结果。 | +| type | string | 是 | 注册类型,取值“cooperation”。 | +| callback | AsyncCallback | 否 | 需要取消注册的回调函数,若无此参数,则取消当前应用注册的所有回调函数。 | **示例**: ```js +// 取消注册单个回调函数 +function callback(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +} try { - inputDeviceCooperate.off('cooperation', (err) => { - if (err) { - console.log(`error: ${JSON.stringify(err)}`); - } else { - console.log(`Unregistered succeed`); - } - }); -} catch (err) { - console.log(`Unregistered failed. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); + inputDeviceCooperate.on('cooperation', callback); + inputDeviceCooperate.off("cooperation", callback); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} +``` +```js +// 取消注册所有回调函数 +function callback(event) { + console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); + return false; +} +try { + inputDeviceCooperate.on('cooperation', callback); + inputDeviceCooperate.off("cooperation"); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md index 79c474b00aa1c9e77c25a6ea710df58815c0069a..bc6162d6d793754139104299d0f5f3623dea6972 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -632,7 +632,7 @@ import distributedObject from '@ohos.data.distributedDataObject'; import featureAbility from '@ohos.ability.featureAbility'; // 获取context let context = featureAbility.getContext(); -let g_object = distributedObject.create({name:"Amy", age:18, isVis:false}); +let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.save("local").then((result) => { console.log("save callback"); @@ -654,7 +654,7 @@ class MainAbility extends Ability{ context = this.context } } -let g_object = distributedObject.create({name:"Amy", age:18, isVis:false}); +let g_object = distributedObject.create(context,{name:"Amy", age:18, isVis:false}); g_object.setSessionId("123456"); g_object.save("local").then((result) => { console.log("save callback"); diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md index 4db44625182dc2518deb9ab3a9309cca99a6bfb2..a19a37efd9f244207dbdc75fa7abd60d684a450d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @@ -22,8 +22,8 @@ import data_preferences from '@ohos.data.preferences'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ---------------- | -------- | ---- | ---- | --------------------------------------- | -| MAX_KEY_LENGTH | string | 是 | 否 | Key的最大长度限制,需小于80个字节。 | -| MAX_VALUE_LENGTH | string | 是 | 否 | Value的最大长度限制,需小于8192个字节。 | +| MAX_KEY_LENGTH | number | 是 | 否 | Key的最大长度限制,需小于80个字节。 | +| MAX_VALUE_LENGTH | number | 是 | 否 | Value的最大长度限制,需小于8192个字节。 | ## data_preferences.getPreferences @@ -475,7 +475,7 @@ get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): ```js try { - data_preferences.get('startup', 'default', function (err, val) { + preferences.get('startup', 'default', function (err, val) { if (err) { console.info("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); return; diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index 39465f70542b10799dcac16ccfe566fe8d989cc1..86cd8f8ebd6accc6ee41a7d01c2e40dc40e1c73e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -4,8 +4,8 @@ 该模块提供以下关系型数据库相关的常用功能: -- [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 -- [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。 +- [RdbPredicatesV9](#rdbpredicatesv99): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 +- [RdbStoreV9](#rdbstorev99):提供管理关系数据库(RDB)方法的接口。 > **说明:** > @@ -17,22 +17,304 @@ import data_rdb from '@ohos.data.rdb'; ``` -## data_rdb.getRdbStore +## data_rdb.getRdbStoreV99+ + +getRdbStoreV9(context: Context, config: StoreConfigV9, version: number, callback: AsyncCallback<RdbStoreV9>): void + +获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | +| callback | AsyncCallback<[RdbStoreV9](#rdbstorev9)> | 是 | 指定callback回调函数,返回RdbStoreV9对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | +| 14800011 | Database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { + if (err) { + console.info("Get RdbStoreV9 failed, err: " + err) + return + } + console.log("Get RdbStoreV9 successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { + if (err) { + console.info("Get RdbStoreV9 failed, err: " + err) + return + } + console.log("Get RdbStoreV9 successfully.") +}) +``` + +## data_rdb.getRdbStoreV99+ + +getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> + +获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStoreV9](#rdbstorev99)> | Promise对象。返回RdbStoreV9对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | +| 14800011 | Database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); +promise.then(async (rdbStoreV9) => { + console.log("Get RdbStoreV9 successfully.") +}).catch((err) => { + console.log("Get RdbStoreV9 failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStoreV9 +const STORE_CONFIGV9 = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); +promise.then(async (rdbStoreV9) => { + console.log("Get RdbStoreV9 successfully.") +}).catch((err) => { + console.log("Get RdbStoreV9 failed, err: " + err) +}) +``` + +## data_rdb.deleteRdbStoreV99+ + +deleteRdbStoreV9(context: Context, name: string, callback: AsyncCallback<void>): void + +删除数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStoreV9 +data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStorev9 failed, err: " + err) + return + } + console.log("Delete RdbStorev9 successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStoreV9 +data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStoreV9 failed, err: " + err) + return + } + console.log("Delete RdbStoreV9 successfully.") +}) +``` + +## data_rdb.deleteRdbStoreV99+ + +deleteRdbStoreV9(context: Context, name: string): Promise<void> + +使用指定的数据库文件配置删除数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | Invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStoreV9 +let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStoreV9 successfully.") +}).catch((err) => { + console.info("Delete RdbStoreV9 failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStoreV9 +let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStoreV9 successfully.") +}).catch((err) => { + console.info("Delete RdbStoreV9 failed, err: " + err) +}) +``` + +## data_rdb.getRdbStore(deprecated) getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。 | -| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回一个RdbStore。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | **示例:** @@ -41,7 +323,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db"} @@ -59,7 +341,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -76,27 +358,32 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Get RdbStore successfully.") }) ``` -## data_rdb.getRdbStore + +## data_rdb.getRdbStore(deprecated) getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| version | number | 是 | 数据库版本。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<[RdbStore](#rdbstore)> | 指定Promise回调函数。返回一个RdbStore。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise对象。返回RdbStore对象。 | **示例:** @@ -105,7 +392,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用getRdbStore const STORE_CONFIG = { name: "RdbTest.db" } @@ -122,7 +409,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -139,21 +426,25 @@ promise.then(async (rdbStore) => { }) ``` -## data_rdb.deleteRdbStore +## data_rdb.deleteRdbStore(deprecated) deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void 删除数据库,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| name | string | 是 | 数据库名称。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | **示例:** @@ -162,7 +453,7 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用deleteRdbStore data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -179,7 +470,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -196,26 +487,30 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { }) ``` -## data_rdb.deleteRdbStore +## data_rdb.deleteRdbStore(deprecated) deleteRdbStore(context: Context, name: string): Promise<void> 使用指定的数据库文件配置删除数据库,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。| -| name | string | 是 | 数据库名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -224,11 +519,11 @@ FA模型示例: ```js // 获取context import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // 获取context后调用deleteRdbStore let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Delete RdbStore successfully.") }).catch((err) => { console.info("Delete RdbStore failed, err: " + err) @@ -240,7 +535,7 @@ Stage模型示例: ```ts // 获取context import Ability from '@ohos.application.Ability' -var context +let context class MainAbility extends Ability{ onWindowStageCreate(windowStage){ context = this.context @@ -256,162 +551,162 @@ promise.then(()=>{ }) ``` -## RdbPredicates +## RdbPredicatesV99+ 表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 -### constructor +### constructor9+ constructor(name: string) 构造函数。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| name | string | 是 | 数据库表名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| name | string | 是 | 数据库表名。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") ``` -### inDevices8+ +### inDevices9+ -inDevices(devices: Array<string>): RdbPredicates +inDevices(devices: Array<string>): RdbPredicatesV9 同步分布式数据库时连接到组网内指定的远程设备。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inDevices(['12345678abcde']) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.inDevices(['12345678abcde']) ``` -### inAllDevices8+ +### inAllDevices9+ -inAllDevices(): RdbPredicates +inAllDevices(): RdbPredicatesV9 同步分布式数据库时连接到组网内所有的远程设备。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesv9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.inAllDevices() +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.inAllDevices() ``` -### equalTo +### equalTo9+ -equalTo(field: string, value: ValueType): RdbPredicates +equalTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") ``` -### notEqualTo +### notEqualTo9+ -notEqualTo(field: string, value: ValueType): RdbPredicates +notEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notEqualTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notEqualTo("NAME", "lisi") ``` -### beginWrap +### beginWrap9+ -beginWrap(): RdbPredicates +beginWrap(): RdbPredicatesV9 向谓词添加左括号。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有左括号的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -419,25 +714,25 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### endWrap +### endWrap9+ -endWrap(): RdbPredicates +endWrap(): RdbPredicatesV9 向谓词添加右括号。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有右括号的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "lisi") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) .or() @@ -445,676 +740,677 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### or +### or9+ -or(): RdbPredicates +or(): RdbPredicatesV9 将或条件添加到谓词中。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有或条件的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` -### and +### and9+ -and(): RdbPredicates +and(): RdbPredicatesV9 向谓词添加和条件。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有和条件的Rdb谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` -### contains +### contains9+ -contains(field: string, value: string): RdbPredicates +contains(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且value包含指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.contains("NAME", "os") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.contains("NAME", "os") ``` -### beginsWith +### beginsWith9+ -beginsWith(field: string, value: string): RdbPredicates +beginsWith(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.beginsWith("NAME", "os") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.beginsWith("NAME", "os") ``` -### endsWith +### endsWith9+ -endsWith(field: string, value: string): RdbPredicates +endsWith(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.endsWith("NAME", "se") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.endsWith("NAME", "se") ``` -### isNull +### isNull9+ -isNull(field: string): RdbPredicates +isNull(field: string): RdbPredicatesV9 配置谓词以匹配值为null的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例**: + ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNull("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.isNull("NAME") ``` -### isNotNull +### isNotNull9+ -isNotNull(field: string): RdbPredicates +isNotNull(field: string): RdbPredicatesV9 配置谓词以匹配值不为null的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.isNotNull("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.isNotNull("NAME") ``` -### like +### like9+ -like(field: string, value: string): RdbPredicates +like(field: string, value: string): RdbPredicatesV9 配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.like("NAME", "%os%") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.like("NAME", "%os%") ``` -### glob +### glob9+ -glob(field: string, value: string): RdbPredicates +glob(field: string, value: string): RdbPredicatesV9 -配置RdbPredicates匹配数据字段为string的指定字段。 +配置RdbPredicatesV9匹配数据字段为string的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.glob("NAME", "?h*g") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.glob("NAME", "?h*g") ``` -### between +### between9+ -between(field: string, low: ValueType, high: ValueType): RdbPredicates +between(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.between("AGE", 10, 50) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.between("AGE", 10, 50) ``` -### notBetween +### notBetween9+ -notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 -配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 +配置RdbPredicatesV9以匹配数据字段为ValueType且value超出给定范围的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notBetween("AGE", 10, 50) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notBetween("AGE", 10, 50) ``` -### greaterThan +### greaterThan9+ -greaterThan(field: string, value: ValueType): RdbPredicates +greaterThan(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThan("AGE", 18) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.greaterThan("AGE", 18) ``` -### lessThan +### lessThan9+ -lessThan(field: string, value: ValueType): RdbPredicates +lessThan(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为valueType且value小于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThan("AGE", 20) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.lessThan("AGE", 20) ``` -### greaterThanOrEqualTo +### greaterThanOrEqualTo9+ -greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.greaterThanOrEqualTo("AGE", 18) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.greaterThanOrEqualTo("AGE", 18) ``` -### lessThanOrEqualTo +### lessThanOrEqualTo9+ -lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.lessThanOrEqualTo("AGE", 20) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.lessThanOrEqualTo("AGE", 20) ``` -### orderByAsc +### orderByAsc9+ -orderByAsc(field: string): RdbPredicates +orderByAsc(field: string): RdbPredicatesV9 配置谓词以匹配其值按升序排序的列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByAsc("NAME") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.orderByAsc("NAME") ``` -### orderByDesc +### orderByDesc9+ -orderByDesc(field: string): RdbPredicates +orderByDesc(field: string): RdbPredicatesV9 配置谓词以匹配其值按降序排序的列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.orderByDesc("AGE") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.orderByDesc("AGE") ``` -### distinct +### distinct9+ -distinct(): RdbPredicates +distinct(): RdbPredicatesV9 配置谓词以过滤重复记录并仅保留其中一个。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于过滤重复记录的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").distinct() +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").distinct() ``` -### limitAs +### limitAs9+ -limitAs(value: number): RdbPredicates +limitAs(value: number): RdbPredicatesV9 设置最大数据记录数的谓词。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| value | number | 是 | 最大数据记录数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| value | number | 是 | 最大数据记录数。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于设置最大数据记录数的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").limitAs(3) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").limitAs(3) ``` -### offsetAs +### offsetAs9+ -offsetAs(rowOffset: number): RdbPredicates +offsetAs(rowOffset: number): RdbPredicatesV9 -配置RdbPredicates以指定返回结果的起始位置。 +配置RdbPredicatesV9以指定返回结果的起始位置。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定返回结果起始位置的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").offsetAs(3) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose").offsetAs(3) ``` -### groupBy +### groupBy9+ -groupBy(fields: Array<string>): RdbPredicates +groupBy(fields: Array<string>): RdbPredicatesV9 -配置RdbPredicates按指定列分组查询结果。 +配置RdbPredicatesV9按指定列分组查询结果。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| fields | Array<string> | 是 | 指定分组依赖的列名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | 是 | 指定分组依赖的列名。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回分组查询列的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | ---------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回分组查询列的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.groupBy(["AGE", "NAME"]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.groupBy(["AGE", "NAME"]) ``` -### indexedBy +### indexedBy9+ -indexedBy(field: string): RdbPredicates +indexedBy(field: string): RdbPredicatesV9 -配置RdbPredicates以指定索引列。 +配置RdbPredicatesV9以指定索引列。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 索引列的名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------- | +| field | string | 是 | 索引列的名称。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定索引列的RdbPredicatesV9。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.indexedBy("SALARY_INDEX") +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.indexedBy("SALARY_INDEX") ``` -### in +### in9+ -in(field: string, value: Array<ValueType>): RdbPredicates +in(field: string, value: Array<ValueType>): RdbPredicatesV9 -配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 +配置RdbPredicatesV9以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.in("AGE", [18, 20]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.in("AGE", [18, 20]) ``` -### notIn +### notIn9+ -notIn(field: string, value: Array<ValueType>): RdbPredicates +notIn(field: string, value: Array<ValueType>): RdbPredicatesV9 -将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 +将RdbPredicatesV9配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.notIn("NAME", ["Lisa", "Rose"]) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.notIn("NAME", ["Lisa", "Rose"]) ``` -## RdbStore +## RdbStoreV99+ 提供管理关系数据库(RDB)方法的接口。 在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 -### insert +### insert9+ insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void 向目标表中插入一行数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | **示例:** @@ -1125,7 +1421,7 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { +rdbStoreV9.insert("EMPLOYEE", valueBucket, function (status, rowId) { if (status) { console.log("Insert is failed"); return; @@ -1134,26 +1430,26 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { }) ``` -### insert +### insert9+ insert(table: string, values: ValuesBucket):Promise<number> 向目标表中插入一行数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。如果操作成功,返回行ID;否则返回-1。 | +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | **示例:** @@ -1164,7 +1460,7 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let promise = rdbStore.insert("EMPLOYEE", valueBucket) +let promise = rdbStoreV9.insert("EMPLOYEE", valueBucket) promise.then((rowId) => { console.log("Insert is successful, rowId = " + rowId); }).catch((status) => { @@ -1178,15 +1474,15 @@ batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCal 向目标表中插入一组数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | **示例:** @@ -1210,8 +1506,8 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("batchInsert is failed, status = " + status); return; @@ -1226,20 +1522,20 @@ batchInsert(table: string, values: Array<ValuesBucket>):Promise<number& 向目标表中插入一组数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | **示例:** @@ -1263,8 +1559,8 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); }).catch((status) => { @@ -1272,21 +1568,21 @@ promise.then((insertNum) => { }) ``` -### update +### update9+ -update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void +update(values: ValuesBucket, predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void -根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 +根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | **示例:** @@ -1297,9 +1593,9 @@ const valueBucket = { "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +rdbStoreV9.update(valueBucket, predicatesV9, function (err, ret) { if (err) { console.info("Updated failed, err: " + err) return @@ -1308,25 +1604,25 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { }) ``` -### update +### update9+ -update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> +update(values: ValuesBucket, predicates: RdbPredicatesV9):Promise<number> -根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 +根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicatesV9 | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | | Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | **示例:** @@ -1338,9 +1634,9 @@ const valueBucket = { "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update(valueBucket, predicates) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +let promise = rdbStoreV9.update(valueBucket, predicatesV9) promise.then(async (ret) => { console.log("Updated row count: " + ret) }).catch((err) => { @@ -1349,22 +1645,21 @@ promise.then(async (ret) => { ``` ### update9+ + update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void 根据DataSharePredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| 是 | DataSharePredicates的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | **示例:** @@ -1378,7 +1673,7 @@ const valueBucket = { } let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { +rdbStoreV9.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { if (err) { console.info("Updated failed, err: " + err) return @@ -1393,22 +1688,20 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data 根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | | Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | **示例:** @@ -1423,7 +1716,7 @@ const valueBucket = { } let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +let promise = rdbStoreV9.update("EMPLOYEE", valueBucket, predicates) promise.then(async (ret) => { console.log("Updated row count: " + ret) }).catch((err) => { @@ -1431,27 +1724,27 @@ promise.then(async (ret) => { }) ``` -### delete +### delete9+ -delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void +delete(predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void -根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 +根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -rdbStore.delete(predicates, function (err, rows) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +rdbStoreV9.delete(predicatesV9, function (err, rows) { if (err) { console.info("Delete failed, err: " + err) return @@ -1460,32 +1753,32 @@ rdbStore.delete(predicates, function (err, rows) { }) ``` -### delete +### delete9+ -delete(predicates: RdbPredicates):Promise<number> +delete(predicates: RdbPredicatesV9):Promise<number> -根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 +根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。返回受影响的行数。 | +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete(predicates) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Lisa") +let promise = rdbStoreV9.delete(predicatesV9) promise.then((rows) => { console.log("Delete rows: " + rows) }).catch((err) => { @@ -1499,17 +1792,15 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb 根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** @@ -1517,7 +1808,7 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callb import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { +rdbStoreV9.delete("EMPLOYEE", predicates, function (err, rows) { if (err) { console.info("Delete failed, err: " + err) return @@ -1532,22 +1823,20 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promi 根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<number> | 指定Promise回调函数。返回受影响的行数。 | +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** @@ -1555,7 +1844,7 @@ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promi import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) +let promise = rdbStoreV9.delete("EMPLOYEE", predicates) promise.then((rows) => { console.log("Delete rows: " + rows) }).catch((err) => { @@ -1563,151 +1852,2196 @@ promise.then((rows) => { }) ``` -### query +### query9+ -query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(predicates: RdbPredicatesV9, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void 根据指定条件查询数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose") -rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose") +rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { if (err) { console.info("Query failed, err: " + err) return } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) }) ``` -### query +### query9+ -query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> +query(predicates: RdbPredicatesV9, columns?: Array<string>):Promise<ResultSetV9> 根据指定条件查询数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | **返回值**: -| 类型 | 说明 | -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | **示例:** ```js - let predicates = new data_rdb.RdbPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose") - let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) - }).catch((err) => { - console.info("Query failed, err: " + err) - }) +let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") +predicatesV9.equalTo("NAME", "Rose") +let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) ``` ### query9+ -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void 根据指定条件查询数据库中的数据,使用callback异步回调。 -**系统接口:** 此接口为系统接口。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### query9+ + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSetV9> + +根据指定条件查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string> , callback: AsyncCallback<ResultSetV9>): void + +根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.greaterThan("id", 0) +rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSetV9){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSetV9.columnNames) + console.info("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> + +根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md#resultset)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.greaterThan("id", 0) +let promise = rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSetV9) => { + console.info("ResultSet column names: " + resultSetV9.columnNames) + console.info("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql9+ + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSetV9>):void + +根据指定SQL语句查询数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSetV9) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}) +``` + +### querySql9+ + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSetV9> + +根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | + +**示例:** + +```js +let promise = rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +promise.then((resultSetV9) => { + console.log("ResultSet column names: " + resultSetV9.columnNames) + console.log("ResultSet column count: " + resultSetV9.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### executeSql9+ + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +rdbStoreV9.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("ExecuteSql failed, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql9+ + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promise = rdbStoreV9.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("ExecuteSql failed, err: " + err) +}) +``` + +### beginTransaction9+ + +beginTransaction():void + +在开始执行SQL语句之前,开始事务。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + rdbStoreV9.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() +}) +``` + +### commit9+ + +commit():void + +提交已执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + rdbStoreV9.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() +}) +``` + +### rollBack9+ + +rollBack():void + +回滚已经执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { + try { + rdbStoreV9.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStoreV9.insert("test", valueBucket) + rdbStoreV9.commit() + } catch (e) { + rdbStoreV9.rollBack() + } +}) +``` + +### backup9+ + +backup(destName:string, callback: AsyncCallback<void>):void + +以指定名称备份数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup9+ + +backup(destName:string): Promise<void> + +以指定名称备份数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseBackup = rdbStoreV9.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore9+ + +restore(srcName:string, callback: AsyncCallback<void>):void + +从指定的数据库备份文件恢复数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore9+ + +restore(srcName:string): Promise<void> + +从指定的数据库备份文件恢复数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseRestore = rdbStoreV9.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables9+ + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +设置分布式列表,使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | 是 | 要设置的分布式列表表名 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStoreV9.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.info('SetDistributedTables failed, err: ' + err) + return + } + console.info('SetDistributedTables successfully.') +}) +``` + +### setDistributedTables9+ + + setDistributedTables(tables: Array<string>): Promise<void> + +设置分布式列表,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | 是 | 要设置的分布式列表表名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promise = rdbStoreV9.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("SetDistributedTables successfully.") +}).catch((err) => { + console.info("SetDistributedTables failed, err: " + err) +}) +``` + +### obtainDistributedTableName9+ + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | 是 | 远程设备 。 | +| table | string | 是 | 本地表名。 | +| callback | AsyncCallback<string> | 是 | 指定的callback回调函数。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('ObtainDistributedTableName failed, err: ' + err) + return + } + console.info('ObtainDistributedTableName successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName9+ + + obtainDistributedTableName(device: string, table: string): Promise<string> + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| device | string | 是 | 远程设备。 | +| table | string | 是 | 本地表名。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +let promise = rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('ObtainDistributedTableName successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('ObtainDistributedTableName failed, err: ' + err) +}) +``` + +### sync9+ + +sync(mode: SyncMode, predicates: RdbPredicatesV9, callback: AsyncCallback<Array<[string, number]>>): void + +在设备之间同步数据, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | +| callback | AsyncCallback<Array<[string, number]>> | 是 | 指定的callback回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.inDevices(['12345678abcde']) +rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9, function (err, result) { + if (err) { + console.log('Sync failed, err: ' + err) + return + } + console.log('Sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } +}) +``` + +### sync9+ + + sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise<Array<[string, number]>> + +在设备之间同步数据,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | + +**返回值**: + +| 类型 | 说明 | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') +predicatesV9.inDevices(['12345678abcde']) +let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9) +promise.then((resultSetV9) =>{ + console.log('Sync done.') + for (let i = 0; i < resultSetV9.length; i++) { + console.log('device=' + resultSetV9[i][0] + ' status=' + resultSetV9[i][1]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange')9+ + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指分布式数据库中数据更改事件的观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Register observer failed') +} +``` + +### off('dataChange')9+ + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +从数据库中删除指定类型的指定观察者, 使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指已注册的数据更改观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStoreV9.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Unregister observer failed') +} +``` + +## StoreConfigV99+ + +管理关系数据库配置。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 参数名 | 类型 | 必填 | 说明 | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | 是 | 数据库文件名。 | +| securityLevel | SecurityLevel | 是 | 设置数据库安全级别 | +| encrypt | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | + +## SecurityLevel9+ + +数据库的安全级别枚举。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | +| S2 | 2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | +| S3 | 3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | +| S4 | 4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | + +## ValueType + +用于表示允许的数据字段类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 类型 | 说明 | +| ------- | -------------------- | +| number | 表示值类型为数字。 | +| string | 表示值类型为字符。 | +| boolean | 表示值类型为布尔值。 | + + +## ValuesBucket + +用于存储键值对的类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 键类型 | 值类型 | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +指数据库同步模式。 + +**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | 表示数据从本地设备推送到远程设备。 | +| SYNC_MODE_PULL | 1 | 表示数据从远程设备拉至本地设备。 | + +## SubscribeType8+ + +描述订阅类型。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | + +## RdbPredicates(deprecated) + +表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[RdbPredicatesV9](#rdbpredicatesv99)替代。 + + +### constructor(deprecated) + +constructor(name: string) + +构造函数。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[constructor](#constructor9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 数据库表名。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices(deprecated) + +inDevices(devices: Array<string>): RdbPredicates + +同步分布式数据库时连接到组网内指定的远程设备。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inDevices](#indevices9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices(deprecated) + +inAllDevices(): RdbPredicates + +同步分布式数据库时连接到组网内所有的远程设备。 + +> **说明:** +> +> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inAllDevices](#inalldevices9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo(deprecated) + +equalTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[equalTo](#equalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo(deprecated) + +notEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[notEqualTo](#notequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap(deprecated) + +beginWrap(): RdbPredicates + +向谓词添加左括号。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[beginWrap](#beginwrap9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap(deprecated) + +endWrap(): RdbPredicates + +向谓词添加右括号。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[endWrap](#endwrap9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or(deprecated) + +or(): RdbPredicates + +将或条件添加到谓词中。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[or](#or9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and(deprecated) + +and(): RdbPredicates + +向谓词添加和条件。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[and](#and9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains(deprecated) + +contains(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且value包含指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[contains](#contains9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith(deprecated) + +beginsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[beginsWith](#beginswith9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith(deprecated) + +endsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[endsWith](#endswith9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull(deprecated) + +isNull(field: string): RdbPredicates + +配置谓词以匹配值为null的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNull](#isnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例**: +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull(deprecated) + +isNotNull(field: string): RdbPredicates + +配置谓词以匹配值不为null的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNotNull](#isnotnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like(deprecated) + +like(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[like](#like9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob(deprecated) + +glob(field: string, value: string): RdbPredicates + +配置RdbPredicates匹配数据字段为string的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[glob](#glob9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between(deprecated) + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[between](#between9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween(deprecated) + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notBetween](#notbetween9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan(deprecated) + +greaterThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThan](#greaterthan9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan(deprecated) + +lessThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为valueType且value小于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThan](#lessthan9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo(deprecated) + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThanOrEqualTo](#greaterthanorequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo(deprecated) + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThanOrEqualTo](#lessthanorequalto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc(deprecated) + +orderByAsc(field: string): RdbPredicates + +配置谓词以匹配其值按升序排序的列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByAsc](#orderbyasc9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc(deprecated) + +orderByDesc(field: string): RdbPredicates + +配置谓词以匹配其值按降序排序的列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByDesc](#orderbydesc9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct(deprecated) + +distinct(): RdbPredicates + +配置谓词以过滤重复记录并仅保留其中一个。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[distinct](#distinct9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs(deprecated) + +limitAs(value: number): RdbPredicates + +设置最大数据记录数的谓词。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[limitAs](#limitas9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | number | 是 | 最大数据记录数。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs(deprecated) + +offsetAs(rowOffset: number): RdbPredicates + +配置RdbPredicates以指定返回结果的起始位置。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[offsetAs](#offsetas9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy(deprecated) + +groupBy(fields: Array<string>): RdbPredicates + +配置RdbPredicates按指定列分组查询结果。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[groupBy](#groupby9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| fields | Array<string> | 是 | 指定分组依赖的列名。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回分组查询列的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy(deprecated) + +indexedBy(field: string): RdbPredicates + +配置RdbPredicates以指定索引列。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[indexedBy](#indexedby9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 索引列的名称。 | + +**返回值**: + + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in(deprecated) + +in(field: string, value: Array<ValueType>): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[in](#in9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn(deprecated) + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notIn](#notin9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore(deprecated) + +提供管理关系数据库(RDB)方法的接口。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[RdbStoreV9](#rdbstorev99)替代。 + +在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 + +### insert(deprecated) + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +向目标表中插入一行数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Insert is failed"); + return; + } + console.log("Insert is successful, rowId = " + rowId); +}) +``` + +### insert(deprecated) + +insert(table: string, values: ValuesBucket):Promise<number> + +向目标表中插入一行数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Insert is successful, rowId = " + rowId); +}).catch((status) => { + console.log("Insert is failed"); +}) +``` + +### batchInsert(deprecated) + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +向目标表中插入一组数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("batchInsert is failed, status = " + status); + return; + } + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert(deprecated) + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +向目标表中插入一组数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("batchInsert is failed, status = " + status); +}) +``` + +### update(deprecated) + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, function (err, ret) { + if (err) { + console.info("Updated failed, err: " + err) + return + } + console.log("Updated row count: " + ret) +}) +``` + +### update(deprecated) + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | + +**返回值**: + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates) +promise.then(async (ret) => { + console.log("Updated row count: " + ret) +}).catch((err) => { + console.info("Updated failed, err: " + err) +}) +``` + +### delete(deprecated) + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | **示例:** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.delete(predicates, function (err, rows) { if (err) { - console.info("Query failed, err: " + err) + console.info("Delete failed, err: " + err) return } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) + console.log("Delete rows: " + rows) }) ``` -### query9+ +### delete(deprecated) -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> +delete(predicates: RdbPredicates):Promise<number> -根据指定条件查询数据库中的数据,使用Promise异步回调。 +根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 -**系统接口:** 此接口为系统接口。 +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-2)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | **返回值**: | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<number> | Promise对象。返回受影响的行数。 | **示例:** ```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) }).catch((err) => { - console.info("Query failed, err: " + err) + console.info("Delete failed, err: " + err) }) ``` -### remoteQuery9+ +### query(deprecated) -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 +根据指定条件查询数据库中的数据,使用callback异步回调。 + +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-1)替代。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1715,33 +4049,34 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | | columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | **示例:** ```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { if (err) { - console.info("Failed to remoteQuery, err: " + err) + console.info("Query failed, err: " + err) return } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) }) ``` -### remoteQuery9+ +### query(deprecated) + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> +根据指定条件查询数据库中的数据,使用Promise异步回调。 -根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 +> **说明:** +> +> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-2)替代。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1749,38 +4084,40 @@ remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: A | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | | columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | **返回值**: -| 类型 | 说明 | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | **示例:** -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` + ```js + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) + }).catch((err) => { + console.info("Query failed, err: " + err) + }) + ``` -### querySql8+ +### querySql(deprecated) querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void 根据指定SQL语句查询数据库中的数据,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1803,13 +4140,17 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", }) ``` -### querySql8+ +### querySql(deprecated) querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1822,7 +4163,7 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | 类型 | 说明 | | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | 指定Promise回调函数。如果操作成功,则返回ResultSet对象。 | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSet对象。 | **示例:** @@ -1836,13 +4177,17 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql(deprecated) executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void 执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-1)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1865,13 +4210,17 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql(deprecated) executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> 执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-2)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -1884,7 +4233,7 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> | 类型 | 说明 | | -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -1898,19 +4247,23 @@ promise.then(() => { }) ``` -### beginTransaction8+ +### beginTransaction(deprecated) beginTransaction():void 在开始执行SQL语句之前,开始事务。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[beginTransaction](#begintransaction9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1925,19 +4278,23 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### commit8+ +### commit(deprecated) commit():void 提交已执行的SQL语句。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[commit](#commit9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1952,19 +4309,23 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### rollBack8+ +### rollBack(deprecated) rollBack():void 回滚已经执行的SQL语句。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[rollBack](#rollback9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,131 +4345,19 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -以指定名称备份数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| destName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Backup failed, err: ' + err) - return - } - console.info('Backup success.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -以指定名称备份数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| destName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | - -**示例:** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backup success.') -}).catch((err)=>{ - console.info('Backup failed, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -从指定的数据库备份文件恢复数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| srcName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Restore failed, err: ' + err) - return - } - console.info('Restore success.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -从指定的数据库备份文件恢复数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| srcName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | - -**示例:** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restore success.') -}).catch((err)=>{ - console.info('Restore failed, err: ' + err) -}) -``` - -### setDistributedTables8+ +### setDistributedTables(deprecated) setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void 设置分布式列表,使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2129,15 +4378,19 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { }) ``` -### setDistributedTables8+ +### setDistributedTables(deprecated) setDistributedTables(tables: Array<string>): Promise<void> 设置分布式列表,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2149,7 +4402,7 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { | 类型 | 说明 | | -------- | -------- | -| Promise<void> | 指定Promise回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** @@ -2162,15 +4415,19 @@ promise.then(() => { }) ``` -### obtainDistributedTableName8+ +### obtainDistributedTableName(deprecated) obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2192,15 +4449,19 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, }) ``` -### obtainDistributedTableName8+ +### obtainDistributedTableName(deprecated) obtainDistributedTableName(device: string, table: string): Promise<string> 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2213,7 +4474,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, | 类型 | 说明 | | -------- | -------- | -| Promise<string> | 指定Promise回调函数。如果操作成功,返回远程设备的分布式表名。 | +| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | **示例:** @@ -2226,15 +4487,19 @@ promise.then((tableName) => { }) ``` -### sync8+ +### sync(deprecated) sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void 在设备之间同步数据, 使用callback异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-1)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2261,15 +4526,19 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul }) ``` -### sync8+ +### sync(deprecated) sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> 在设备之间同步数据,使用Promise异步回调。 +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-2)替代。 + **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2282,7 +4551,7 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul | 类型 | 说明 | | -------- | -------- | -| Promise<Array<[string, number]>> | 指定Promise回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | +| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | **示例:** @@ -2300,15 +4569,17 @@ promise.then((result) =>{ }) ``` -### on('dataChange')8+ +### on('dataChange')(deprecated) on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[on](#ondatachange9)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2333,15 +4604,17 @@ try { } ``` -### off('dataChange')8+ +### off('dataChange')(deprecated) off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 从数据库中删除指定类型的指定观察者, 使用callback异步回调。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +> **说明:** +> +> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[off](#offdatachange9)替代。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2366,59 +4639,17 @@ try { } ``` -## StoreConfig +## StoreConfig(deprecated) 管理关系数据库配置。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 +**说明:** + +从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[StoreConfigV9](#storeconfigv99)替代。 + +**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | name | string | 是 | 数据库文件名。 | -| encrypt9+ | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | - -## ValueType - -用于表示允许的数据字段类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 类型 | 说明 | -| -------- | -------- | -| number | 表示值类型为数字。 | -| string | 表示值类型为字符。 | -| boolean | 表示值类型为布尔值。| - - -## ValuesBucket - -用于存储键值对的类型。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 键类型 | 值类型 | -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -指数据库同步模式。 - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 - -| 名称 | 默认值 | 说明 | -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | 表示数据从本地设备推送到远程设备。 | -| SYNC_MODE_PULL | 1 | 表示数据从远程设备拉至本地设备。 | - -## SubscribeType8+ - -描述订阅类型。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 -| 名称 | 默认值 | 说明 | -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md index 19648104db323d6f2c89f71ce52e027cf317e7c8..33438f5bec8daf8bdb3225cc1f5c736bc97ffea6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @@ -6,7 +6,545 @@ > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -## 使用说明 +## ResultSetV99+ + +提供通过查询数据库生成的数据库结果集的访问方法。 + +### 使用说明 + +需要通过[RdbStoreV9.query()](js-apis-data-rdb.md#query)获取resultSetV9对象。 + +```js +import dataRdb from '@ohos.data.rdb'; +let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +predicatesV9.equalTo("AGE", 18); +let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSetV9) => { + console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); +}); +``` + +### 属性9+ + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 参数类型 | 必填 | 说明 | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | 是 | 获取结果集中所有列的名称。 | +| columnCount | number | 是 | 获取结果集中的列数。 | +| rowCount | number | 是 | 获取结果集中的行数。 | +| rowIndex | number | 是 | 获取结果集当前行的索引。 | +| isAtFirstRow | boolean | 是 | 检查结果集是否位于第一行。 | +| isAtLastRow | boolean | 是 | 检查结果集是否位于最后一行。 | +| isEnded | boolean | 是 | 检查结果集是否位于最后一行之后。 | +| isStarted | boolean | 是 | 检查指针是否移动过。 | +| isClosed | boolean | 是 | 检查当前结果集是否关闭。 | + +### getColumnIndex9+ + +getColumnIndex(columnName: string): number + +根据指定的列名获取列索引。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | 是 | 表示结果集中指定列的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 返回指定列的索引。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +resultSetV9.goToFirstRow(); +const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); +const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); +const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); +const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); + ``` + +### getColumnName9+ + +getColumnName(columnIndex: number): string + +根据指定的列索引获取列名。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | 是 | 表示结果集中指定列的索引。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| string | 返回指定列的名称。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const id = resultSetV9.getColumnName(0); +const name = resultSetV9.getColumnName(1); +const age = resultSetV9.getColumnName(2); + ``` + +### goTo9+ + +goTo(offset:number): boolean + +向前或向后转至结果集的指定行,相对于其当前位置偏移。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | 是 | 表示相对于当前位置的偏移量。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoto.then((resultSetV9) => { + resultSetV9.goTo(1); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow9+ + +goToRow(position: number): boolean + +转到结果集的指定行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| position | number | 是 | 表示要移动到的指定位置。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygotorow.then((resultSetV9) => { + resultSetV9.goToRow(5); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow9+ + +goToFirstRow(): boolean + + +转到结果集的第一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoFirst.then((resultSetV9) => { + resultSetV9.goToFirstRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow9+ + +goToLastRow(): boolean + +转到结果集的最后一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoLast.then((resultSetV9) => { + resultSetV9.goToLastRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow9+ + +goToNextRow(): boolean + +转到结果集的下一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoNext.then((resultSetV9) => { + resultSetV9.goToNextRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow9+ + +goToPreviousRow(): boolean + +转到结果集的上一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promisequerygoPrev.then((resultSetV9) => { + resultSetV9.goToPreviousRow(); + resultSetV9.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob9+ + +getBlob(columnIndex: number): Uint8Array + +以字节数组的形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------------------- | +| Uint8Array | 以字节数组的形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); + ``` + +### getString9+ + +getString(columnIndex: number): string + +以字符串形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| string | 以字符串形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); + ``` + +### getLong9+ + +getLong(columnIndex: number): number + +以Long形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------- | +| number | 以Long形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); + ``` + +### getDouble9+ + +getDouble(columnIndex: number): number + +以double形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| number | 以double形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); + ``` + +### isColumnNull9+ + +isColumnNull(columnIndex: number): boolean + +检查当前行中指定列的值是否为null。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------------------- | +| boolean | 如果当前行中指定列的值为null,则返回true,否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); + ``` + +### close9+ + +close(): void + +关闭结果集。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + + ```js +let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); +let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSetV9) => { + resultSetV9.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +## ResultSet(deprecated) + +提供通过查询数据库生成的数据库结果集的访问方法。 + +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[ResultSetV9](#resultsetv99)替代。 + +### 使用说明 需要通过[RdbStore.query()](js-apis-data-rdb.md#query)获取resultSet对象。 @@ -21,13 +559,13 @@ promise.then((resultSet) => { }); ``` -## ResultSet - -提供通过查询数据库生成的数据库结果集的访问方法。 +### 属性(deprecated) -### 属性 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[属性](#属性9)替代。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core。 +**系统能力:** 以下各项对应的系统能力均为SystemCapability.DistributedDataManager.RelationalStore.Core | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -41,13 +579,17 @@ promise.then((resultSet) => { | isStarted | boolean | 是 | 检查指针是否移动过。 | | isClosed | boolean | 是 | 检查当前结果集是否关闭。 | -### getColumnIndex +### getColumnIndex(deprecated) getColumnIndex(columnName: string): number 根据指定的列名获取列索引。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnIndex](#getcolumnindex9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -71,13 +613,17 @@ getColumnIndex(columnName: string): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName +### getColumnName(deprecated) getColumnName(columnIndex: number): string 根据指定的列索引获取列名。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnName](#getcolumnname9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -99,13 +645,17 @@ getColumnName(columnIndex: number): string const age = resultSet.getColumnName(2); ``` -### goTo +### goTo(deprecated) goTo(offset:number): boolean 向前或向后转至结果集的指定行,相对于其当前位置偏移。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goTo](#goto9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -124,7 +674,7 @@ goTo(offset:number): boolean ```js let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoto.then((resultSet) { + promisequerygoto.then((resultSet) => { resultSet.goTo(1); resultSet.close(); }).catch((err) => { @@ -132,13 +682,17 @@ goTo(offset:number): boolean }); ``` -### goToRow +### goToRow(deprecated) goToRow(position: number): boolean 转到结果集的指定行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToRow](#gotorow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -157,7 +711,7 @@ goToRow(position: number): boolean ```js let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygotorow.then((resultSet) { + promisequerygotorow.then((resultSet) => { resultSet.goToRow(5); resultSet.close(); }).catch((err) => { @@ -165,14 +719,17 @@ goToRow(position: number): boolean }); ``` -### goToFirstRow +### goToFirstRow(deprecated) goToFirstRow(): boolean - 转到结果集的第一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToFirstRow](#gotofirstrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -185,7 +742,7 @@ goToFirstRow(): boolean ```js let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoFirst.then((resultSet) { + promisequerygoFirst.then((resultSet) => { resultSet.goToFirstRow(); resultSet.close(); }).catch((err) => { @@ -193,13 +750,17 @@ goToFirstRow(): boolean }); ``` -### goToLastRow +### goToLastRow(deprecated) goToLastRow(): boolean 转到结果集的最后一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToLastRow](#gotolastrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -212,7 +773,7 @@ goToLastRow(): boolean ```js let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoLast.then((resultSet) { + promisequerygoLast.then((resultSet) => { resultSet.goToLastRow(); resultSet.close(); }).catch((err) => { @@ -220,13 +781,17 @@ goToLastRow(): boolean }); ``` -### goToNextRow +### goToNextRow(deprecated) goToNextRow(): boolean 转到结果集的下一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToNextRow](#gotonextrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -239,7 +804,7 @@ goToNextRow(): boolean ```js let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoNext.then((resultSet) { + promisequerygoNext.then((resultSet) => { resultSet.goToNextRow(); resultSet.close(); }).catch((err) => { @@ -247,13 +812,17 @@ goToNextRow(): boolean }); ``` -### goToPreviousRow +### goToPreviousRow(deprecated) goToPreviousRow(): boolean 转到结果集的上一行。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToPreviousRow](#gotopreviousrow9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -266,7 +835,7 @@ goToPreviousRow(): boolean ```js let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE"); let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promisequerygoPrev.then((resultSet) { + promisequerygoPrev.then((resultSet) => { resultSet.goToPreviousRow(); resultSet.close(); }).catch((err) => { @@ -274,13 +843,17 @@ goToPreviousRow(): boolean }); ``` -### getBlob +### getBlob(deprecated) getBlob(columnIndex: number): Uint8Array 以字节数组的形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getBlob](#getblob9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -300,13 +873,17 @@ getBlob(columnIndex: number): Uint8Array const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString +### getString(deprecated) getString(columnIndex: number): string 以字符串形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getString](#getstring9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -326,13 +903,17 @@ getString(columnIndex: number): string const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong +### getLong(deprecated) getLong(columnIndex: number): number 以Long形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getLong](#getlong9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -352,13 +933,17 @@ getLong(columnIndex: number): number const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble +### getDouble(deprecated) getDouble(columnIndex: number): number 以double形式获取当前行中指定列的值。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getDouble](#getdouble9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -378,13 +963,17 @@ getDouble(columnIndex: number): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull +### isColumnNull(deprecated) isColumnNull(columnIndex: number): boolean 检查当前行中指定列的值是否为null。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +> **说明:** +> +> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[isColumnNull](#iscolumnnull9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -404,20 +993,24 @@ isColumnNull(columnIndex: number): boolean const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close +### close(deprecated) close(): void 关闭结果集。 -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core。 +**说明:** + +从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[close](#close9)替代。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** ```js let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); - promiseClose.then((resultSet) { + promiseClose.then((resultSet) => { resultSet.close(); }).catch((err) => { console.log('resultset close failed'); diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md index 2110b8065f4602a382bb1e1b339c9f968377239c..064669b6e3100d19ace8f95bb6656c96d598947d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md @@ -24,8 +24,8 @@ import data_storage from '@ohos.data.storage'; | 名称 | 参数类型 | 可读 | 可写 | 说明 | | ---------------- | -------- | ---- | ---- | ------------------------------------- | -| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,需小于80字节。 | -| MAX_VALUE_LENGTH | string | 是 | 否 | value的最大长度限制,需小于8192字节。 | +| MAX_KEY_LENGTH | number | 是 | 否 | key的最大长度限制,需小于80字节。 | +| MAX_VALUE_LENGTH | number | 是 | 否 | value的最大长度限制,需小于8192字节。 | ## data_storage.getStorageSync diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md similarity index 90% rename from zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md rename to zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md index 202f1042a292d31e6882f77383e71cc1a936cd33..bad1f5f21c498bf8b14d6b5c22448c638945561a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -15,7 +15,7 @@ import defaultAppMgr from '@ohos.bundle.defaultAppManager'; 应用类型 -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp | 名称 | 类型 | 值 | 说明 | | -------- | -------- | -------------------------------------- | -------------------------------------- | @@ -34,7 +34,7 @@ isDefaultApplication(type: string): Promise\ 以异步方法根据系统已定义的应用类型判断当前应用是否是该应用类型的默认应用,使用Promise形式返回结果。 -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **参数:** @@ -51,6 +51,7 @@ isDefaultApplication(type: string): Promise\ **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) .then((data) => { console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data)); @@ -65,7 +66,7 @@ isDefaultApplication(type: string, callback: AsyncCallback\): void 以异步方法根据系统已定义的应用类型判断当前应用是否是该应用类型的默认应用,使用callback形式返回结果。 -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **参数:** @@ -77,6 +78,7 @@ isDefaultApplication(type: string, callback: AsyncCallback\): void **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -94,7 +96,7 @@ getDefaultApplication(type: string, userId?: number): Promise\ **需要权限:** ohos.permission.GET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -122,6 +124,7 @@ getDefaultApplication(type: string, userId?: number): Promise\ **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) .then((data) => { console.info('Operation successful. bundleInfo: ' + JSON.stringify(data)); @@ -147,7 +150,7 @@ getDefaultApplication(type: string, userId: number, callback: AsyncCallback\ { +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +let userId = 100; +defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -178,7 +183,7 @@ defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); }); -defaultAppMgr.getDefaultApplication("image/png", 100, (err, data) => { +defaultAppMgr.getDefaultApplication("image/png", userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -195,7 +200,7 @@ getDefaultApplication(type: string, callback: AsyncCallback\) : void **需要权限:** ohos.permission.GET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -217,6 +222,7 @@ getDefaultApplication(type: string, callback: AsyncCallback\) : void **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -224,7 +230,6 @@ defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, } console.info('Operation successful. bundleInfo:' + JSON.stringify(data)); }); - defaultAppMgr.getDefaultApplication("image/png", (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -236,13 +241,19 @@ defaultAppMgr.getDefaultApplication("image/png", (err, data) => { ## defaultAppMgr.setDefaultApplication -setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\ +setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\<**返回值:** + +| 类型 | 说明 | +| ----------------------------------------------------------- | --------------------------- | +| Promise\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Promise对象,返回BundleInfo | + +> 以异步方法根据系统已定义的应用类型或者符合媒体类型格式(type/subtype)的文件类型设置默认应用,使用Promise形式返回结果。 **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -254,6 +265,12 @@ setDefaultApplication(type: string, elementName: ElementName, userId?: number): | elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 要设置为默认应用的组件信息。 | | userId | number | 否 | 用户ID。默认值:调用方所在用户。 | +**返回值:** + +| 类型 | 说明 | +| -------------- | ---------------------------------- | +| Promise\ | Promise对象,无返回结果的Promise。 | + **错误码:** | 错误码ID | 错误码信息 | @@ -265,15 +282,25 @@ setDefaultApplication(type: string, elementName: ElementName, userId?: number): **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { bundleName: "com.test.app", moduleName: "module01", abilityName: "MainAbility" -}) -.then((data) => { +}).then((data) => { console.info('Operation successful.'); -}) -.catch((error) => { +}).catch((error) => { + console.error('Operation failed. Cause: ' + JSON.stringify(error)); +}); + +let userId = 100; +defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { + bundleName: "com.test.app", + moduleName: "module01", + abilityName: "MainAbility" +}, userId).then((data) => { + console.info('Operation successful.'); +}).catch((error) => { console.error('Operation failed. Cause: ' + JSON.stringify(error)); }); @@ -281,11 +308,9 @@ defaultAppMgr.setDefaultApplication("image/png", { bundleName: "com.test.app", moduleName: "module01", abilityName: "MainAbility" -}) -.then((data) => { +}, userId).then((data) => { console.info('Operation successful.'); -}) -.catch((error) => { +}).catch((error) => { console.error('Operation failed. Cause: ' + JSON.stringify(error)); }); ``` @@ -298,7 +323,7 @@ setDefaultApplication(type: string, elementName: ElementName, userId: number, ca **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -322,11 +347,13 @@ setDefaultApplication(type: string, elementName: ElementName, userId: number, ca **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { bundleName: "com.test.app", moduleName: "module01", abilityName: "MainAbility" -}, 100, (err, data) => { +}, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -338,7 +365,7 @@ defaultAppMgr.setDefaultApplication("image/png", { bundleName: "com.test.app", moduleName: "module01", abilityName: "MainAbility" -}, 100, (err, data) => { +}, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -355,7 +382,7 @@ setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCal **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -378,6 +405,7 @@ setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCal **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { bundleName: "com.test.app", moduleName: "module01", @@ -411,7 +439,7 @@ resetDefaultApplication(type: string, userId?: number): Promise\ **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -432,7 +460,9 @@ resetDefaultApplication(type: string, userId?: number): Promise\ **示例:** ```js -defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +let userId = 100; +defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId) .then((data) => { console.info('Operation successful.'); }) @@ -440,7 +470,7 @@ defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) console.error('Operation failed. Cause: ' + JSON.stringify(error)); }); -defaultAppMgr.resetDefaultApplication("image/png") +defaultAppMgr.resetDefaultApplication("image/png", userId) .then((data) => { console.info('Operation successful.'); }) @@ -457,7 +487,7 @@ resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\ { +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; +let userId = 100; +defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -487,7 +519,7 @@ defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100 console.info('Operation successful.'); }); -defaultAppMgr.resetDefaultApplication("image/png", 100, (err, data) => { +defaultAppMgr.resetDefaultApplication("image/png", userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); return; @@ -504,7 +536,7 @@ resetDefaultApplication(type: string, callback: AsyncCallback\) : void; **需要权限:** ohos.permission.SET_DEFAULT_APPLICATION -**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultAppManager.defaultAppManager +**系统能力:** SystemCapability.BundleManager.BundleFramework.DefaultApp **系统API:** 此接口为系统接口,三方应用不支持调用 @@ -525,6 +557,7 @@ resetDefaultApplication(type: string, callback: AsyncCallback\) : void; **示例:** ```js +import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md index dd35648cacc70ea65dfb26aba8629e44c48d64d9..4fb4fcdb83c8df3a3c661a2abf7d8fe97f84894a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deque.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -88,9 +88,10 @@ deque.insertFront(1); let b = [1, 2, 3]; deque.insertFront(b); let c = {name : "Dylon", age : "13"}; +deque.insertFront(c); deque.insertFront(false); try { - deque.insertFront.bind({}, "b")(); + deque.insertFront.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -127,9 +128,10 @@ deque.insertEnd(1); let b = [1, 2, 3]; deque.insertEnd(b); let c = {name : "Dylon", age : "13"}; +deque.insertEnd(c); deque.insertEnd(false); try { - deque.insertEnd.bind({}, "b")(); + deque.insertEnd.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -171,7 +173,7 @@ let result = deque.has("squirrel"); deque.insertFront("squirrel"); let result1 = deque.has("squirrel"); try { - deque.has.bind({}, "b")(); + deque.has.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -210,7 +212,7 @@ deque.insertFront(2); deque.insertFront(4); let result = deque.popFirst(); try { - deque.popFirst.bind({})(); + deque.popFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -249,7 +251,7 @@ deque.insertFront(2); deque.insertFront(4); let result = deque.popLast(); try { - deque.popLast.bind({})(); + deque.popLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -301,7 +303,7 @@ deque.forEach((value, index) => { try { deque.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -339,7 +341,7 @@ deque.insertFront(5); deque.insertFront(4); let result = deque.getFirst(); try { - deque.getFirst.bind({})(); + deque.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -377,7 +379,7 @@ deque.insertFront(5); deque.insertFront(4); let result = deque.getLast(); try { - deque.getLast.bind({})(); + deque.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -426,7 +428,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - deque[Symbol.iterator].bind({})(); + deque[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-display.md b/zh-cn/application-dev/reference/apis/js-apis-display.md index 4e6680987322cb3d837833f821b1f973592e48c4..c7cd21dfd3271e5c42884e305bacd6b870b59f25 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-display.md +++ b/zh-cn/application-dev/reference/apis/js-apis-display.md @@ -94,7 +94,7 @@ try { displayClass = display.getDefaultDisplaySync(); } catch (exception) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.getAllDisplays9+ @@ -204,25 +204,24 @@ hasPrivateWindow(displayId: number): boolean let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); -} catch (exception) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); - return; -}; -let ret = undefined; -try { - ret = display.hasPrivateWindow(displayClass.id); + let ret = undefined; + try { + ret = display.hasPrivateWindow(displayClass.id); + } catch (exception) { + console.error('Failed to check has privateWindow or not. Code: ' + JSON.stringify(exception)); + } + 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."); + } } catch (exception) { - console.error('Failed to check has privateWindow or not. Code: ' + JSON.stringify(exception)); -}; -if (ret == undefined) { - console.log("Failed to check has privateWindow or not."); + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); } -if (ret) { - console.log("There has privateWindow."); -} else if (!ret) { - console.log("There has no privateWindow."); -}; ``` ## display.on('add'|'remove'|'change') @@ -250,7 +249,7 @@ try { display.on("add", callback); } catch (exception) { console.error('Failed to register callback. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.off('add'|'remove'|'change') @@ -275,7 +274,7 @@ try { display.off("remove"); } catch (exception) { console.error('Failed to unregister callback. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.getDefaultDisplay(deprecated) @@ -450,17 +449,17 @@ getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); + + displayClass.getCutoutInfo((err, data) => { + if (err.code) { + console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); + }); } catch (exception) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); -}; - -displayClass.getCutoutInfo((err, data) => { - if (err.code) { - console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); -}); +} ``` ### getCutoutInfo9+ getCutoutInfo(): Promise<CutoutInfo> @@ -489,12 +488,14 @@ getCutoutInfo(): Promise<CutoutInfo> let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); + + let promise = displayClass.getCutoutInfo(); + promise.then((data) => { + console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + }); } catch (exception) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); -}; - -let promise = displayClass.getCutoutInfo(); -promise.then((data) => { - console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); -}); +} ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md index 462caa2391b5942034954d8b5645d47260e6dd11..6501cbf3d71da90d07e6db905ff2c3738a7f1751 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @@ -35,7 +35,7 @@ createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ------ | ------ | | config | [KVManagerConfig](#kvmanagerconfig) | 是 | 提供KVManager实例的配置信息,包括调用方的包名和用户信息。 | | callback | AsyncCallback<[KVManager](#kvmanager)> | 是 | 回调函数。返回创建的KVManager对象实例。 | @@ -75,7 +75,7 @@ createKVManager(config: KVManagerConfig): Promise<KVManager> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ------ | ------ | | config |[KVManagerConfig](#kvmanager) | 是 | 提供KVManager实例的配置信息,包括调用方的包名和用户信息。 | @@ -116,10 +116,10 @@ try { **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 参数名 | 参数类型 | 必填 | 说明 | -| ----- | ------ | ------ | ------ | -| userInfo | [UserInfo](#userinfo) | 是 | 调用方的用户信息。 | -| bundleName | string | 是 | 调用方的包名。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ------ | ------ | ------ | +| userInfo | [UserInfo](#userinfo) | 是 | 是 | 调用方的用户信息。 | +| bundleName | string | 是 | 是 | 调用方的包名。 | ## UserInfo @@ -127,10 +127,10 @@ try { **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 | 必填 | 说明 | -| ----- | ------ | ------ | ------ | -| userId | string | 是 | 指示要设置的用户ID。 | -| userType | [UserType](#usertype) | 是 | 指示要设置的用户类型。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ------ | ------ | ------ | +| userId | string | 是 | 是 | 指示要设置的用户ID。 | +| userType | [UserType](#usertype) | 是 | 是 | 指示要设置的用户类型。 | ## UserType @@ -158,7 +158,7 @@ getKVStore<T extends KVStore>(storeId: string, options: Options, callback: **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ------ | ------ | | storeId | string | 是 | 数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | | options | [Options](#options) | 是 | 创建KVStore实例的配置信息。 | @@ -202,7 +202,7 @@ getKVStore<T extends KVStore>(storeId: string, options: Options): Promise& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------------- | ---- | -------------------- | | storeId | string | 是 | 数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | | options | [Options](#options) | 是 | 创建KVStore实例的配置信息。| @@ -250,7 +250,7 @@ closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCa **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------- | ---- | --------------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要关闭的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -295,7 +295,7 @@ closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要关闭的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -349,7 +349,7 @@ deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要删除的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -392,7 +392,7 @@ deleteKVStore(appId: string, storeId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要删除的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -446,7 +446,7 @@ getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | callback | AsyncCallback<string[]> | 是 |回调函数。返回所有创建的KvStore数据库的storeId。 | @@ -476,7 +476,7 @@ getAllKVStoreId(appId: string): Promise<string[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | appId | string | 是 | 所调用数据库方的包名。 | @@ -515,7 +515,7 @@ on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): voi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event | string | 是 | 订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。 | | deathCallback | Callback<void> | 是 | 回调函数。 | @@ -546,7 +546,7 @@ off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): v **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event | string | 是 | 取消订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。 | | deathCallback | Callback<void> | 否 | 回调函数。 | @@ -573,15 +573,15 @@ try { 用于提供创建数据库的配置信息。 -| 参数名 | 参数类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | 否 | 当数据库文件不存在时是否创建数据库,默认创建。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | 否 |设置数据库文件是否加密,默认不加密。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | 否 |设置数据库文件是否备份,默认备份。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| autoSync | boolean | 否 |设置数据库文件是否自动同步,默认不自动同步。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
**需要权限**: ohos.permission.DISTRIBUTED_DATASYNC | -| kvStoreType | [KVStoreType](#kvstoretype) | 否 |设置要创建的数据库类型,默认为多设备协同数据库。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| securityLevel | [SecurityLevel](#securitylevel) | 否 |设置数据库安全级别,默认不设置安全级别。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| schema8+ | [Schema](#schema8) | 否 | 设置定义存储在数据库中的值。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ------ | ------ | -------------------| +| createIfMissing | boolean | 是 | 是 | 当数据库文件不存在时是否创建数据库,默认创建。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | 是 | 是 |设置数据库文件是否加密,默认不加密。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | 是 | 是 |设置数据库文件是否备份,默认备份。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| autoSync | boolean | 是 | 是 |设置数据库文件是否自动同步,默认不自动同步。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
**需要权限**: ohos.permission.DISTRIBUTED_DATASYNC | +| kvStoreType | [KVStoreType](#kvstoretype) | 是 | 是 |设置要创建的数据库类型,默认为多设备协同数据库。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| securityLevel | [SecurityLevel](#securitylevel) | 是 | 是 |设置数据库安全级别,默认不设置安全级别。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| schema8+ | [Schema](#schema8) | 是 | 是 | 设置定义存储在数据库中的值。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | ## KVStoreType @@ -631,12 +631,12 @@ KVStore常量。 **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| 名称 | 类型 | 说明 | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | 表示json根对象。 | -| indexes8+ | Array\ | 表示json类型的字符串数组。 | -| mode8+ | number | 表示Schema的模式。 | -| skip8+ | number | Schema的跳跃大小。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --- | ---- | ---- | ---- | ----------------------- | +| root8+ | [FieldNode](#fieldnode8) | 是 | 是 | 表示json根对象。 | +| indexes8+ | Array\ | 是 | 是 | 表示json类型的字符串数组。 | +| mode8+ | number | 是 | 是 | 表示Schema的模式。 | +| skip8+ | number | 是 | 是 | Schema的跳跃大小。 | ### constructor8+ @@ -652,11 +652,11 @@ constructor() **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| 名称 | 类型 | 说明 | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | 表示数据库字段是否可以为空。 | -| default8+ | string | 表示Fieldnode的默认值。 | -| type8+ | number | 表示指定节点对应数据类型的值。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --- | ---- | ---- | ---- | ----------------------- | +| nullable8+ | boolean | 是 | 是 | 表示数据库字段是否可以为空。 | +| default8+ | string | 是 | 是 | 表示Fieldnode的默认值。 | +| type8+ | number | 是 | 是 | 表示指定节点对应数据类型的值。 | ### constructor8+ @@ -668,7 +668,7 @@ constructor(name: string) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | --------------- | | name | string | 是 | FieldNode的值。 | @@ -682,7 +682,7 @@ appendChild(child: FieldNode): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | child | [FieldNode](#fieldnode8) | 是 | 要附加的域节点。 | @@ -935,7 +935,7 @@ move(offset: number): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | offset | number | 是 | 表示与当前位置的相对偏移量,负偏移表示向后移动,正偏移表示向前移动。 | @@ -975,7 +975,7 @@ moveToPosition(position: number): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | position | number | 是 |表示绝对位置。 | @@ -1230,7 +1230,7 @@ equalTo(field: string, value: number|string|boolean): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1265,7 +1265,7 @@ notEqualTo(field: string, value: number|string|boolean): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1300,7 +1300,7 @@ greaterThan(field: string, value: number|string|boolean): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1335,10 +1335,10 @@ lessThan(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | -| value | number\|string\|boolean | 是 | 表示指定的值。| +| value | number\|string | 是 | 表示指定的值。| **返回值:** @@ -1370,10 +1370,10 @@ greaterThanOrEqualTo(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | -| value | number\|string\|boolean | 是 | 表示指定的值。| +| value | number\|string | 是 | 表示指定的值。| **返回值:** @@ -1405,10 +1405,10 @@ lessThanOrEqualTo(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | -| value | number\|string\|boolean | 是 | 表示指定的值。| +| value | number\|string | 是 | 表示指定的值。| **返回值:** @@ -1440,7 +1440,7 @@ isNull(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | @@ -1475,7 +1475,7 @@ inNumber(field: string, valueList: number[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | valueList | number[] | 是 | 表示指定的值列表。| @@ -1510,7 +1510,7 @@ inString(field: string, valueList: string[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | valueList | string[] | 是 | 表示指定的字符串值列表。| @@ -1545,7 +1545,7 @@ notInNumber(field: string, valueList: number[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | valueList | number[] | 是 | 表示指定的值列表。| @@ -1580,7 +1580,7 @@ notInString(field: string, valueList: string[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | valueList | string[] | 是 | 表示指定的字符串值列表。| @@ -1615,7 +1615,7 @@ like(field: string, value: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | string | 是 | 表示指定的字符串值。| @@ -1650,7 +1650,7 @@ unlike(field: string, value: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | string | 是 | 表示指定的字符串值。| @@ -1745,7 +1745,7 @@ orderByAsc(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | @@ -1780,7 +1780,7 @@ orderByDesc(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | @@ -1815,7 +1815,7 @@ limit(total: number, offset: number): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | total | number | 是 |表示指定的结果数。 | | offset | number | 是 |表示起始位置。 | @@ -1853,7 +1853,7 @@ isNotNull(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | @@ -1947,7 +1947,7 @@ prefixKey(prefix: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | prefix | string | 是 |表示指定的键前缀。 | @@ -1982,7 +1982,7 @@ setSuggestIndex(index: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | index | string | 是 |指示要设置的索引。 | @@ -2017,7 +2017,7 @@ deviceId(deviceId:string):Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId | string | 是 |指示查询的设备ID。 | @@ -2084,7 +2084,7 @@ put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncC **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要添加数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | value | Uint8Array \| string \| number \| boolean | 是 |要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于[MAX_VALUE_LENGTH](#constants)。 | @@ -2119,7 +2119,7 @@ put(key: string, value: Uint8Array | string | number | boolean): Promise<void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要添加数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | value | Uint8Array \| string \| number \| boolean | 是 |要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于[MAX_VALUE_LENGTH](#constants)。 | @@ -2157,7 +2157,7 @@ delete(key: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要删除数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback | AsyncCallback<void> | 是 |回调函数。 | @@ -2198,7 +2198,7 @@ delete(key: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要删除数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -2240,7 +2240,7 @@ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotific **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |订阅的事件名,固定为'dataChange',表示数据变更事件。 | | type |[SubscribeType](#subscribetype) | 是 |表示订阅的类型。 | @@ -2265,7 +2265,7 @@ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback |Callback<Array<[string, number]>> | 是 |回调函数。 | @@ -2289,7 +2289,7 @@ off(event:'dataChange', listener?: Callback<ChangeNotification>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |取消订阅的事件名,固定为'dataChange',表示数据变更事件。 | | listener |Callback<[ChangeNotification](#changenotification)> |否 |回调函数。 | @@ -2325,7 +2325,7 @@ putBatch(entries: Entry[], callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | 是 |表示要批量插入的键值对。 | | callback |Asyncallback<void> |是 |回调函数。 | @@ -2372,7 +2372,7 @@ putBatch(entries: Entry[]): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | 是 |表示要批量插入的键值对。 | @@ -2426,7 +2426,7 @@ deleteBatch(keys: string[], callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keys |string[] | 是 |表示要批量删除的键值对。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -2473,7 +2473,7 @@ deleteBatch(keys: string[]): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keys |string[] | 是 |表示要批量删除的键值对。 | @@ -2529,7 +2529,7 @@ startTransaction(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -2616,7 +2616,7 @@ commit(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -2678,7 +2678,7 @@ rollback(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -2740,7 +2740,7 @@ enableSync(enabled: boolean, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | enabled |boolean | 是 |设定是否开启同步,true表示开启同步,false表示不启用同步。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -2773,7 +2773,7 @@ enableSync(enabled: boolean): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | enabled |boolean | 是 |设定是否开启同步,true表示开启同步,false表示不启用同步。 | @@ -2809,7 +2809,7 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: Asy **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | localLabels |string[] | 是 |表示本地设备的同步标签。 | | remoteSupportLabels |string[] | 是 |表示要同步数据的设备的同步标签。 | @@ -2841,7 +2841,7 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<v **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | localLabels |string[] | 是 |表示本地设备的同步标签。 | | remoteSupportLabels |string[] | 是 |表示要同步数据的设备的同步标签。 | @@ -2889,7 +2889,7 @@ try { **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 |可读 |可写 | 说明 | +| 名称 | 类型 |可读 |可写 | 说明 | | ----- | ------- | -----| ------|------------------------ | | insertEntries | [Entry](#entry)[] | 是 | 是 |数据添加记录。 | | updateEntries | [Entry](#entry)[] | 是 | 是 |数据更新记录。 | @@ -2902,7 +2902,7 @@ try { **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 |可读 |可写 | 说明 | +| 名称 | 类型 |可读 |可写 | 说明 | | ----- | ------- | -----| ------|------------------------ | | key | string | 是 | 是 |键值。 | | value | [Value](#value) | 是 | 是 |值对象。 | @@ -2914,7 +2914,7 @@ try { **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 |可读 |可写 | 说明 | +| 名称 | 类型 |可读 |可写 | 说明 | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | 是 | 是 |值类型。 | | value | Uint8Array \| string \| number \| boolean| 是 | 是 |值。 | @@ -2952,7 +2952,7 @@ get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | numb **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key |string | 是 |要查询数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | 是 |回调函数。返回获取查询的值。 | @@ -2990,7 +2990,7 @@ get(key: string): Promise<Uint8Array | string | boolean | number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key |string | 是 |要查询数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -3033,7 +3033,7 @@ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | 是 |表示要匹配的键前缀。 | | callback |AsyncCallback<[Entry](#entry)[]> | 是 |回调函数。返回匹配指定前缀的键值对列表。 | @@ -3079,7 +3079,7 @@ getEntries(keyPrefix: string): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -3137,7 +3137,7 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示要匹配的键前缀。 | | callback |AsyncCallback<[Entry](#entry)[]> | 是 |回调函数。返回与指定Query对象匹配的键值对列表。 | @@ -3188,7 +3188,7 @@ getEntries(query: Query): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -3246,7 +3246,7 @@ getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | 是 |表示要匹配的键前缀。 | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | 是 |回调函数。返回具有指定前缀的结果集。 | @@ -3295,7 +3295,7 @@ getResultSet(keyPrefix: string): Promise<KvStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -3355,7 +3355,7 @@ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): voi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |Query | 是 |表示查询对象。 | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | 是 |回调函数,获取与指定Query对象匹配的KvStoreResultSet对象。 | @@ -3403,7 +3403,7 @@ getResultSet(query: Query): Promise<KvStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -3459,7 +3459,7 @@ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | 是 |表示要关闭的KvStoreResultSet对象。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -3493,7 +3493,7 @@ closeResultSet(resultSet: KvStoreResultSet): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | 是 |表示要关闭的KvStoreResultSet对象。 | @@ -3530,7 +3530,7 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | | callback |AsyncCallback<number> | 是 |回调函数。返回与指定Query对象匹配的结果数。 | @@ -3576,7 +3576,7 @@ getResultSize(query: Query): Promise<number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -3631,7 +3631,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |表示要删除设备的名称。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -3673,7 +3673,7 @@ removeDeviceData(deviceId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |表示要删除设备的名称。 | @@ -3722,7 +3722,7 @@ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback |Callback<Array<[string, number]>> | 是 |回调函数。用于向调用方发送同步结果的回调。 | @@ -3758,7 +3758,7 @@ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |取消订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback |Callback<Array<[string, number]>> | 否 |回调函数。用于向调用方发送同步结果的回调。 | @@ -3797,7 +3797,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceIds |string[] | 是 |同一组网环境下,需要同步的设备的deviceId列表。 | | mode |[SyncMode](#syncmode) | 是 |同步模式。 | @@ -3820,7 +3820,7 @@ setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | defaultAllowedDelayMs |number | 是 |表示数据库同步允许的默认延迟,以毫秒为单位。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -3850,7 +3850,7 @@ setSyncParam(defaultAllowedDelayMs: number): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | defaultAllowedDelayMs |number | 是 |表示数据库同步允许的默认延迟,以毫秒为单位。 | @@ -3888,7 +3888,7 @@ getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | callback |AsyncCallback<[SecurityLevel](#securitylevel)> | 是 |回调函数。返回数据库的安全级别。 | @@ -3956,7 +3956,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|num **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | key |string | 是 |表示要查询key值的键。 | @@ -3991,7 +3991,7 @@ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | key |string | 是 |表示要查询key值的键。 | @@ -4035,7 +4035,7 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -4083,7 +4083,7 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -4142,7 +4142,7 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | | callback |AsyncCallback<[Entry](#entry)[]> | 是 |回调函数,返回与指定Query对象匹配的键值对列表。 | @@ -4194,7 +4194,7 @@ getEntries(query: Query): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4252,7 +4252,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |键值对所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4305,7 +4305,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |键值对所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4365,7 +4365,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvS **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -4400,7 +4400,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet&g **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | keyPrefix |string | 是 |表示要匹配的键前缀。 | @@ -4444,7 +4444,7 @@ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): voi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | 是 |回调函数,返回与指定Query对象匹配的KvStoreResultSet对象。 | @@ -4496,7 +4496,7 @@ getResultSet(query: Query): Promise<KvStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4560,7 +4560,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreR **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4612,7 +4612,7 @@ getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4678,7 +4678,7 @@ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#getresultset8) | 是 |指示要关闭的KvStoreResultSet对象。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -4713,7 +4713,7 @@ closeResultSet(resultSet: KvStoreResultSet): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#getresultset8) | 是 |指示要关闭的KvStoreResultSet对象。 | @@ -4751,7 +4751,7 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | | callback |AsyncCallback<number> | 是 |回调函数,返回与指定Query对象匹配的结果数。 | @@ -4798,7 +4798,7 @@ getResultSize(query: Query): Promise<number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4854,7 +4854,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4901,7 +4901,7 @@ getResultSize(deviceId: string, query: Query): Promise<number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |KvStoreResultSet对象所属的设备ID。 | | query |[Query](#query8) | 是 |表示查询对象。 | @@ -4957,7 +4957,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要删除其数据的设备。 | | callback |AsyncCallback<void> | 是 |回调函数。 | @@ -4999,7 +4999,7 @@ removeDeviceData(deviceId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要删除其数据的设备。 | @@ -5050,7 +5050,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceIds |string[] | 是 |需要同步DeviceKvStore数据库的设备ID列表。 | | mode |[SyncMode](#syncmode) | 是 |同步模式。 | @@ -5087,7 +5087,7 @@ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback |Callback | 是 |回调函数。用于向调用方发送同步结果的回调。 | @@ -5123,7 +5123,7 @@ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | event |string | 是 |取消订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback |Callback; **错误码:** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | |---------------|-------------------------| @@ -158,7 +158,7 @@ getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\ **错误码:** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | |---------------|-------------------------| @@ -224,7 +224,7 @@ getRemoteAbilityInfo(elementNames: Array\): Promise\, locale: string, callback **错误码:** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | |---------------|-------------------------| @@ -464,7 +464,7 @@ getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise **错误码:** -以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 | 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | |---------------|-------------------------| diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md index a1fd2b59fb7a2a13f0315cf9d46d567544158bfb..bec88516f18b34a540732e0226186a56a7dc4bb4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -26,10 +26,10 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 参数名 | 参数类型 | 必填 | 说明 | -| ---------- | --------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| bundleName | string | 是 | 调用方的包名。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 是 |应用的上下文。
FA模型的应用Context定义见[Context](js-apis-Context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| bundleName | string | 是 | 是 | 调用方的包名。 | ## Constants @@ -67,7 +67,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 |可读 |可写 | 说明 | +| 名称 | 类型 |可读 |可写 | 说明 | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#valuetype) | 是 | 是 |值类型。 | | value | Uint8Array \| string \| number \| boolean| 是 | 是 |值。 | @@ -78,7 +78,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ----- | --------------- | ---- | ---- | -------- | | key | string | 是 | 是 | 键值。 | | value | [Value](#value) | 是 | 是 | 值对象。 | @@ -89,7 +89,7 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ------------- | ----------------- | ---- | ---- | ------------------------ | | insertEntries | [Entry](#entry)[] | 是 | 是 | 数据添加记录。 | | updateEntries | [Entry](#entry)[] | 是 | 是 | 数据更新记录。 | @@ -146,15 +146,15 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; 用于提供创建数据库的配置信息。 -| 参数名 | 参数类型 | 必填 | 说明 | -| --------------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| createIfMissing | boolean | 否 | 当数据库文件不存在时是否创建数据库,默认创建。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | 否 | 设置数据库文件是否加密,默认不加密。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | 否 | 设置数据库文件是否备份,默认备份。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| autoSync | boolean | 否 | 设置数据库文件是否自动同步,默认不自动同步。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
**需要权限**: ohos.permission.DISTRIBUTED_DATASYNC | -| kvStoreType | [KVStoreType](#kvstoretype) | 否 | 设置要创建的数据库类型,默认为多设备协同数据库。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| securityLevel | [SecurityLevel](#securitylevel) | 是 | 设置数据库安全级别。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | -| schema | [Schema](#schema) | 否 | 设置定义存储在数据库中的值,默认不使用Schema。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| createIfMissing | boolean | 是 | 是 | 当数据库文件不存在时是否创建数据库,默认创建。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | 是 | 是 | 设置数据库文件是否加密,默认不加密。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | 是 | 是 | 设置数据库文件是否备份,默认备份。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| autoSync | boolean | 是 | 是 | 设置数据库文件是否自动同步,默认不自动同步。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
**需要权限**: ohos.permission.DISTRIBUTED_DATASYNC | +| kvStoreType | [KVStoreType](#kvstoretype) | 是 | 是 | 设置要创建的数据库类型,默认为多设备协同数据库。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| securityLevel | [SecurityLevel](#securitylevel) | 是 | 是 |设置数据库安全级别。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core | +| schema | [Schema](#schema) | 是 | 是 | 设置定义存储在数据库中的值,默认不使用Schema。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | ## Schema @@ -162,12 +162,12 @@ import distributedKVStore from '@ohos.data.distributedKVStore'; **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| 名称 | 类型 | 说明 | -| ------- | ----------------------- | -------------------------- | -| root | [FieldNode](#fieldnode) | 表示json根对象。 | -| indexes | Array\ | 表示json类型的字符串数组。 | -| mode | number | 表示Schema的模式。 | -| skip | number | Schema的跳跃大小。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------- | ----------------------- | ---- | ---- | -------------------------- | +| root | [FieldNode](#fieldnode) | 是 | 是 | 表示json根对象。 | +| indexes | Array\ | 是 | 是 | 表示json类型的字符串数组。 | +| mode | number | 是 | 是 | 表示Schema的模式。 | +| skip | number | 是 | 是 | Schema的跳跃大小。 | ### constructor @@ -183,11 +183,11 @@ constructor() **系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| 名称 | 类型 | 说明 | -| -------- | ------- | ------------------------------ | -| nullable | boolean | 表示数据库字段是否可以为空。 | -| default | string | 表示Fieldnode的默认值。 | -| type | number | 表示指定节点对应数据类型的值。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------- | ---- | ---- | ------------------------------ | +| nullable | boolean | 是 | 是 | 表示数据库字段是否可以为空。 | +| default | string | 是 | 是 | 表示Fieldnode的默认值。 | +| type | number | 是 | 是 | 表示指定节点对应数据类型的值。 | ### constructor @@ -199,7 +199,7 @@ constructor(name: string) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | --------------- | | name | string | 是 | FieldNode的值。 | @@ -213,7 +213,7 @@ appendChild(child: FieldNode): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------- | ---- | ---------------- | | child | [FieldNode](#fieldnode) | 是 | 要附加的域节点。 | @@ -256,7 +256,7 @@ createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | | config | [KVManagerConfig](#kvmanagerconfig) | 是 | 提供KVManager实例的配置信息,包括调用方的包名和应用上下文。 | | callback | AsyncCallback<[KVManager](#kvmanager)> | 是 | 回调函数。返回创建的KVManager对象实例。 | @@ -326,7 +326,7 @@ createKVManager(config: KVManagerConfig): Promise<KVManager> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | ----------------------------- | ---- | --------------------------------------------------------- | | config | [KVManagerConfig](#kvmanager) | 是 | 提供KVManager实例的配置信息,包括调用方的包名和用户信息。 | @@ -401,7 +401,7 @@ getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | storeId | string | 是 | 数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | | options | [Options](#options) | 是 | 创建分布式键值实例的配置信息。 | @@ -453,7 +453,7 @@ getKVStore<T >(storeId: string, options: Options): Promise<T> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------- | ---- | ------------------------------------------------------------ | | storeId | string | 是 | 数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | | options | [Options](#options) | 是 | 创建分布式键值实例的配置信息。 | @@ -508,7 +508,7 @@ closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要关闭的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -541,7 +541,7 @@ try { }); }); } catch (e) { - console.error(`An unexpected error occurred.code is ${err.code},message is ${err.message}`); + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` @@ -555,7 +555,7 @@ closeKVStore(appId: string, storeId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | -------- | ---- | ------------------------------------------------------------ | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要关闭的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -607,7 +607,7 @@ deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要删除的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -666,7 +666,7 @@ deleteKVStore(appId: string, storeId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | -------- | ---- | ------------------------------------------------------------ | | appId | string | 是 | 所调用数据库方的包名。 | | storeId | string | 是 | 要删除的数据库唯一标识符,长度不大于[MAX_STORE_ID_LENGTH](#constants)。 | @@ -726,7 +726,7 @@ getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------- | ---- | --------------------------------------------------- | | appId | string | 是 | 所调用数据库方的包名。 | | callback | AsyncCallback<string[]> | 是 | 回调函数。返回所有创建的分布式键值数据库的storeId。 | @@ -738,7 +738,7 @@ let kvManager; try { kvManager.getAllKVStoreId('appId', function (err, data) { if (err != undefined) { - console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); return; } console.log('Succeeded in getting AllKVStoreId'); @@ -759,7 +759,7 @@ getAllKVStoreId(appId: string): Promise<string[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ---------------------- | | appId | string | 是 | 所调用数据库方的包名。 | @@ -796,7 +796,7 @@ on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): voi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------- | -------------------- | ---- | ------------------------------------------------------------ | | event | string | 是 | 订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。 | | deathCallback | Callback<void> | 是 | 回调函数。 | @@ -826,7 +826,7 @@ off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): v **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------- | -------------------- | ---- | ------------------------------------------------------------ | | event | string | 是 | 取消订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。 | | deathCallback | Callback<void> | 否 | 回调函数。 | @@ -1060,7 +1060,7 @@ move(offset: number): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------------------------------------------ | | offset | number | 是 | 表示与当前位置的相对偏移量,负偏移表示向后移动,正偏移表示向前移动。 | @@ -1099,7 +1099,7 @@ moveToPosition(position: number): boolean **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | -------------- | | position | number | 是 | 表示绝对位置。 | @@ -1346,7 +1346,7 @@ equalTo(field: string, value: number|string|boolean): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1380,7 +1380,7 @@ notEqualTo(field: string, value: number|string|boolean): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1413,7 +1413,7 @@ greaterThan(field: string, value: number|string|boolean): Query **系统能力:** SystemCapability.DistributedDataManager.KVStore.Core **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string\|boolean | 是 | 表示指定的值。| @@ -1448,7 +1448,7 @@ lessThan(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string | 是 | 表示指定的值。| @@ -1483,7 +1483,7 @@ greaterThanOrEqualTo(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string | 是 | 表示指定的值。| @@ -1518,7 +1518,7 @@ lessThanOrEqualTo(field: string, value: number|string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number\|string | 是 | 表示指定的值。| @@ -1552,7 +1552,7 @@ isNull(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | @@ -1585,7 +1585,7 @@ inNumber(field: string, valueList: number[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | valueList | number[] | 是 | 表示指定的值列表。 | @@ -1619,7 +1619,7 @@ inString(field: string, valueList: string[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | valueList | string[] | 是 | 表示指定的字符串值列表。 | @@ -1653,7 +1653,7 @@ notInNumber(field: string, valueList: number[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | valueList | number[] | 是 | 表示指定的值列表。 | @@ -1687,7 +1687,7 @@ notInString(field: string, valueList: string[]): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | valueList | string[] | 是 | 表示指定的字符串值列表。 | @@ -1721,7 +1721,7 @@ like(field: string, value: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | value | string | 是 | 表示指定的字符串值。 | @@ -1755,7 +1755,7 @@ unlike(field: string, value: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | | value | string | 是 | 表示指定的字符串值。 | @@ -1847,7 +1847,7 @@ orderByAsc(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | @@ -1881,7 +1881,7 @@ orderByDesc(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | @@ -1915,7 +1915,7 @@ limit(total: number, offset: number): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------ | | total | number | 是 | 表示指定的结果数。 | | offset | number | 是 | 表示起始位置。 | @@ -1952,7 +1952,7 @@ isNotNull(field: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ----------------------------- | | fieId | string | 是 | 表示指定字段,不能包含' ^ '。 | @@ -2043,7 +2043,7 @@ prefixKey(prefix: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------ | | prefix | string | 是 | 表示指定的键前缀。 | @@ -2077,7 +2077,7 @@ setSuggestIndex(index: string): Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------ | | index | string | 是 | 指示要设置的索引。 | @@ -2111,7 +2111,7 @@ deviceId(deviceId:string):Query **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ------------------ | | deviceId | string | 是 | 指示查询的设备ID。 | @@ -2175,7 +2175,7 @@ put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncC **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要添加数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | value | Uint8Array \| string \| number \| boolean | 是 |要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于[MAX_VALUE_LENGTH](#constants)。 | @@ -2219,7 +2219,7 @@ put(key: string, value: Uint8Array | string | number | boolean): Promise<void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key | string | 是 |要添加数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | value | Uint8Array \| string \| number \| boolean | 是 |要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于[MAX_VALUE_LENGTH](#constants)。 | @@ -2266,7 +2266,7 @@ putBatch(entries: Entry[], callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------ | ---- | ------------------------ | | entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。 | | callback | Asyncallback<void> | 是 | 回调函数。 | @@ -2328,7 +2328,7 @@ putBatch(entries: Entry[]): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------- | ---- | ------------------------ | | entries | [Entry](#entry)[] | 是 | 表示要批量插入的键值对。 | @@ -2393,7 +2393,7 @@ putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------ | | value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | 是 | 表示要插入的数据。 | | callback | Asyncallback<void> | 是 | 回调函数。 | @@ -2445,7 +2445,7 @@ putBatch(value: Array<ValuesBucket>): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------------------------------------ | ---- | ------------------ | | value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | 是 | 表示要插入的数据。 | @@ -2498,7 +2498,7 @@ delete(key: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | key | string | 是 | 要删除数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -2535,7 +2535,7 @@ try { }); }); } catch (e) { - console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`; + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); } ``` @@ -2549,7 +2549,7 @@ delete(key: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------------------------------------------ | | key | string | 是 | 要删除数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -2603,7 +2603,7 @@ delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallb **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -2649,7 +2649,7 @@ delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | @@ -2704,7 +2704,7 @@ deleteBatch(keys: string[], callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------ | | keys | string[] | 是 | 表示要批量删除的键值对。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -2768,7 +2768,7 @@ deleteBatch(keys: string[]): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------ | | keys | string[] | 是 | 表示要批量删除的键值对。 | @@ -2833,7 +2833,7 @@ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------- | | deviceId | string | 是 | 表示要删除设备的名称。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -2882,7 +2882,7 @@ removeDeviceData(deviceId: string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ---------------------- | | deviceId | string | 是 | 表示要删除设备的名称。 | @@ -2938,10 +2938,10 @@ get(key: string, callback: AsyncCallback) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | key |string | 是 |要查询数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | 是 |回调函数。返回获取查询的值。 | +| callback |AsyncCallback<boolean \| string \| number \| Uint8Array>) | 是 |回调函数。返回获取查询的值。 | **错误码:** @@ -2989,7 +2989,7 @@ get(key: string): Promise<boolean | string| number | Uint8Array> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------------------------------------------ | | key | string | 是 | 要查询数据的key,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -3041,7 +3041,7 @@ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------------------------------------- | ---- | ---------------------------------------- | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | | callback | AsyncCallback<[Entry](#entry)[]> | 是 | 回调函数。返回匹配指定前缀的键值对列表。 | @@ -3104,7 +3104,7 @@ getEntries(keyPrefix: string): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | -------------------- | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -3167,7 +3167,7 @@ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ----------------------------------------------- | | query | [Query](query) | 是 | 表示要匹配的键前缀。 | | callback | AsyncCallback<[Entry](#entry)[]> | 是 | 回调函数。返回与指定Query对象匹配的键值对列表。 | @@ -3230,7 +3230,7 @@ getEntries(query: Query): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | | query | [Query](query) | 是 | 表示查询对象。 | @@ -3297,7 +3297,7 @@ getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | | callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | 是 | 回调函数。返回具有指定前缀的结果集。 | @@ -3366,7 +3366,7 @@ getResultSet(keyPrefix: string): Promise<KVStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | -------------------- | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -3434,7 +3434,7 @@ getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): voi **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | | query | Query | 是 | 表示查询对象。 | | callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | 是 | 回调函数,获取与指定Query对象匹配的KVStoreResultSet对象。 | @@ -3497,7 +3497,7 @@ getResultSet(query: Query): Promise<KVStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | | query | [Query](query) | 是 | 表示查询对象。 | @@ -3564,7 +3564,7 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: Asyn **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | | callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | 是 | 回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。 | @@ -3620,7 +3620,7 @@ getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KV **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | @@ -3675,7 +3675,7 @@ closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------------------- | ---- | ---------------------------------- | | resultSet | [KVStoreResultSet](#kvstoreresultset) | 是 | 表示要关闭的KVStoreResultSet对象。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -3708,7 +3708,7 @@ closeResultSet(resultSet: KVStoreResultSet): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------------------- | ---- | ---------------------------------- | | resultSet | [KVStoreResultSet](#kvstoreresultset) | 是 | 表示要关闭的KVStoreResultSet对象。 | @@ -3744,7 +3744,7 @@ getResultSize(query: Query, callback: AsyncCallback<number>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------------------- | | query | [Query](query) | 是 | 表示查询对象。 | | callback | AsyncCallback<number> | 是 | 回调函数。返回与指定Query对象匹配的结果数。 | @@ -3802,7 +3802,7 @@ getResultSize(query: Query): Promise<number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------------- | ---- | -------------- | | query | [Query](query) | 是 | 表示查询对象。 | @@ -3865,7 +3865,7 @@ backup(file:string, callback: AsyncCallback<void>):void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | file | string | 是 | 备份数据库的指定名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback | AsyncCallback<void> | 是 | 回调函数。当以指定名称备份数据库成功,err为undefined,否则为错误对象。 | @@ -3907,7 +3907,7 @@ backup(file:string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------------------------------------------ | | file | string | 是 | 备份数据库的指定名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -3952,7 +3952,7 @@ restore(file:string, callback: AsyncCallback<void>):void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | file | string | 是 | 指定的数据库文件名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback | AsyncCallback<void> | 是 | 回调函数。当从指定的数据库文件恢复数据库成功,err为undefined,否则为错误对象。 | @@ -3994,7 +3994,7 @@ restore(file:string): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | -------- | ---- | ------------------------------------------------------------ | | file | string | 是 | 指定的数据库文件名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -4039,7 +4039,7 @@ deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[str **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | | files | Array<string> | 是 | 删除备份文件所指定的名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | | callback | AsyncCallback<Array<[string, number]>> | 是 | 回调函数,返回删除备份的文件名及其处理结果。 | @@ -4072,7 +4072,7 @@ deleteBackup(files:Array<string>): Promise<Array<[string, number]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------- | ---- | ------------------------------------------------------------ | | files | Array<string> | 是 | 删除备份文件所指定的名称,不能为空且长度不大于[MAX_KEY_LENGTH](#constants)。 | @@ -4108,7 +4108,7 @@ startTransaction(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -4147,7 +4147,7 @@ try { }); kvStore.startTransaction(async function (err, data) { if (err != undefined) { - console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); return; } console.log('Succeeded in starting Transaction'); @@ -4155,7 +4155,7 @@ try { console.log(`entries: ${entries}`); kvStore.putBatch(entries, async function (err, data) { if (err != undefined) { - console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); return; } console.log('Succeeded in putting Batch'); @@ -4218,7 +4218,7 @@ commit(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -4294,7 +4294,7 @@ rollback(callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -4370,7 +4370,7 @@ enableSync(enabled: boolean, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | --------------------------------------------------------- | | enabled | boolean | 是 | 设定是否开启同步,true表示开启同步,false表示不启用同步。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -4402,7 +4402,7 @@ enableSync(enabled: boolean): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------- | -------- | ---- | --------------------------------------------------------- | | enabled | boolean | 是 | 设定是否开启同步,true表示开启同步,false表示不启用同步。 | @@ -4437,7 +4437,7 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: Asy **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------------- | ------------------------- | ---- | -------------------------------- | | localLabels | string[] | 是 | 表示本地设备的同步标签。 | | remoteSupportLabels | string[] | 是 | 表示要同步数据的设备的同步标签。 | @@ -4472,7 +4472,7 @@ setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<v **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------------- | -------- | ---- | -------------------------------- | | localLabels | string[] | 是 | 表示本地设备的同步标签。 | | remoteSupportLabels | string[] | 是 | 表示要同步数据的设备的同步标签。 | @@ -4510,7 +4510,7 @@ setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>) **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------------------- | ------------------------- | ---- | -------------------------------------------- | | defaultAllowedDelayMs | number | 是 | 表示数据库同步允许的默认延迟,以毫秒为单位。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | @@ -4543,7 +4543,7 @@ setSyncParam(defaultAllowedDelayMs: number): Promise<void> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------------------- | -------- | ---- | -------------------------------------------- | | defaultAllowedDelayMs | number | 是 | 表示数据库同步允许的默认延迟,以毫秒为单位。 | @@ -4581,7 +4581,7 @@ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------------------------- | | deviceIds | string[] | 是 | 同一组网环境下,需要同步的设备的deviceId列表。 | | mode | [SyncMode](#syncmode) | 是 | 同步模式。 | @@ -4619,7 +4619,7 @@ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------- | ---- | ---------------------------------------------- | | deviceIds | string[] | 是 | 同一组网环境下,需要同步的设备的deviceId列表。 | | mode | [SyncMode](#syncmode) | 是 | 同步模式。 | @@ -4673,7 +4673,7 @@ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotific **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | | event | string | 是 | 订阅的事件名,固定为'dataChange',表示数据变更事件。 | | type | [SubscribeType](#subscribetype) | 是 | 表示订阅的类型。 | @@ -4711,7 +4711,7 @@ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | | event | string | 是 | 订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback | Callback<Array<[string, number]>> | 是 | 回调函数。用于向调用方发送同步结果的回调。 | @@ -4746,7 +4746,7 @@ off(event:'dataChange', listener?: Callback<ChangeNotification>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | | event | string | 是 | 取消订阅的事件名,固定为'dataChange',表示数据变更事件。 | | listener | Callback<[ChangeNotification](#changenotification)> | 否 | 回调函数。 | @@ -4800,7 +4800,7 @@ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | | event | string | 是 | 取消订阅的事件名,固定为'syncComplete',表示同步完成事件。 | | syncCallback | Callback<Array<[string, number]>> | 否 | 回调函数。用于向调用方发送同步结果的回调。 | @@ -4846,7 +4846,7 @@ getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------------- | ---- | -------------------------------- | | callback | AsyncCallback<[SecurityLevel](#securitylevel)> | 是 | 回调函数。返回数据库的安全级别。 | @@ -4932,7 +4932,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|num **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | deviceId |string | 是 |标识要查询其数据的设备。 | | key |string | 是 |表示要查询key值的键。 | @@ -4984,7 +4984,7 @@ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | ---- | ------------------------ | | deviceId | string | 是 | 标识要查询其数据的设备。 | | key | string | 是 | 表示要查询key值的键。 | @@ -5020,7 +5020,7 @@ try { console.error(`Fail to get.code is ${err.code},message is ${err.message}`); }); }).catch((error) => { - console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + console.error(`Fail to put.code is ${error.code},message is ${error.message}`); }); } catch (e) { console.error(`Fail to get.code is ${e.code},message is ${e.message}`); @@ -5037,7 +5037,7 @@ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------------------------------------- | ---- | ---------------------------------------------- | | deviceId | string | 是 | 标识要查询其数据的设备。 | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -5101,7 +5101,7 @@ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ------------------------ | | deviceId | string | 是 | 标识要查询其数据的设备。 | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -5168,7 +5168,7 @@ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------------------- | ---- | ------------------------------------------------------- | | deviceId | string | 是 | 键值对所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | @@ -5238,7 +5238,7 @@ getEntries(deviceId: string, query: Query): Promise<Entry[]> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | -------------------- | | deviceId | string | 是 | 键值对所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | @@ -5293,7 +5293,7 @@ try { }); console.log('Succeeded in getting entries'); } catch (e) { - console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); } ``` @@ -5307,7 +5307,7 @@ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVS **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | 是 | 标识要查询其数据的设备。 | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -5358,7 +5358,7 @@ getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet&g **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | --------- | -------- | ---- | ------------------------ | | deviceId | string | 是 | 标识要查询其数据的设备。 | | keyPrefix | string | 是 | 表示要匹配的键前缀。 | @@ -5410,7 +5410,7 @@ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreR **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | @@ -5482,7 +5482,7 @@ getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | @@ -5558,7 +5558,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | 是 | 标识要查询其数据的设备。 | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | @@ -5615,7 +5615,7 @@ getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicat **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | deviceId | string | 是 | 标识要查询其数据的设备。 | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | 指示筛选条件,当此参数为null时,应定义处理逻辑。 | @@ -5670,7 +5670,7 @@ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number& **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------------------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | @@ -5734,7 +5734,7 @@ getResultSize(deviceId: string, query: Query): Promise<number> **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | +| 参数名 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------- | | deviceId | string | 是 | KVStoreResultSet对象所属的设备ID。 | | query | [Query](query) | 是 | 表示查询对象。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-effectKit.md b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md index b6384526fa5648a24780890d5a8aaed46283f458..37e09247632690faf9128bcbfc2cc558dd897427 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-effectKit.md +++ b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md @@ -4,7 +4,7 @@ 该模块提供以下图像效果相关的常用功能: -- [Filter](#filter):效果链,指各种图像处理效果的集合链表。 +- [Filter](#filter):效果类,用于添加指定效果到图像源。 - [Color](#color):颜色类,用于保存取色的结果。 - [ColorPicker](#colorpicker):智能取色器。 @@ -43,7 +43,6 @@ createEffect(source: image.PixelMap): Filter import image from "@ohos.multimedia.image"; const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts).then((pixelMap) => { let headFilter = effectKit.createEffect(pixelMap); @@ -76,7 +75,6 @@ createColorPicker(source: image.PixelMap): Promise\ import image from "@ohos.multimedia.image"; const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts).then((pixelMap) => { effectKit.createColorPicker(pixelMap).then(colorPicker => { @@ -106,7 +104,6 @@ createColorPicker(source: image.PixelMap, callback: AsyncCallback\) import image from "@ohos.multimedia.image"; const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts).then((pixelMap) => { effectKit.createColorPicker(pixelMap, (error, colorPicker) => { @@ -181,6 +178,7 @@ getMainColorSync(): Color let color = colorPicker.getMainColorSync(); console.log('get main color =' + color); ``` +![zh-ch_image_Main_Color.png](figures/zh-ch_image_Main_Color.png) ## Filter @@ -204,7 +202,7 @@ blur(radius: number): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -221,6 +219,7 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Blur.png](figures/zh-ch_image_Add_Blur.png) ### brightness @@ -240,7 +239,7 @@ brightness(bright: number): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -257,6 +256,7 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Brightness.png](figures/zh-ch_image_Add_Brightness.png) ### grayscale @@ -270,7 +270,7 @@ grayscale(): Filter | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [Filter](#filter) | 返回效果链表头。 | +| [Filter](#filter) | 返回已添加的图像效果。 | **示例:** @@ -286,10 +286,11 @@ image.createPixelMap(color, opts).then((pixelMap) => { } }) ``` +![zh-ch_image_Add_Grayscale.png](figures/zh-ch_image_Add_Grayscale.png) ### getPixelMap -getPixelMap(): image.PixelMap +getPixelMap(): [image.PixelMap](js-apis-image.md#pixelmap7) 获取已添加链表效果的源图像的image.PixelMap。 @@ -299,7 +300,7 @@ getPixelMap(): image.PixelMap | 类型 | 说明 | | :------------- | :---------------------------------------------- | -| [image.PixelMap](js-apis-image.md#pixelmap7) | 已添加链表效果的源图像的image.PixelMap。 | +| [image.PixelMap](js-apis-image.md#pixelmap7) | 已添加效果的源图像的image.PixelMap。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 6b86a4f7826a6b00b69b241a3ccfdb261488d7b6..c8ce2f7ab0ef05b63ab5739e411886bd7482acb9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -35,7 +35,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callba **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | --------------------------------------------------------------- | @@ -87,7 +87,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | --------------------------------------------------------------- | @@ -144,7 +144,7 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | --------------------------------------------------------------- | @@ -190,7 +190,7 @@ disableAdmin(admin: Want, callback: AsyncCallback\): void **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -234,7 +234,7 @@ disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -283,7 +283,7 @@ disableAdmin(admin: Want, userId?: number): Promise\ **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -322,7 +322,7 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -367,7 +367,7 @@ disableSuperAdmin(bundleName: String): Promise\ **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -401,7 +401,7 @@ isAdminEnabled(admin: Want, callback: AsyncCallback\): void **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------------------- | @@ -573,7 +573,7 @@ getDeviceSettingsManager(callback: AsyncCallback<DeviceSettingsManager>): **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ---------------------------------------------------------------------------- | @@ -616,7 +616,7 @@ getDeviceSettingsManager(): Promise<DeviceSettingsManager> **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ---------------------------------------------------------------------------- | @@ -661,7 +661,7 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCa **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------- | @@ -714,7 +714,7 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\; **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------- | @@ -755,7 +755,7 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------- | @@ -802,7 +802,7 @@ getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ----------------------------------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md b/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md index e2629ee19d504edbfedc91525641bd4ec0487fcf..ef00fbbcea9afc1bd9223fe0900b271b61c7b303 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @@ -44,7 +44,7 @@ setDateTime(admin: Want, time: number, callback: AsyncCallback\): void **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ---------------------------------------------------------------------------- | @@ -100,7 +100,7 @@ setDateTime(admin: Want, time: number): Promise\ **错误码**: -以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-EnterpriseDeviceManager.md) +以下的错误码的详细介绍请参见[企业设备管理错误码](../errorcodes/errorcode-enterpriseDeviceManager.md) | 类型 | 说明 | | ------- | ---------------------------------------------------------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-extension-context.md index 1425107f97c162746ce4d71025124660ee2c131d..aab5d3f7ffefbbb3a778e2150d92cbd2c069c525 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-extension-context.md @@ -31,7 +31,7 @@ ExtensionContext主要用于查询所属Extension的信息、Module的配置信 三个Module内都定义一个相同名称的ServiceExtension: ``` js -import ServiceExtension from '@ohos.application.ServiceExtensionAbility' +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' import Want from '@ohos.application.Want' export default class TheServiceExtension extends ServiceExtension { onCreate(want:Want) { @@ -61,7 +61,7 @@ export default class TheServiceExtension extends ServiceExtension { 在entry的MainAbility的onCreate回调内启动ServiceExtension ``` js -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.app.ability.Ability' export default class MainAbility extends Ability { onCreate(want, launchParam) { console.log("[Demo] MainAbility onCreate"); diff --git a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md index 5d131e1dfcab25145571f4b9b41e615965c969d2..c835160acbbd11c07a24985a49fb4887d67690e9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @@ -52,6 +52,9 @@ featureAbility.startAbility( uri: "" }, }, + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } ); ``` @@ -268,6 +271,9 @@ featureAbility.terminateSelfWithResult( } }, }, + (err) => { + console.info("err: " + JSON.stringify(err)) + } ); ``` @@ -345,7 +351,11 @@ hasWindowFocus(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.hasWindowFocus() +featureAbility.hasWindowFocus( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.hasWindowFocus7+ @@ -389,7 +399,11 @@ getWant(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.getWant() +featureAbility.getWant( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.getWant @@ -455,7 +469,11 @@ terminateSelf(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; -featureAbility.terminateSelf() +featureAbility.terminateSelf( + (err) => { + console.info("err: " + JSON.stringify(err)) + } +) ``` ## featureAbility.terminateSelf7+ @@ -583,8 +601,8 @@ var connId = featureAbility.connectAbility( }, ); var result = featureAbility.disconnectAbility(connId, - (error,data) => { - console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code + " data: " + data) + (error) => { + console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code) }, ); ``` @@ -660,7 +678,11 @@ getWindow(callback: AsyncCallback\): void **示例:** ```javascript -featureAbility.getWindow() +featureAbility.getWindow( + (err, data) => { + console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + } +) ``` ## featureAbility.getWindow7+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileio.md b/zh-cn/application-dev/reference/apis/js-apis-fileio.md index 9ba948beaccf86693e6d13fe257ab5554212659b..148d48c848561526ac5cb3e16f1dbf167ba910e3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -250,7 +250,7 @@ access(path: string, mode?: number): Promise<void> ## fileio.access -access(path: string, mode: number, callback: AsyncCallback<void>): void +access(path: string, mode?: number, callback: AsyncCallback<void>): void 检查当前进程是否可访问某文件,使用callback异步回调。 @@ -395,8 +395,8 @@ copyFile(src: string | number, dest: string | number, mode?: number): Promise< | 参数名 | 类型 | 必填 | 说明 | | ---- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | - | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | + | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | + | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。
0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | **返回值:** @@ -430,8 +430,8 @@ copyFile(src: string | number, dest: string | number, mode: number, callback: As | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | - | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | + | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | + | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。
0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | @@ -458,8 +458,8 @@ copyFileSync(src: string | number, dest: string | number, mode?: number): void | 参数名 | 类型 | 必填 | 说明 | | ---- | -------------------------- | ---- | ---------------------------------------- | - | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | - | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | + | src | string \| number | 是 | 待复制文件的路径或待复制文件的描述符。 | + | dest | string \| number | 是 | 目标文件路径或目标文件描述符。 | | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。
0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | **示例:** @@ -602,7 +602,7 @@ open(path: string, flags: number, mode: number, callback: AsyncCallback<numbe | path | string | 是 | 待打开文件的应用沙箱路径。 | | flags | number | 否 | 打开文件的选项,必须指定如下选项中的一个,默认以只读方式打开:
- 0o0:只读打开。
- 0o1:只写打开。
- 0o2:读写打开。
同时,也可给定如下选项,以按位或的方式追加,默认不给定任何额外选项:
- 0o100:若文件不存在,则创建文件。使用该选项时必须指定第三个参数 mode。
- 0o200:如果追加了0o100选项,且文件已经存在,则出错。
- 0o1000:如果文件存在且以只写或读写的方式打开文件,则将其长度裁剪为零。
- 0o2000:以追加方式打开,后续写将追加到文件末尾。
- 0o4000:如果path指向FIFO、块特殊文件或字符特殊文件,则本次打开及后续 IO 进行非阻塞操作。
- 0o200000:如果path不指向目录,则出错。
- 0o400000:如果path指向符号链接,则出错。
- 0o4010000:以同步IO的方式打开文件。 | | mode | number | 否 | 若创建文件,则指定文件的权限,可给定如下权限,以按位或的方式追加权限,默认给定0o666。
- 0o666:所有者具有读、写权限,所有用户组具有读、写权限,其余用户具有读、写权限。
- 0o700:所有者具有读、写及可执行权限。
- 0o400:所有者具有读权限。
- 0o200:所有者具有写权限。
- 0o100:所有者具有可执行权限。
- 0o070:所有用户组具有读、写及可执行权限。
- 0o040:所有用户组具有读权限。
- 0o020:所有用户组具有写权限。
- 0o010:所有用户组具有可执行权限。
- 0o007:其余用户具有读、写及可执行权限。
- 0o004:其余用户具有读权限。
- 0o002:其余用户具有写权限。
- 0o001:其余用户具有可执行权限。 | -| callback | AsyncCallback <void> | 是 | 异步打开文件之后的回调。 | +| callback | AsyncCallback <number> | 是 | 异步打开文件之后的回调。 | **示例:** @@ -991,7 +991,7 @@ writeSync(fd: number, buffer: ArrayBuffer | string, options?: { offset?: number; | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | 是 | 待写入文件的文件描述符。 | - | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | + | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | | options | Object | 否 | 支持如下选项:
- offset,number类型,表示期望写入数据的位置相对于数据首地址的偏移。可选,默认为0。
- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度减去偏移长度。
- position,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。
约束:offset+length<=buffer.size。 | **返回值:** @@ -1525,7 +1525,7 @@ lstat(path: string): Promise<Stat> ```js let filePath = pathDir + "/test.txt"; fileio.lstat(filePath).then(function(stat){ - console.info("get link status succeed, " + the size of file is + stat.size); + console.info("get link status succeed, the size of file is" + stat.size); }).catch(function(err){ console.info("get link status failed with error:"+ err); }); @@ -1598,7 +1598,7 @@ rename(oldPath: string, newPath: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | 是 | 目标文件的当前应用沙箱路径。 | -| newPath | String | 是 | 目标文件的新应用沙箱路径。 | +| newPath | string | 是 | 目标文件的新应用沙箱路径。 | **返回值:** @@ -1632,8 +1632,8 @@ rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------------------- | | oldPath | string | 是 | 目标文件的当前应用沙箱路径。 | -| newPath | String | 是 | 目标文件的新应用沙箱路径。 | -| Callback | AsyncCallback<void> | 是 | 异步重命名文件之后的回调。 | +| newPath | string | 是 | 目标文件的新应用沙箱路径。 | +| callback | AsyncCallback<void> | 是 | 异步重命名文件之后的回调。 | **示例:** @@ -1658,7 +1658,7 @@ renameSync(oldPath: string, newPath: string): void | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---------------------------- | | oldPath | string | 是 | 目标文件的当前应用沙箱路径。 | -| newPath | String | 是 | 目标文件的新应用沙箱路径。 | +| newPath | string | 是 | 目标文件的新应用沙箱路径。 | **示例:** @@ -1797,7 +1797,7 @@ fdatasync(fd: number, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ----------------- | | fd | number | 是 | 待同步文件的文件描述符。 | - | callback | AsyncCallback <void> | 是 | 异步将文件内容数据同步之后的回调。 | + | callback | AsyncCallback<void> | 是 | 异步将文件内容数据同步之后的回调。 | **示例:** @@ -2137,7 +2137,7 @@ fchmod(fd: number, mode: number, callback: AsyncCallback<void>): void | -------- | ------------------------------- | ---- | ---------------------------------------- | | fd | number | 是 | 待改变文件的文件描述符。 | | mode | number | 是 | 若创建文件,则指定文件的权限,可给定如下权限,以按位或的方式追加权限。
- 0o700:所有者具有读、写及可执行权限。
- 0o400:所有者具有读权限。
- 0o200:所有者具有写权限。
- 0o100:所有者具有可执行权限。
- 0o070:所有用户组具有读、写及可执行权限。
- 0o040:所有用户组具有读权限。
- 0o020:所有用户组具有写权限。
- 0o010:所有用户组具有可执行权限。
- 0o007:其余用户具有读、写及可执行权限。
- 0o004:其余用户具有读权限。
- 0o002:其余用户具有写权限。
- 0o001:其余用户具有可执行权限。 | - | callback | AsyncCallback <void> | 是 | 异步改变文件权限之后的回调。 | + | callback | AsyncCallback<void> | 是 | 异步改变文件权限之后的回调。 | **示例:** @@ -2312,7 +2312,7 @@ fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): v | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | fd | number | 是 | 待打开文件的文件描述符。 | | mode | string | 是 | - r:打开只读文件,该文件必须存在。
- r+:打开可读写的文件,该文件必须存在。
- w:打开只写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。
- w+:打开可读写文件,若文件存在则文件长度清0,即该文件内容会消失。若文件不存在则建立该文件。
- a:以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
- a+:以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。 | - | callback | AsyncCallback <[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | + | callback | AsyncCallback<[Stream](#stream)> | 是 | 异步打开文件流之后的回调。 | **示例:** @@ -2547,8 +2547,8 @@ createWatcher(filename: string, events: number, callback: AsyncCallback<numbe | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | 是 | 待监视文件的应用沙箱路径。 | -| events | Number | 是 | - 1: 监听文件或者目录是否发生重命名。
- 2:监听文件或者目录内容的是否修改。
- 3:两者都有。 | -| callback | AsyncCallback<number > | 是 | 每发生变化一次,调用一次此函数。 | +| events | number | 是 | - 1: 监听文件或者目录是否发生重命名。
- 2:监听文件或者目录内容的是否修改。
- 3:两者都有。 | +| callback | AsyncCallback<number> | 是 | 每发生变化一次,调用一次此函数。 | **返回值:** @@ -2573,7 +2573,7 @@ createWatcher(filename: string, events: number, callback: AsyncCallback<numbe **系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.File.FileIO。 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ---------- | ---- | ---- | ----------------- | | bytesRead | number | 是 | 是 | 实际读取长度。 | | offset | number | 是 | 是 | 读取数据相对于缓冲区首地址的偏移。 | @@ -2588,7 +2588,7 @@ createWatcher(filename: string, events: number, callback: AsyncCallback<numbe ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ------ | ------ | ---- | ---- | ---------------------------------------- | | dev | number | 是 | 否 | 标识包含该文件的主设备号。 | | ino | number | 是 | 否 | 标识该文件。通常同设备上的不同文件的INO不同。 | @@ -2966,7 +2966,7 @@ write(buffer: ArrayBuffer | string, options?: { offset?: number; length?: number | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ---------------------------------------- | - | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | + | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | | options | Object | 否 | 支持如下选项:
- offset,number类型,表示期望写入数据的位置相对于数据首地址的偏移。可选,默认为0。
- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度减去偏移长度。
- position,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。
约束:offset+length<=buffer.size。 | **返回值:** @@ -3000,7 +3000,7 @@ write(buffer: ArrayBuffer | string, options: { offset?: number; length?: number; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | - | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | + | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | | options | Object | 否 | 支持如下选项:
- offset,number类型,表示期望写入数据的位置相对于数据首地址的偏移。可选,默认为0。
- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度减去偏移长度。
- position,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。
约束:offset+length<=buffer.size。 | | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | @@ -3030,7 +3030,7 @@ writeSync(buffer: ArrayBuffer | string, options?: { offset?: number; length?: nu | 参数名 | 类型 | 必填 | 说明 | | ------- | ------------------------------- | ---- | ---------------------------------------- | - | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | + | buffer | ArrayBuffer \| string | 是 | 待写入文件的数据,可来自缓冲区或字符串。 | | options | Object | 否 | 支持如下选项:
- offset,number类型,表示期望写入数据的位置相对于数据首地址的偏移。可选,默认为0。
- length,number类型,表示期望写入数据的长度。可选,默认缓冲区长度减去偏移长度。
- position,number类型,表示期望写入文件的位置。可选,默认从当前位置开始写。
- encoding,string类型,当数据是string类型时有效,表示数据的编码方式,默认 'utf-8'。仅支持 'utf-8'。
约束:offset+length<=buffer.size。 | **返回值:** @@ -3277,7 +3277,7 @@ closeSync(): void ### 属性 -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ---- | ------ | ---- | ---- | ------- | | name | string | 是 | 否 | 目录项的名称。 | @@ -3443,7 +3443,7 @@ isSymbolicLink(): boolean 文件过滤器配置项。 -| 名称 | 参数类型 | 说明 | +| 名称 | 类型 | 说明 | | ----------- | --------------- | ------------------ | | suffix | Array<string> | 文件后缀名,各个关键词OR关系。 | | displayName | Array<string> | 文件名模糊匹配,各个关键词OR关系。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-freeInstall.md b/zh-cn/application-dev/reference/apis/js-apis-freeInstall.md new file mode 100644 index 0000000000000000000000000000000000000000..0458f5fa83756906051b9e19ffaa281b851396cd --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @@ -0,0 +1,450 @@ +# Bundle.freeInstall模块(JS端SDK接口) + +本模块提供免安装相关的设置和查询能力,支持BundlePackInfo、DispatchInfo等信息的查询 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## 导入模块 + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +``` + +## 权限列表 + +| 权限 | 权限等级 | 描述 | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 | +| ohos.permission.INSTALL_BUNDLE | system_core | 可安装、卸载应用 | + +权限等级参考[权限等级说明](../../security/accesstoken-overview.md#权限等级说明)。 +## UpgradeFlag + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +| 名称 | 值 | 说明 | +| ----------------------------- | ---- | ---------------- | +| NOT_UPGRADE | 0 | 模块无需升级 | +| SINGLE_UPGRADE | 1 | 单个模块需要升级 | +| RELATION_UPGRADE | 2 | 关系模块需要升级 | + +## BundlePackFlag + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +| 名称 | 值 | 说明 | +| ------------------ | ---------- | ---------------------------------- | +| GET_PACK_INFO_ALL | 0x00000000 | 获取应用包pack.info的所有信息。 | +| GET_PACKAGES | 0x00000001 | 获取应用包pack.info的package信息。 | +| GET_BUNDLE_SUMMARY | 0x00000002 | 获取应用包pack.info的bundle摘要信息。 | +| GET_MODULE_SUMMARY | 0x00000004 | 获取应用包pack.info的module摘要信息。 | + +## freeInstall.setHapModuleUpgradeFlag + +setHapModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag, callback: AsyncCallback\):void; + +设置指定模块是否升级。使用callback异步回调。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | --------------------------- | ---- | ---------------------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| moduleName | string | 是 | 应用程序模块名称。 | +| upgradeFlag | [UpgradeFlag](#upgradeflag) | 是 | 仅供内部系统使用标志位 | +| callback | AsyncCallback\ | 是 | 回调函数。当函数调用成功,err为null,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700002 | The specified module name is not found. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let upgradeFlag = freeInstall.UpgradeFlag.SINGLE_UPGRADE; +try { + freeInstall.setHapModuleUpgradeFlag(bundleName, moduleName, upgradeFlag, err => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed'); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## setHapModuleUpgradeFlag + +setHapModuleUpgradeFlag(bundleName: string, moduleName: string, upgradeFlag: UpgradeFlag): Promise\; + +设置指定模块是否升级。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | --------------------------- | ---- | ---------------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| moduleName | string | 是 | 应用程序模块名称。 | +| upgradeFlag | [UpgradeFlag](#upgradeflag) | 是 | 仅供内部系统使用标志位 | + +**返回值:** + +| 类型 | 说明 | +| ------------- | ------------------------------------ | +| Promise\ | Promise对象。无返回结果的Promise对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700002 | The specified module name is not found. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +let upgradeFlag = freeInstall.UpgradeFlag.SINGLE_UPGRADE; +try { + freeInstall.setHapModuleUpgradeFlag(bundleName, moduleName, upgradeFlag).then(() => { + console.info('Operation succeed') + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## isHapModuleRemovable + +isHapModuleRemovable(bundleName: string, moduleName: string, callback: AsyncCallback\): void; + +查询指定模块是否可以被移除。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ---------------------- | ---- | --------------------------------------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| moduleName | string | 是 | 应用程序模块名称。 | +| callback | AsyncCallback\ | 是 | 回调函数。返回true表示可以移除;返回false表示不可移除。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700002 | The specified module name is not found. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +try { + freeInstall.isHapModuleRemovable(bundleName, moduleName, (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## isHapModuleRemovable + +isHapModuleRemovable(bundleName: string, moduleName: string): Promise\; + +查询指定模块是否可以被移除。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | ------------------ | +| bundleName | string | 是 | 应用程序包名称。 | +| moduleName | string | 是 | 应用程序模块名称。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ---------------------------- | +| Promise\ | Promise对象。返回true表示可以移除;返回false表示不可移除。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700002 | The specified module name is not found. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let moduleName = 'entry'; +try { + freeInstall.isHapModuleRemovable(bundleName, moduleName).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## getBundlePackInfo + +getBundlePackInfo(bundleName: string, bundlePackFlag : BundlePackFlag, callback: AsyncCallback\): void; + +基于bundleName和bundlePackFlag来获取bundlePackInfo。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | 是 | 指示要查询的应用包标志 | +| callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | 是 | 回调函数。当函数调用成功,err为null,data为获取到的BundlePackInfo信息。否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let bundlePackFlag = freeInstall.BundlePackFlag.GET_PACK_INFO_ALL; +try { + freeInstall.getBundlePackInfo(bundleName, bundlePackFlag, (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` +## getBundlePackInfo + +getBundlePackInfo(bundleName: string, bundlePackFlag : BundlePackFlag): Promise\; + +基于bundleName和bundleFlag来获取bundlePackInfo。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------------- | ------------------------------------------------- | ---- | ---------------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | 是 | 指示要查询的应用包标志 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------------------------- | ----------------------------------- | +| Promise<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | Promise对象,返回BundlePackInfo信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +let bundleName = 'com.example.myapplication'; +let bundlePackFlag = freeInstall.BundlePackFlag.GET_PACK_INFO_ALL; +try { + freeInstall.getBundlePackInfo(bundleName, bundlePackFlag).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## getDispatchInfo + +getDispatchInfo(callback: AsyncCallback\): void; + +获取有关dispatch版本的信息。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)> | 是 | 回调函数。当函数调用成功,err为null,data为获取到的[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)信息。否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 801 | Capability not supported. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +try { + freeInstall.getDispatchInfo((err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## getDispatchInfo + +getDispatchInfo(): Promise\; + +获取有关dispatch版本的信息。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.BundleFramework.FreeInstall + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)> | Promise对象,返回[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 801 | Capability not supported. | + +**示例:** + +```js +import freeInstall from '@ohos.bundle.freeInstall'; +try { + freeInstall.getDispatchInfo().then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md index b0e51a6b414bbdb2b3d6f23ffd3559eae266f144..66036d7616f66140e56437efd6e19223c37a8a75 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -63,7 +63,7 @@ off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“countryCodeChange”,表示取消订阅国家码信息变化事件。 | - | callback | Callback<[CountryCode](#countrycode)> | 是 | 接收国家码信息上报。 | + | callback | Callback<[CountryCode](#countrycode)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **错误码**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md index ab2399b1884ecb3a015e2c25794c485b284d7260..65d6de9a6f3f800065adbe2710544189b69d9c16 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-geolocation.md +++ b/zh-cn/application-dev/reference/apis/js-apis-geolocation.md @@ -59,7 +59,7 @@ off(type: 'locationChange', callback?: Callback<Location>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationChange”,表示位置变化。 | - | callback | Callback<[Location](#location)> | 否 | 接收位置变化状态变化监听。 | + | callback | Callback<[Location](#location)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** @@ -119,7 +119,7 @@ off(type: 'locationServiceState', callback?: Callback<boolean>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“locationServiceState”,表示位置服务状态。 | - | callback | Callback<boolean> | 否 | 接收位置服务状态变化监听。 | + | callback | Callback<boolean> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** @@ -180,7 +180,7 @@ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Locati | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“cachedGnssLocationsReporting”,表示GNSS缓存定位结果上报。 | - | callback | Callback<boolean> | 否 | 接收GNSS缓存位置上报。 | + | callback | Callback<boolean> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** @@ -240,7 +240,7 @@ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“gnssStatusChange”,表示订阅GNSS卫星状态信息上报。 | - | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 否 | 接收GNSS卫星状态信息上报。 | + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** @@ -298,7 +298,7 @@ off(type: 'nmeaMessageChange', callback?: Callback<string>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | type | string | 是 | 设置事件类型。type为“nmeaMessageChange”,表示订阅GNSS NMEA信息上报。 | - | callback | Callback<string> | 否 | 接收GNSS NMEA信息上报。 | + | callback | Callback<string> | 否 | 需要取消订阅的回调函数。若无此参数,则取消当前类型的所有订阅。 | **示例** @@ -1076,7 +1076,7 @@ flushCachedGnssLocations(): Promise<boolean>; sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; -给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 +给位置服务子系统的各个部件发送扩展命令。 **需要权限**:ohos.permission.LOCATION @@ -1109,7 +1109,7 @@ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): v sendCommand(command: LocationCommand): Promise<boolean>; -给位置服务子系统的各个部件发送扩展命令。只有系统应用才能调用。 +给位置服务子系统的各个部件发送扩展命令。 **需要权限**:ohos.permission.LOCATION diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md index 2aacdc18fe767d767b1323153f1446f560bb2f92..5e58073b79314e40bef7036dd829b2a51a738bc2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -88,7 +88,7 @@ isEmpty(): boolean const hashMap = new HashMap(); let result = hashMap.isEmpty(); try { - hashMap.isEmpty.bind({})(); + hashMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -131,7 +131,7 @@ let result = hashMap.hasKey("squirrel"); hashMap.set("squirrel", 123); let result1 = hashMap.hasKey("squirrel"); try { - hashMap.hasKey.bind({}, "squirrel")(); + hashMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -174,7 +174,7 @@ let result = hashMap.hasValue(123); hashMap.set("squirrel", 123); let result1 = hashMap.hasValue(123); try { - hashMap.hasValue.bind({}, 123)(); + hashMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -217,7 +217,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); try { - hashMap.get.bind({}, "sparrow")(); + hashMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -255,7 +255,7 @@ hashMap.set("sparrow", 356); let newHashMap = new HashMap(); hashMap.setAll(newHashMap); try { - hashMap.setAll.bind({}, newHashMap)(); + hashMap.setAll.bind({}, newHashMap)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -297,7 +297,7 @@ set(key: K, value: V): Object let hashMap = new HashMap(); let result = hashMap.set("squirrel", 123); try { - hashMap.set.bind({}, "squirrel", 123)(); + hashMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -340,7 +340,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); try { - hashMap.remove.bind({}, "sparrow")(); + hashMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -371,7 +371,7 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); try { - hashMap.clear.bind({})(); + hashMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -413,7 +413,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.keys.bind({})(); + hashMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -455,7 +455,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.values.bind({})(); + hashMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -498,7 +498,7 @@ let hashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); try { - hashMap.replace.bind({}, "sparrow", 357)(); + hashMap.replace.bind({}, "sparrow", 357)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -547,7 +547,7 @@ hashMap.forEach((value, key) => { try { hashMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -590,7 +590,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap.entries.bind({})(); + hashMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -640,7 +640,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashMap[Symbol.iterator].bind({})(); + hashMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md index df7dde4d3dbed6fd5cbd132bfe2ccd07ef0daeef..5a270cec3dc83316db1eadfd6642c18dfd7695ea 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hashset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -96,7 +96,7 @@ isEmpty(): boolean const hashSet = new HashSet(); let result = hashSet.isEmpty(); try { - hashSet.isEmpty.bind({})(); + hashSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -139,7 +139,7 @@ let result = hashSet.has("squirrel"); hashSet.add("squirrel"); let result1 = hashSet.has("squirrel"); try { - hashSet.has.bind({}, "squirrel")(); + hashSet.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ add(value: T): boolean let hashSet = new HashSet(); let result = hashSet.add("squirrel"); try { - hashSet.add.bind({}, "squirrel")(); + hashSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); try { - hashSet.remove.bind({}, "sparrow")(); + hashSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -254,7 +254,7 @@ hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); try { - hashSet.remove.bind({})(); + hashSet.remove.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -296,7 +296,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet.values.bind({})(); + hashSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -345,7 +345,7 @@ hashSet.forEach((value, key) => { try { hashSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -387,7 +387,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet.entries.bind({})(); + hashSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -436,7 +436,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - hashSet[Symbol.iterator].bind({})(); + hashSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-image.md b/zh-cn/application-dev/reference/apis/js-apis-image.md index c1cc2bf3cca7cc10f4a968c407348676b5ea62d4..32940b1ac22869c454f4a181ae66003d0cb4f0db 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-image.md +++ b/zh-cn/application-dev/reference/apis/js-apis-image.md @@ -1771,7 +1771,7 @@ createImageReceiver(width: number, height: number, format: number, capacity: num | -------- | ------ | ---- | ---------------------- | | width | number | 是 | 图像的默认宽度。 | | height | number | 是 | 图像的默认高度。 | -| format | number | 是 | 图像格式,取值为[ImageFormat](#imageformat9)常量。 | +| format | number | 是 | 图像格式,取值为[ImageFormat](#imageformat9)常量(目前该参数为使用者和camera约定的值,以后可能还有其他应用场景,receiver的作用只是传递,目前仅支持 ImageFormat:JPEG 格式)。 | | capacity | number | 是 | 同时访问的最大图像数。 | **返回值:** @@ -1783,7 +1783,7 @@ createImageReceiver(width: number, height: number, format: number, capacity: num **示例:** ```js -var receiver = image.createImageReceiver(8192, 8, 4, 8); +var receiver = image.createImageReceiver(8192, 8, 2000, 8); ``` ## ImageReceiver9+ diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md index 96022038df5110f77024b83733eec4c9e126267e..7f9be5cf41f311e7f897d28c913dc166b7a2585f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @@ -36,9 +36,10 @@ on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): v **示例:** ```js -let powerKeyCode = 18; +let leftAltKey = 2045; +let tabKey = 2049; try { - inputConsumer.on("key", {preKeys: [], finalKey: powerKeyCode, isFinalKeyDown: true, finalKeyDownDuration: 0}, keyOptions => { + inputConsumer.on("key", {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}, keyOptions => { console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); }); } catch (error) { @@ -66,27 +67,33 @@ off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): **示例:** ```js +let leftAltKey = 2045; +let tabKey = 2049; // 取消订阅单个回调函数 let callback = function (keyOptions) { console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); } -let keyOption = {preKeys: [], finalKey: powerKeyCode, isFinalKeyDown: true, finalKeyDownDuration: 0}; +let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}; try { inputConsumer.on("key", keyOption, callback); inputConsumer.off("key", keyOption, callback); + console.log(`Unsubscribe success`); } catch (error) { console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ```js +let leftAltKey = 2045; +let tabKey = 2049; // 取消订阅所有回调函数 let callback = function (keyOptions) { console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); } -let keyOption = {preKeys: [], finalKey: powerKeyCode, isFinalKeyDown: true, finalKeyDownDuration: 0}; +let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}; try { inputConsumer.on("key", keyOption, callback); inputConsumer.off("key", keyOption); + console.log(`Unsubscribe success`); } catch (error) { console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md b/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md index 5ddc299f650e5fed2f429f7cbd1458c3d9f552f3..6ad7b9bf7af1415ca104854ce87ef89165ba8b92 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @@ -194,19 +194,19 @@ off(type: "change", listener?: Callback<DeviceListener>): void **示例**: ```js -callback: function(data) { +function callback(data) { console.log(`Report device event info: ${JSON.stringify(data, [`type`, `deviceId`])}`); -} +}; try { - inputDevice.on("change", this.callback); + inputDevice.on("change", callback); } catch (error) { console.log(`Listen device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } // 取消指定的监听。 try { - inputDevice.off("change", this.callback); + inputDevice.off("change", callback); } catch (error) { console.log(`Cancel listening device event failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } @@ -334,19 +334,19 @@ inputDevice.getDeviceInfo(1).then((deviceData) => { ## inputDevice.supportKeys9+ -supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void +supportKeys(deviceId: number, keys: Array<KeyCode>, callback: AsyncCallback <Array<boolean>>): void -获取输入设备是否支持指定的键码值,使用Callback异步方式返回结果。 +获取输入设备是否支持指定的键码值,使用AsyncCallback异步方式返回结果。 **系统能力**:SystemCapability.MultimodalInput.Input.InputDevice **参数**: -| 参数 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | -| deviceId | number | 是 | 输入设备id,同一个物理设备反复插拔,设备id会发生变化。 | -| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | -| callback | Callback<Array<boolean>> | 是 | 回调函数,异步返回查询结果。 | +| 参数 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------ | +| deviceId | number | 是 | 输入设备id,同一个物理设备反复插拔,设备id会发生变化。 | +| keys | Array<KeyCode> | 是 | 需要查询的键码值,最多支持5个按键查询。 | +| callback | AsyncCallback<Array<boolean>> | 是 | 回调函数,异步返回查询结果。 | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md index df973465e5b7341c60de3740e757d320dc3feed7..1d964e6d0bab941d4127557c6da6f91cd1f65881 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputevent.md @@ -1,6 +1,6 @@ # 输入事件 -InputEvent模块描述了设备上报的基本事件。 +设备上报的基本事件。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -17,7 +17,7 @@ import InputEvent from '@ohos.multimodalInput.inputEvent'; | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ---------- | ------ | ---- | ---- | -------------- | -| id | number | 是 | 否 | 由服务端生成全局唯一事件id | +| id | number | 是 | 否 | 事件id | | deviceId | number | 是 | 否 | 上报输入事件的设备id | | actionTime | number | 是 | 否 | 输入事件的上报时间 | | screenId | number | 是 | 否 | 目标屏幕id | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md index 80d1a26688e276daea5ed1572764368ef93fb8ba..d23d842670d79d7b06a1b1a437ade4482354e299 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @@ -41,7 +41,7 @@ try { keyDownDuration: 0, isIntercepted: false } - inputEventClient.injectKeyEvent({ KeyEvent: backKeyDown }); + inputEventClient.injectEvent({ KeyEvent: backKeyDown }); let backKeyUp = { isPressed: false, @@ -49,7 +49,7 @@ try { keyDownDuration: 0, isIntercepted: false }; - inputEventClient.injectKeyEvent({ KeyEvent: backKeyUp }); + inputEventClient.injectEvent({ KeyEvent: backKeyUp }); } catch (error) { console.log(`Failed to inject KeyEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md index 1bef6711b741ed5a5f6987472f4989bd42adadc2..28b5c4a502ecd0348aab8a07507eda45a6ca4be9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @@ -8,7 +8,7 @@ ## 导入模块 -``` +```js import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; ``` @@ -30,9 +30,9 @@ Extension生命周期回调,在拉起Extension输入法应用时调用,执 **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------- | ---- | ------------------------------- | +| want | [Want](js-apis-application-Want.md) | 是 | 当前Extension相关的Want类型信息,包括ability名称、bundle名称等。 | **示例:** @@ -60,4 +60,4 @@ class InputMethodExt extends InputMethodExtensionAbility { console.log('onDestroy'); } } -``` +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md index ed798722aa3fa47dcbcd68cdb617499af6b4c9e4..eb51a3f69f6561557501f527ab8e3713dc9860b4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @@ -56,7 +56,7 @@ getController(): InputMethodController **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | ------------------------------ | @@ -84,7 +84,7 @@ getSetting(): InputMethodSetting **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -115,7 +115,7 @@ switchInputMethod(target: InputMethodProperty, callback: AsyncCallback<boolea **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -164,7 +164,7 @@ switchInputMethod(target: InputMethodProperty): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -228,7 +228,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -290,7 +290,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean& **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -366,7 +366,7 @@ switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inp **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -434,7 +434,7 @@ switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inp **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -541,7 +541,7 @@ stopInputSession(callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -584,7 +584,7 @@ stopInputSession(): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -627,7 +627,7 @@ showSoftKeyboard(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -664,7 +664,7 @@ showSoftKeyboard(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -699,7 +699,7 @@ hideSoftKeyboard(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -736,7 +736,7 @@ hideSoftKeyboard(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -884,7 +884,7 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: Async **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -934,7 +934,7 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty): Promise<Arr **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -976,7 +976,7 @@ listCurrentInputMethodSubtype(callback: AsyncCallback<Array<InputMethodSub **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -1015,7 +1015,7 @@ listCurrentInputMethodSubtype(): Promise<Array<InputMethodSubtype>> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -1053,7 +1053,7 @@ getInputMethods(enable: boolean, callback: AsyncCallback<Array<InputMethod **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -1092,7 +1092,7 @@ getInputMethods(enable: boolean): Promise<Array<InputMethodProperty>> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -1137,7 +1137,7 @@ showOptionalInputMethods(callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | @@ -1177,7 +1177,7 @@ showOptionalInputMethods(): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误信息 | | -------- | -------------------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md index 22162f11ff445162cbc62de1ced62955868ce8ec..58015a6314c03d84903ddd993d636189bf6995e0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -712,7 +712,7 @@ hide(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -746,7 +746,7 @@ hide(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -841,7 +841,7 @@ sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -889,7 +889,7 @@ sendKeyFunction(action:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -930,7 +930,7 @@ getForward(length:number, callback: AsyncCallback<string>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -976,7 +976,7 @@ getForward(length:number): Promise<string> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1015,7 +1015,7 @@ getBackward(length:number, callback: AsyncCallback<string>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1061,7 +1061,7 @@ getBackward(length:number): Promise<string> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1100,7 +1100,7 @@ deleteForward(length:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1150,7 +1150,7 @@ deleteForward(length:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1193,7 +1193,7 @@ deleteBackward(length:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1243,7 +1243,7 @@ deleteBackward(length:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1282,7 +1282,7 @@ insertText(text:string, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1327,7 +1327,7 @@ insertText(text:string): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1368,7 +1368,7 @@ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1403,7 +1403,7 @@ getEditorAttribute(): Promise<EditorAttribute> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1437,7 +1437,7 @@ moveCursor(direction: number, callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1481,7 +1481,7 @@ moveCursor(direction: number): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md index 06de18434c1f9fe4d721e5db79cd185dcebcd684..85716542e22921480952629fdc7d034f51f2ee1f 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @@ -96,13 +96,14 @@ off(type: "touch", receiver?: TouchEventReceiver): void ```js // 取消监听单个回调函数 -callback: function(touchEvent) { +function callback(touchEvent) { console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); return false; -}, +}; try { - inputMonitor.on("touch", this.callback); - inputMonitor.off("touch", this.callback); + inputMonitor.on("touch", callback); + inputMonitor.off("touch", callback); + console.log(`Monitor off success`); } catch (error) { console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } @@ -110,13 +111,14 @@ try { ```js // 取消监听所有回调函数 -callback: function(touchEvent) { +function callback(touchEvent) { console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); return false; -}, +}; try { - inputMonitor.on("touch", this.callback); + inputMonitor.on("touch", callback); inputMonitor.off("touch"); + console.log(`Monitor off success`); } catch (error) { console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } @@ -141,12 +143,14 @@ off(type: "mouse", receiver?: Callback<MouseEvent>): void ```js // 取消监听单个回调函数 -callback: function(mouseEvent) { +function callback(mouseEvent) { console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); -}, + return false; +}; try { - inputMonitor.on("mouse", this.callback); - inputMonitor.off("mouse", this.callback); + inputMonitor.on("mouse", callback); + inputMonitor.off("mouse", callback); + console.log(`Monitor off success`); } catch (error) { console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } @@ -154,12 +158,14 @@ try { ```js // 取消监听所有回调函数 -callback: function(mouseEvent) { +function callback(mouseEvent) { console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); -}, + return false; +}; try { - inputMonitor.on("mouse", this.callback); + inputMonitor.on("mouse", callback); inputMonitor.off("mouse"); + console.log(`Monitor off success`); } catch (error) { console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } @@ -188,7 +194,7 @@ try { ```js try { inputMonitor.on("touch", touchEvent => { - if (touchEvent.touches.size() == 3) { // 当前有三个手指按下 + if (touchEvent.touches.length == 3) { // 当前有三个手指按下 return true; } else { return false; diff --git a/zh-cn/application-dev/reference/apis/js-apis-installer.md b/zh-cn/application-dev/reference/apis/js-apis-installer.md new file mode 100644 index 0000000000000000000000000000000000000000..6614d02e8d7abb3f833dab287e901e567e164c70 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-installer.md @@ -0,0 +1,299 @@ +# BundleInstaller + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +在设备上安装、升级和卸载应用 + +## 导入模块 + +```js +import installer from '@ohos.bundle.installer'; +``` + +## 权限列表 + +| 权限 | 权限等级 | 描述 | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.INSTALL_BUNDLE | system_core | 可安装、卸载应用 | + +权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) + +## BundleInstaller.getBundleInstaller + +getBundleInstaller(callback: AsyncCallback\): void; + +获取BundleInstaller对象,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | 是 | 回调函数,获取BundleInstaller对象,err为undefined,data为获取到的BundleInstaller对象;否则为错误对象 | + +**错误码:** + +错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; + +try { + installer.getBundleInstaller((err, data) => { + if (err) { + console.error('getBundleInstaller failed:' + err.message); + } else { + console.info('getBundleInstaller successfully'); + } + }); +} catch (error) { + console.error('getBundleInstaller failed:' + error.message); +} +``` + +## BundleInstaller.getBundleInstaller + +getBundleInstaller(): Promise\; + +获取BundleInstaller对象,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**返回值:** +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------ | +| Promise\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | Promise对象,返回BundleInstaller对象 | + +**错误码:** + +错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; + +try { + installer.getBundleInstaller().then((data) => { + console.info('getBundleInstaller successfully.'); + }).catch((error) => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.install +install(hapFilePaths: Array<string>, installParam: InstallParam, callback: AsyncCallback<void>): void; + +以异步方法安装应用,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| hapFilePaths | Array<string> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP包的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP包,且这些HAP包的签名需要保持一致 | +| installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数 | +| callback | AsyncCallback<void> | 是 | 回调函数,安装应用成功,err为undefined,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------------------------| +| 17700004 | The specified userId is not existed | +| 17700010 | To parse file of config.json or module.json failed | +| 17700011 | To verify signature failed | +| 17700012 | Invalid hap file path or too large file size | +| 17700015 | Multiple haps have inconsistent configured information | +| 17700016 | No disk space left for installation | +| 17700017 | Downgrade installation is prohibited | +| 17700101 | The system service is excepted | +| 17700103 | I/O operation is failed | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +try { + installer.getBundleInstaller().then(data => { + data.install(hapFilePaths, installParam, err => { + if (err) { + console.error('install failed:' + err.message); + } else { + console.info('install successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.uninstall + +uninstall(bundleName: string, installParam: InstallParam, callback: AsyncCallback<void>): void; + +以异步方法卸载应用,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | 是 | 包名 | +| installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数 | +| callback | AsyncCallback<void> | 是 | 回调函数,卸载应用成功,err为undefined,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------------------------------------| +| 17700004 | The specified userId is not existed | +| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled | +| 17700101 | The system service is excepted | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1 +}; + +try { + installer.getBundleInstaller().then(data => { + data.uninstall(bundleName, installParam, err => { + if (err) { + console.error('uninstall failed:' + err.message); + } else { + console.info('uninstall successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## BundleInstaller.recover + +recover(bundleName: string, installParam: InstallParam, callback: AsyncCallback<void>): void; + +以异步方法回滚应用,使用callback形式返回结果。 + +**系统接口:** 此接口为系统接口,三方应用不支持调用 + +**需要权限:** ohos.permission.INSTALL_BUNDLE + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Core + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | 是 | 包名 | +| installParam | [InstallParam](#installparam) | 是 | 指定安装所需的其他参数 | +| callback | AsyncCallback<void> | 是 | 回调函数,回滚应用成功,err为undefined,否则为错误对象 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。 + +| 错误码ID | 错误码信息 | +| -------- | ---------------------------------------------------------------------------| +| 17700004 | The specified userId is not existed | + +**示例:** + +```ts +import installer from '@ohos.bundle.installer'; +let bundleName = 'com.ohos.demo'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1 +}; + +try { + installer.getBundleInstaller().then(data => { + data.recover(bundleName, installParam, err => { + if (err) { + console.error('recover failed:' + err.message); + } else { + console.info('recover successfully.'); + } + }); + }).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getBundleInstaller failed. Cause: ' + error.message); +} +``` + +## HashParam + +应用程序安装卸载信息 + + **系统能力:** SystemCapability.BundleManager.BundleFramework.Core + + **系统接口:** 此接口为系统接口,三方应用不支持调用 + +| 名称 | 类型 | 说明 | +| ---------- | ------ | ---------------- | +| moduleName | string | 应用程序模块名称 | +| hashValue | string | 哈希值 | + +## InstallParam + +应用程序安装卸载信息 + + **系统能力:** SystemCapability.BundleManager.BundleFramework.Core + + **系统接口:** 此接口为系统接口,三方应用不支持调用 + +| 名称 | 类型 | 说明 | +| ------------------------------ | ------------------------------ | ------------------ | +| userId | number | 指示用户id,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9)获取当前进程所在用户 | +| installFlag | number | 指示安装标志,枚举值:0:应用初次安装,1:应用覆盖安装 | +| isKeepData | boolean | 卸载时是否保留数据目录 | +| hashParams | Array<[HashParam](#hashparam)> | 哈希值参数 | +| crowdtestDeadline| number | 测试包的被杀死时间 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-keycode.md b/zh-cn/application-dev/reference/apis/js-apis-keycode.md index 072408de7c4db11a84a00f3742f0104eaaf2f52f..150356c791aee490a2aa04facc354b2c10a51674 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keycode.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keycode.md @@ -1,6 +1,6 @@ # 键值 -KeyCode模块提供了按键类设备的键值。 +按键设备键值。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -19,7 +19,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | -------------------------------- | ------ | ---- | ---- | --------------------------- | | KEYCODE_FN | number | 是 | 否 | 功能(Fn)键 | | KEYCODE_UNKNOWN | number | 是 | 否 | 未知按键 | -| KEYCODE_HOME | number | 是 | 否 | 按键Home | +| KEYCODE_HOME | number | 是 | 否 | 功能(Home)键 | | KEYCODE_BACK | number | 是 | 否 | 返回键 | | KEYCODE_MEDIA_PLAY_PAUSE | number | 是 | 否 | 多媒体键 播放/暂停 | | KEYCODE_MEDIA_STOP | number | 是 | 否 | 多媒体键 停止 | @@ -80,10 +80,10 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_Z | number | 是 | 否 | 按键'Z' | | KEYCODE_COMMA | number | 是 | 否 | 按键',' | | KEYCODE_PERIOD | number | 是 | 否 | 按键'.' | -| KEYCODE_ALT_LEFT | number | 是 | 否 | Alt+Left | -| KEYCODE_ALT_RIGHT | number | 是 | 否 | Alt+Right | -| KEYCODE_SHIFT_LEFT | number | 是 | 否 | Shift+Left | -| KEYCODE_SHIFT_RIGHT | number | 是 | 否 | Shift+Right | +| KEYCODE_ALT_LEFT | number | 是 | 否 | 左Alt键 | +| KEYCODE_ALT_RIGHT | number | 是 | 否 | 右Alt键 | +| KEYCODE_SHIFT_LEFT | number | 是 | 否 | 左Shift键 | +| KEYCODE_SHIFT_RIGHT | number | 是 | 否 | 右Shift键 | | KEYCODE_TAB | number | 是 | 否 | Tab键 | | KEYCODE_SPACE | number | 是 | 否 | 空格键 | | KEYCODE_SYM | number | 是 | 否 | 符号修改器按键 | @@ -107,19 +107,19 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_PAGE_DOWN | number | 是 | 否 | 向下翻页键 | | KEYCODE_ESCAPE | number | 是 | 否 | ESC键 | | KEYCODE_FORWARD_DEL | number | 是 | 否 | 删除键 | -| KEYCODE_CTRL_LEFT | number | 是 | 否 | Control+Left | -| KEYCODE_CTRL_RIGHT | number | 是 | 否 | Control+Right | +| KEYCODE_CTRL_LEFT | number | 是 | 否 | 左Ctrl键 | +| KEYCODE_CTRL_RIGHT | number | 是 | 否 | 右Ctrl键 | | KEYCODE_CAPS_LOCK | number | 是 | 否 | 大写锁定键 | | KEYCODE_SCROLL_LOCK | number | 是 | 否 | 滚动锁定键 | | KEYCODE_META_LEFT | number | 是 | 否 | 左元修改器键 | | KEYCODE_META_RIGHT | number | 是 | 否 | 右元修改器键 | -| KEYCODE_FUNCTION | number | 是 | 否 | 函数修改器键 | +| KEYCODE_FUNCTION | number | 是 | 否 | 功能键 | | KEYCODE_SYSRQ | number | 是 | 否 | 系统请求/打印屏幕键 | | KEYCODE_BREAK | number | 是 | 否 | Break/Pause键 | | KEYCODE_MOVE_HOME | number | 是 | 否 | 光标移动到开始键 | | KEYCODE_MOVE_END | number | 是 | 否 | 光标移动到末尾键 | | KEYCODE_INSERT | number | 是 | 否 | 插入键 | -| KEYCODE_FORWARD | number | 是 | 否 | 删除键 | +| KEYCODE_FORWARD | number | 是 | 否 | 前进键 | | KEYCODE_MEDIA_PLAY | number | 是 | 否 | 多媒体键 播放 | | KEYCODE_MEDIA_PAUSE | number | 是 | 否 | 多媒体键 暂停 | | KEYCODE_MEDIA_CLOSE | number | 是 | 否 | 多媒体键 关闭 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md index 45d91a8953f4e477a073562f8b7fa13e937ed306..d1ac98a67ae88626552bb6c8c02252bb5e351ace 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-keyevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ # 按键输入事件 -KeyEvent模块提供了设备可以上报的按键事件。 +设备上报的按键事件。 > **说明:** > @@ -18,9 +18,9 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ------ | -------- | ---- | ---- | -------- | -| CANCEL | number | 是 | 否 | 取消按钮 | -| DOWN | number | 是 | 否 | 按下按钮 | -| UP | number | 是 | 否 | 抬起按钮 | +| CANCEL | number | 是 | 否 | 按键取消 | +| DOWN | number | 是 | 否 | 按键按下 | +| UP | number | 是 | 否 | 按键抬起 | ## Key @@ -29,8 +29,8 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ----------- | -------- | ---- | ---- | -------------- | | code | KeyCode | 是 | 否 | 按键码 | -| pressedTime | number | 是 | 否 | 按下持续的时间 | -| deviceId | number | 是 | 否 | 按键所属设备 | +| pressedTime | number | 是 | 否 | 按键按下时间 | +| deviceId | number | 是 | 否 | 按键所属设备id | ## KeyEvent @@ -39,7 +39,7 @@ import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ----------- | -------- | ---- | ---- | ------------------------------ | | action | Action | 是 | 否 | 按键动作 | -| key | Key | 是 | 否 | 当前发生变化的按键 | +| key | Key | 是 | 否 | 当前上报的按键 | | unicodeChar | number | 是 | 否 | 按键对应的uniCode字符 | | keys | Key[] | 是 | 否 | 当前处于按下状态的按键列表 | | ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md new file mode 100644 index 0000000000000000000000000000000000000000..96dc07d812c0ac9a3c87e143254752ef98064865 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -0,0 +1,267 @@ +# Bundle.launcherBundleManager模块 + +本模块支持launcher应用所需的查询能力,支持[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)、[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)信息的查询。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; +``` + + +## launcherBundlemanager.**getLauncherAbilityInfo9+** + +getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallback>) : void; + +查询指定bundleName及用户的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用程序包名称。 | +| userId | number | 是 | 被查询的用户id。| + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | --------------------------------------------------- | +| AsyncCallback\> | callback形式返回bundle包含的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)信息 | + +**相关错误码** + +| 错误码 | 错误信息(此处仅提供错误抛出的关键信息) | +| -------- | ---------------------------------------- | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user id is not found. | + +**示例:** + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getLauncherAbilityInfo('com.example.demo', 100, (errData, data) => { + if (errData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + } + console.log("data is " + JSON.Stringify(data)); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +getLauncherAbilityInfo(bundleName: string, userId: number) : Promise>; + +查询指定bundleName及用户的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用程序包名称 。| +| userId | number | 是 | 被查询的用户id。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | -------------------------------------------------- | +| Promise\> | Promise形式返回bundle包含的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)信息 | + +**相关错误码** + +| 错误码 | 错误信息(此处仅提供错误抛出的关键信息) | +| -------- | ---------------------------------------- | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user id is not found. | + +**示例:** + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getLauncherAbilityInfo("com.example.demo", 100).then(data => { + console.log("data is " + JSON.Stringify(data)); + }).catch (errData => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +## launcherBundlemanager.getAllLauncherAbilityInfo9+ + +getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback>) : void; + +查询指定用户下所有应用的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------- | +| userId | number | 是 | 被查询的用户id。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | ------------------------------------------------------- | +| AsyncCallback\> | callback形式返回指定用户下所有应用的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) | + +**相关错误码** + +| 错误码 | 错误信息(此处仅提供错误抛出的关键信息) | +| -------- | ---------------------------------------- | +| 17700004 | The specified user id is not found. | + +示例: + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getAllLauncherAbilityInfo(100, (errData, data) => { + if (errData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + } + console.log("data is " + JSON.Stringify(data)); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +getAllLauncherAbilityInfo(userId: number) : Promise>; + +查询指定用户下所有应用的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**参数:** + +| 参数名 | 类型 | 必填 | 描述 | +| ------ | ------ | ---- | -------------- | +| userId | number | 是 | 被查询的用户id。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | ------------------------------------------------------ | +| Promise\> | Promise形式返回指定用户下所有应用的[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) | + +示例: + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getAllLauncherAbilityInfo(100).then(data => { + console.log("data is " + JSON.Stringify(data)); + }).catch (errData => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +## launcherBundlemanager.getShortcutInfo9+ + +getShortcutInfo(bundleName :string, callback: AsyncCallback>) : void; + +查询当前用户下指定应用的[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +| 参数名 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用程序包名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| AsyncCallback\> | callback形式返回当前用户下指定应用的[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) | + +示例: + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getShortcutInfo("com.example.demo", (errData, data) => { + if (errData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + } + console.log("data is " + JSON.Stringify(data)); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` + +getShortcutInfo(bundleName : string) : Promise>; + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统接口:** 此接口为系统接口 + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +| 参数名 | 类型 | 必填 | 描述 | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | 是 | 应用程序包名称。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | ----------------------------------------------- | +| Promise\> | Promise形式返回当前用户下指定应用的[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) | + +示例: + +```typescript +import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; + +try { + launcherBundleManager.getShortcutInfo("com.example.demo").then(data => { + console.log("data is " + JSON.Stringify(data)); + }).catch (errData => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + }) +} catch (errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md index 7a05a0d9b342d62f1f50594a256009de753fcfb7..2514ed13d36f220d75e6f70f757d50fd436152b6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -91,7 +91,7 @@ isEmpty(): boolean const lightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); try { - lightWeightMap.isEmpty.bind({})(); + lightWeightMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -136,7 +136,7 @@ let map = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); try { - lightWeightMap.hasAll.bind({}, map)(); + lightWeightMap.hasAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasKey("squirrel"); try { - lightWeightMap.hasKey.bind({}, "squirrel")(); + lightWeightMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ let result = lightWeightMap.hasValue(123); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasValue(123); try { - lightWeightMap.hasValue.bind({}, 123)(); + lightWeightMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -258,7 +258,7 @@ increaseCapacityTo(minimumCapacity: number): void let lightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); try { - lightWeightMap.increaseCapacityTo.bind({}, 10)(); + lightWeightMap.increaseCapacityTo.bind({}, 10)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -301,7 +301,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); try { - lightWeightMap.get.bind({}, "sparrow")(); + lightWeightMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -344,7 +344,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); try { - lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); + lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -387,7 +387,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); try { - lightWeightMap.getIndexOfValue.bind({}, 123)(); + lightWeightMap.getIndexOfValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -431,12 +431,12 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); try { - lightWeightMap.getKeyAt.bind({}, 1)(); + lightWeightMap.getKeyAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } try { - lightWeightMap.getKeyAt(6)(); + lightWeightMap.getKeyAt(6)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -474,7 +474,7 @@ lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); lightWeightMap.setAll(map); try { - lightWeightMap.setAll.bind({}, map)(); + lightWeightMap.setAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -515,7 +515,7 @@ set(key: K, value: V): Object let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); try { - lightWeightMap.set.bind({}, "squirrel", 123)(); + lightWeightMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -558,7 +558,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); try { - lightWeightMap.remove.bind({}, "sparrow")(); + lightWeightMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -601,7 +601,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); try { - lightWeightMap.removeAt.bind({}, 1)(); + lightWeightMap.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -646,7 +646,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); try { - lightWeightMap.setValueAt.bind({}, 1, 3546)(); + lightWeightMap.setValueAt.bind({}, 1, 3546)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -695,7 +695,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); try { - lightWeightMap.getValueAt.bind({}, 1)(); + lightWeightMap.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -731,7 +731,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); try { - lightWeightMap.clear.bind({})(); + lightWeightMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -773,7 +773,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.keys.bind({})(); + lightWeightMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -815,7 +815,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.values.bind({})(); + lightWeightMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -864,7 +864,7 @@ lightWeightMap.forEach((value, key) => { try { lightWeightMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -907,7 +907,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap.entries.bind({})(); + lightWeightMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -943,7 +943,7 @@ lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let iter = lightWeightMap.toString(); try { - lightWeightMap.toString.bind({})(); + lightWeightMap.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -993,7 +993,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightMap[Symbol.iterator].bind({})(); + lightWeightMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md index 6639774866e6a398689f3d54b540213f9e0c9e2a..64dcd50b28ddc85b09c099134cd3b5a5f6b35fca 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -91,7 +91,7 @@ isEmpty(): boolean const lightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); try { - lightWeightSet.isEmpty.bind({})(); + lightWeightSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -131,7 +131,7 @@ add(obj: T): boolean let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); try { - lightWeightSet.add.bind({}, "squirrel")(); + lightWeightSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -170,7 +170,7 @@ let set = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); try { - lightWeightSet.addAll.bind({}, set)(); + lightWeightSet.addAll.bind({}, set)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -215,7 +215,7 @@ let set = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); try { - lightWeightSet.hasAll.bind({}, set)(); + lightWeightSet.hasAll.bind({}, set)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -258,7 +258,7 @@ let result = lightWeightSet.has(123); lightWeightSet.add(123); result = lightWeightSet.has(123); try { - lightWeightSet.has.bind({}, 123)(); + lightWeightSet.has.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -302,7 +302,7 @@ lightWeightSet.add("sparrow"); let obj = ["squirrel", "sparrow"]; let result = lightWeightSet.equal(obj); try { - lightWeightSet.equal.bind({}, obj)(); + lightWeightSet.equal.bind({}, obj)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -338,7 +338,7 @@ increaseCapacityTo(minimumCapacity: number): void let lightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); try { - lightWeightSet.increaseCapacityTo.bind({}, 10)(); + lightWeightSet.increaseCapacityTo.bind({}, 10)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -386,7 +386,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); try { - lightWeightSet.getIndexOf.bind({}, "sparrow")(); + lightWeightSet.getIndexOf.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -429,7 +429,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); try { - lightWeightSet.remove.bind({}, "sparrow")(); + lightWeightSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -472,7 +472,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); try { - lightWeightSet.removeAt.bind({}, 1)(); + lightWeightSet.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -515,7 +515,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); try { - lightWeightSet.getValueAt.bind({}, 1)(); + lightWeightSet.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -546,7 +546,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); try { - lightWeightSet.clear.bind({})(); + lightWeightSet.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -583,7 +583,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); try { - lightWeightSet.toString.bind({})(); + lightWeightSet.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -620,7 +620,7 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); try { - lightWeightSet.toArray.bind({})(); + lightWeightSet.toArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -662,7 +662,7 @@ while(index < lightWeightSet.length) { index++; } try { - lightWeightSet.values.bind({})(); + lightWeightSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -711,7 +711,7 @@ lightWeightSet.forEach((value, key) => { try { lightWeightSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -753,7 +753,7 @@ while(index < lightWeightSet.length) { index++; } try { - lightWeightSet.entries.bind({})(); + lightWeightSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -802,7 +802,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - lightWeightSet[Symbol.iterator].bind({})(); + lightWeightSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index 6f0a7a76eb45b08f700a6a582ad3ba1249186f8a..ba3e264e29dfda0f7ecb933c41c75382ec587d55 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -98,11 +98,12 @@ let linkedList = new LinkedList(); let result = linkedList.add("a"); let result1 = linkedList.add(1); let b = [1, 2, 3]; -linkedList.add(b); +let result2 = linkedList.add(b); let c = {name : "Dylon", age : "13"}; -let result3 = linkedList.add(false); +let result3 = linkedList.add(c); +let result4 = linkedList.add(false); try { - linkedList.add.bind({}, "b")(); + linkedList.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -139,9 +140,10 @@ linkedList.addFirst(1); let b = [1, 2, 3]; linkedList.addFirst(b); let c = {name : "Dylon", age : "13"}; +linkedList.addFirst(c); linkedList.addFirst(false); try { - linkedList.addFirst.bind({}, "b")(); + linkedList.addFirst.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -179,7 +181,7 @@ linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); try { - linkedList.insert.bind({}, 3, "b")(); + linkedList.insert.bind({}, 3, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -226,7 +228,7 @@ let result1 = linkedList.has("squirrel"); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); try { - linkedList.has.bind({}, "squirrel")(); + linkedList.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -273,7 +275,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.get(2); try { - linkedList.get.bind({}, 2)(); + linkedList.get.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -320,7 +322,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.getLastIndexOf(2); try { - linkedList.getLastIndexOf.bind({}, 2)(); + linkedList.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -367,7 +369,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.getIndexOf(2); try { - linkedList.getIndexOf.bind({}, 2)(); + linkedList.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -413,7 +415,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeByIndex(2); try { - linkedList.removeByIndex.bind({}, 2)(); + linkedList.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -463,7 +465,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeFirst(); try { - linkedList.removeFirst.bind({})(); + linkedList.removeFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -508,7 +510,7 @@ linkedList.add(2); linkedList.add(4); let result = linkedList.removeLast(); try { - linkedList.removeLast.bind({})(); + linkedList.removeLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -552,7 +554,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.remove(2); try { - linkedList.remove.bind({}, 2)(); + linkedList.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -592,7 +594,7 @@ removeFirstFound(element: T): boolean ```ts let linkedList = new LinkedList(); try { - linkedList.removeFirstFound(); + linkedList.removeFirstFound(4); } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -602,7 +604,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.removeFirstFound(4); try { - linkedList.removeFirstFound.bind({}, 2)(); + linkedList.removeFirstFound.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -652,7 +654,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.removeLastFound(4); try { - linkedList.removeLastFound.bind({}, 4)(); + linkedList.removeLastFound.bind({}, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -690,7 +692,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.clone(); try { - linkedList.clone.bind({})(); + linkedList.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -742,7 +744,7 @@ linkedList.forEach((value, index) => { try { linkedList.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -774,7 +776,7 @@ linkedList.add(5); linkedList.add(4); linkedList.clear(); try { - linkedList.clear.bind({})(); + linkedList.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -820,7 +822,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.set(2, "b"); try { - linkedList.set.bind({}, 2, "b")(); + linkedList.set.bind({}, 2, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -862,7 +864,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.convertToArray(); try { - linkedList.convertToArray.bind({})(); + linkedList.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -900,7 +902,7 @@ linkedList.add(5); linkedList.add(4); let result = linkedList.getFirst(); try { - linkedList.getFirst.bind({})(); + linkedList.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -938,7 +940,7 @@ linkedList.add(5); linkedList.add(4); linkedList.getLast(); try { - linkedList.getLast.bind({})(); + linkedList.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -988,7 +990,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - linkedList[Symbol.iterator].bind({})(); + linkedList[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md index 6af207351213967e43bc23ac340a2d7d837373a6..0d2eb8595d2791af97b275ad20daf413258c4193 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-list.md +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -90,14 +90,15 @@ add(element: T): boolean ```ts let list = new List(); -let result = list.add("a"); -let result1 = list.add(1); +let result1 = list.add("a"); +let result2 = list.add(1); let b = [1, 2, 3]; -list.add(b); +let result3 = list.add(b); let c = {name : "Dylon", age : "13"}; -let result3 = list.add(false); +let result4 = list.add(c); +let result5 = list.add(false); try { - list.add.bind({}, "b")(); + list.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -135,7 +136,7 @@ list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); try { - list.insert.bind({}, "b", 3)(); + list.insert.bind({}, "b", 3)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -182,7 +183,7 @@ let result = list.has("squirrel"); list.add("squirrel"); let result1 = list.has("squirrel"); try { - list.has.bind({}, "squirrel")(); + list.has.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -229,7 +230,7 @@ list.add(2); list.add(4); let result = list.get(2); try { - list.get.bind({}, 2)(); + list.get.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -276,7 +277,7 @@ list.add(2); list.add(4); let result = list.getLastIndexOf(2); try { - list.getLastIndexOf.bind({}, 2)(); + list.getLastIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -324,7 +325,7 @@ list.add(4); list.getIndexOf(2); let result = list.getIndexOf(2); try { - list.getIndexOf.bind({}, 2)(); + list.getIndexOf.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -374,7 +375,7 @@ list.equal(obj1); let obj2 = {name : "Dylon", age : "13"}; let result = list.equal(obj2); try { - list.equal.bind({}, obj2)(); + list.equal.bind({}, obj2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -420,7 +421,7 @@ list.add(2); list.add(4); let result = list.removeByIndex(2); try { - list.removeByIndex.bind({}, 2)(); + list.removeByIndex.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -469,7 +470,7 @@ list.add(5); list.add(4); let result = list.remove(2); try { - list.remove.bind({}, 2)(); + list.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -524,7 +525,7 @@ list.replaceAllElements((value: number, index: number) => { try { list.replaceAllElements.bind({}, (value: number, index: number) => { return value = 2 * value; - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -576,7 +577,7 @@ list.forEach((value, index) => { try { list.forEach.bind({}, (value, index) => { console.log("value: " + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -623,7 +624,7 @@ list.add(4); list.sort((a: number, b: number) => a - b); list.sort((a: number, b: number) => b - a); try { - list.sort.bind({}, (a: number, b: number) => b - a)(); + list.sort.bind({}, (a: number, b: number) => b - a)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -671,7 +672,7 @@ let result = list.getSubList(2, 4); let result1 = list.getSubList(4, 3); let result2 = list.getSubList(2, 6); try { - list.getSubList.bind({}, 2, 4)(); + list.getSubList.bind({}, 2, 4)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -708,7 +709,7 @@ list.add(5); list.add(4); list.clear(); try { - list.clear.bind({})(); + list.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -754,7 +755,7 @@ list.add(5); list.add(4); list.set(2, "b"); try { - list.set.bind({}, 3, "b")(); + list.set.bind({}, 3, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -797,7 +798,7 @@ list.add(5); list.add(4); let result = list.convertToArray(); try { - list.convertToArray.bind({})(); + list.convertToArray.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -835,7 +836,7 @@ list.add(5); list.add(4); let result = list.isEmpty(); try { - list.isEmpty.bind({})(); + list.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -873,7 +874,7 @@ list.add(5); list.add(4); let result = list.getFirst(); try { - list.getFirst.bind({})(); + list.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -911,7 +912,7 @@ list.add(5); list.add(4); let result = list.getLast(); try { - list.getLast.bind({})(); + list.getLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -961,7 +962,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - list[Symbol.iterator].bind({})(); + list[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 32319b0f5e36631db7f00257255834b220947330..94e38c88cfe4f0b51cc613bea4293c5d85829b67 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -1080,7 +1080,7 @@ seek(timeMs: number, mode?:SeekMode): Promise\ | 类型 | 说明 | | -------------- | ------------------------------------------- | -| Promise\ | 跳转到指定播放位置的Promise返回值,单位ms。 | +| Promise\ | 跳转到指定播放位置的Promise返回值,单位ms。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md index c9be6f2af616711ec5ce4c69ed98def44f71cb1f..da6168229c6c24ff3230dec69ab5f41547ba00fe 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md +++ b/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @@ -300,12 +300,17 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr **示例:** ```js -let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; -media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ - console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult)); -}).catch(function(err){ - console.info("getPublicDirectory failed with error:"+ err); -}); +async function example() { + // 使用Promise方式创建Image类型文件 + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + const path = await media.getPublicDirectory(DIR_IMAGE); + media.createAsset(mediaType, 'imagePromise.jpg', path + 'myPicture/').then((fileAsset) => { + console.info('createAsset successfully, message = ' + JSON.stringify(fileAsset)); + }).catch((err) => { + console.info('createAsset failed, message = ' + err); + }); +} ``` ### deleteAsset8+ @@ -2587,3 +2592,4 @@ async function example() { | type | string | 是 | 媒体类型,包括:image, video, media,当前仅支持media类型 | | count | number | 是 | 媒体选择,count = 1表示单选,count大于1表示多选。 | + diff --git a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md index 557a6a1a8554f9fa895bbba2680069370e0a6510..e576e6611ddd5adce1afe4c1a16c478309bf90f8 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @@ -17,13 +17,13 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ----------- | -------- | ---- | ---- | -------------------- | -| CANCEL | number | 是 | 否 | 取消动作 | +| CANCEL | number | 是 | 否 | 取消 | | MOVE | number | 是 | 否 | 鼠标移动 | | BUTTON_DOWN | number | 是 | 否 | 鼠标按钮按下 | | BUTTON_UP | number | 是 | 否 | 鼠标按钮抬起 | -| AXIS_BEGIN | number | 是 | 否 | 鼠标关联的轴事件开始 | -| AXIS_UPDATE | number | 是 | 否 | 鼠标关联的轴事件更新 | -| AXIS_END | number | 是 | 否 | 鼠标关联的轴事件结束 | +| AXIS_BEGIN | number | 是 | 否 | 鼠标轴事件开始 | +| AXIS_UPDATE | number | 是 | 否 | 鼠标轴事件更新 | +| AXIS_END | number | 是 | 否 | 鼠标轴事件结束 | ## Button @@ -69,14 +69,14 @@ import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mou | 名称 | 参数类型 | 可读 | 可写 | 描述 | | -------------- | ----------- | ---- | ---- | ---------------------------------------- | | action | Action | 是 | 否 | 鼠标事件动作 | -| screenX | number | 是 | 否 | 鼠标光标在屏幕中的x坐标 | -| screenY | number | 是 | 否 | 鼠标光标在屏幕中的y坐标 | -| windowX | number | 是 | 否 | 鼠标归属窗口的x坐标 | -| windowY | number | 是 | 否 | 鼠标归属窗口的y坐标 | -| rawDeltaX | number | 是 | 否 | X轴相对上次上报鼠标位置的偏移,在屏幕边缘位置时,该值可能小于两次鼠标上报的坐标差 | -| rawDeltaY | number | 是 | 否 | Y轴相对上次上报鼠标位置的偏移 | -| button | Button | 是 | 否 | 当前按下/抬起的按钮 | -| pressedButtons | Button[] | 是 | 否 | 当前处于按下状态的按钮 | +| screenX | number | 是 | 否 | 鼠标光标在屏幕中的横坐标 | +| screenY | number | 是 | 否 | 鼠标光标在屏幕中的纵坐标 | +| windowX | number | 是 | 否 | 鼠标所在窗口的横坐标 | +| windowY | number | 是 | 否 | 鼠标所在窗口的纵坐标 | +| rawDeltaX | number | 是 | 否 | 鼠标本次操作横坐标偏移值 | +| rawDeltaY | number | 是 | 否 | 鼠标本次操作纵坐标偏移值 | +| button | Button | 是 | 否 | 鼠标按钮 +| pressedButtons | Button[] | 是 | 否 | 当前处于按下状态的鼠标按钮 | | axes | AxisValue[] | 是 | 否 | 事件包含的所有轴数据 | | pressedKeys | KeyCode[] | 是 | 否 | 当前处于按下状态的按键列表 | | ctrlKey | boolean | 是 | 否 | 当前ctrlKey是否处于按下状态 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md index 71a0bee5b2b0e60b8ee2984768de9fa1c4891da5..e2aa810f1382baeea9df6845f028ef2cbec3d9e2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @@ -315,12 +315,272 @@ getTagInfo(want: [Want](js-apis-application-Want.md#Want)): [TagInfo](#taginfo) | ------------------ | --------------------------| | [TagInfo](#taginfo) | TagInfo对象,用于获取不同技术类型的Tag对象。 | + +## tag.ndef.makeUriRecord9+ + +makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); + +根据输入的URI,构建NDEF标签的Record数据对象。 + +**系统能力**:SystemCapability.Communication.NFC.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = tag.ndef.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.makeTextRecord9+ + +makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); + +根据输入的文本数据和编码类型,构建NDEF标签的Record。 + +**系统能力**:SystemCapability.Communication.NFC.Core + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | 是 | 写入到NDEF Record里面的文本数据内容。 | +| locale | string | 是 | 文本数据内容的编码方式。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +try { + let text = "Hello World"; // change it to be correct. + let locale = "en"; // change it to be correct. + let ndefRecord = tag.ndef.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} +``` + + +## tag.ndef.makeMimeRecord9+ + +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9); + +根据输入的MIME数据和类型,构建NDEF标签的Record。 + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | 是 | 符合RFC规则的MIME类型,比如"text/plain"或"image/jpeg"。 | +| mimeData | number[] | 是 | MIME数据内容,每个number十六进制表示,范围是0x00~0xFF。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +try { + let mimeType = "text/plain"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04, ...]; // change it to be correct. + let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +## tag.ndef.makeExternalRecord9+ + +makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9); + +根据应用程序特定的外部数据,构建NDEF标签的Record。 + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | 是 | 外部数据发布组织的域名,一般是应用程序的包名。 | +| type | string | 是 | 外部数据的指定类型。 | +| externalData | number[] | 是 | 外部数据内容,每个number十六进制表示,范围是0x00~0xFF。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "test"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04, ...]; // change it to be correct. + let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[]; + +把输入的NDEF消息数据对象,转换为字节格式的数据。 + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | 是 | NDEF消息数据对象。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| number[] | NDEF消息数据对象,所转换成的字节格式的数据。每个number十六进制表示,范围是0x00~0xFF。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} + +try { + let rawData2 = tag.ndef.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData2: " + rawData2); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` +## tag.ndef.createNdefMessage9+ + +createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +使用原始字节数据创建NDEF标签的Message。该数据必须符合NDEF Record数据格式,如果不符合格式,则返回的NdeMessage数据对象,所包含的NDE Record列表会为空。 + +**系统能力**:SystemCapability.Communication.NFC + +**参数:** +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF。要求必须满足NDEF Record的格式。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## tag.ndef.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +使用NDEF Records列表,创建NDEF Message。 + +**系统能力**:SystemCapability.Communication.NFC.Core + +**参数:** +| **参数名** | **类型** | **必填** | **说明** | +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | 是 | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | + +**返回值:** +| **类型** | **说明** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。| + +**示例:** +```js +import tag from '@ohos.nfc.tag'; + +let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony"); +let textRecord = tag.ndef.makeTextRecord("Hello World", "en"); +let ndefRecords = [uriRecord, textRecord]; +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + ## TagInfo NFC服务在读取到标签时给出的对象,通过改对象属性,应用知道该标签支持哪些技术类型,并使用匹配的技术类型来调用相关接口。 **系统能力**:SystemCapability.Communication.NFC.Core +**需要权限**:ohos.permission.NFC_TAG + | **参数名** | **类型** | **说明** | | -------- | -------- | -------- | | uid9+ | number[] | 标签的uid,每个number值是十六进制表示,范围是0x00~0xFF。 | @@ -331,6 +591,7 @@ NFC服务在读取到标签时给出的对象,通过改对象属性,应用 NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **类型** | **说明** | | -------- | -------- | -------- | | tnf | number | NDEF Record的TNF(Type Name Field)。 | @@ -342,22 +603,24 @@ NDEF标签Record属性的定义,参考NDEF标签技术规范《NFCForum-TS-NDE NFC Tag有多种不同的技术类型,定义常量描述不同的技术类型。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| NFC_A | 1 | NFC-A(ISO 14443-3A)技术。| -| NFC_B | 2 | NFC-A(ISO 14443-3B)技术。| -| ISO_DEP | 3 | ISO-DEP(ISO 14443-4)技术。| -| NFC_F | 4 | NFC-F(JIS 6319-4)技术。| -| NFC_V | 5 | NFC-V(ISO 15693)技术。| +| NFC_A | 1 | NFC-A (ISO 14443-3A)技术。| +| NFC_B | 2 | NFC-A (ISO 14443-3B)技术。| +| ISO_DEP | 3 | ISO-DEP (ISO 14443-4)技术。| +| NFC_F | 4 | NFC-F (JIS 6319-4)技术。| +| NFC_V | 5 | NFC-V (ISO 15693)技术。| | NDEF | 6 | NDEF技术。| +| NDEF_FORMATABLE9+ | 7 | 可以格式化的NDEF技术。| | MIFARE_CLASSIC | 8 | MIFARE Classic技术。| | MIFARE_ULTRALIGHT | 9 | MIFARE Utralight技术。| -| NDEF_FORMATABLE9+ | 10 | 可以格式化的NDEF技术。| ## TnfType9+ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | | TNF_EMPTY | 0x0 | Empty。| @@ -372,6 +635,7 @@ NDEF Record的TNF(Type Name Field)类型值,参考NDEF标签技术规范《NFC NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规范《NFCForum-TS-NDEF_1.0》的定义细节。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | | RTD_TEXT9+ | [0x54] | 文本类型的NDEF Record。| @@ -381,6 +645,7 @@ NDEF Record的RTD(Record Type Definition)类型值,参考NDEF标签技术规 NFC Forum标准里面Tag类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | | NFC_FORUM_TYPE_1 | 1 | NFC论坛类型1。 | @@ -393,9 +658,10 @@ NFC Forum标准里面Tag类型的定义。 MIFARE Classic标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | -| TYPE_UNKNOWN | 0 | 未知MIFARE类型。 | +| TYPE_UNKNOWN | 0 | 未知的MIFARE类型。 | | TYPE_CLASSIC | 1 | MIFARE Classic类型。| | TYPE_PLUS | 2 | MIFARE Plus类型。| | TYPE_PRO | 3 | MIFARE Pro类型。 | @@ -404,6 +670,7 @@ MIFARE Classic标签类型的定义。 MIFARE Classic标签存储大小的定义。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | | MC_SIZE_MINI | 320 | 每个标签5个扇区,每个扇区4个块。 | @@ -415,6 +682,7 @@ MIFARE Classic标签存储大小的定义。 MIFARE Ultralight标签类型的定义。 **系统能力**:SystemCapability.Communication.NFC.Core + | **参数名** | **常量值** | **说明** | | -------- | -------- | -------- | | TYPE_UNKOWN | 0 | 未知的 MIFARE 类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-nfctech.md b/zh-cn/application-dev/reference/apis/js-apis-nfctech.md index f198cca93ffad384df83c41be315cc0a0c252b7c..159daa8d2819971d08ec506ae7465167f400835a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-nfctech.md +++ b/zh-cn/application-dev/reference/apis/js-apis-nfctech.md @@ -173,7 +173,7 @@ getPmm(): number[] **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** @@ -207,7 +207,7 @@ getResponseFlags(): number **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** @@ -233,7 +233,7 @@ getDsfId(): number **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** @@ -265,7 +265,7 @@ getHistoricalBytes(): number[] 获取标签的历史字节,针对基于NfcA通信技术的IsoDep卡片。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -287,7 +287,7 @@ getHiLayerResponse(): number[] 获取标签的更高层响应字节,针对基于NfcB通信技术的IsoDep卡片。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -311,7 +311,7 @@ isExtendedApduSupported(): Promise<boolean> **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -358,7 +358,7 @@ isExtendedApduSupported(callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -405,7 +405,7 @@ getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] 获取NDEF消息中的所有记录。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -416,213 +416,14 @@ getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] ```js import tag from '@ohos.nfc.tag'; -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. -// var ndefMessage = ndefTag.createNdefMessage(...); +// Obtains ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = tag.ndef.createNdefMessage(...); // var ndefMessage = ndefTag.getNdefMessage(); let ndefRecords = ndefMessage.getNdefRecords(); console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -### NdefMessage.makeUriRecord9+ - -makeUriRecord(uri: string): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); - -根据输入的URI,构建NDEF标签的Record数据对象。 - -**系统能力**:SystemCapability.Communication.NFC -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| uri | string | 是 | 写入到NDEF Record里面的数据内容。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: -// var ndefMessage = ndefTag.createNdefMessage(...); -// var ndefMessage = ndefTag.getNdefMessage(); - -try { - let uri = "https://gitee.com/openharmony"; // change it to be correct. - let ndefRecord = ndefMessage.makeUriRecord(uri); - if (ndefRecord != undefined) { - console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); - console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); - } else { - console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); - } -} catch (busiError) { - console.log("ndefMessage makeUriRecord catched busiError: " + busiError); -} -``` - -### NdefMessage.makeTextRecord9+ - -makeTextRecord(text: string, locale: string): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); - -根据输入的文本数据和编码类型,构建NDEF标签的Record。 - -**系统能力**:SystemCapability.Communication.NFC -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| text | string | 是 | 写入到NDEF Record里面的文本数据内容。 | -| locale | string | 是 | 文本数据内容的编码方式。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: -// var ndefMessage = ndefTag.createNdefMessage(...); -// var ndefMessage = ndefTag.getNdefMessage(); - -try { - let text = "Hello World"; // change it to be correct. - let locale = "utf8"; // change it to be correct. - let ndefRecord = ndefMessage.makeTextRecord(text, locale); - if (ndefRecord != undefined) { - console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); - console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); - } else { - console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); - } -} catch (busiError) { - console.log("ndefMessage makeTextRecord catched busiError: " + busiError); -} -``` - - -### NdefMessage.makeMimeRecord9+ - -makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); - -根据输入的MIME数据和类型,构建NDEF标签的Record。 - -**系统能力**:SystemCapability.Communication.NFC -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| mimeType | string | 是 | MIME数据的类型。 | -| mimeData | number[] | 是 | MIME数据内容。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: -// var ndefMessage = ndefTag.createNdefMessage(...); -// var ndefMessage = ndefTag.getNdefMessage(); - -try { - let mimeType = "media"; // change it to be correct. - let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. - let ndefRecord = ndefMessage.makeMimeRecord(mimeType, mimeData); - if (ndefRecord != undefined) { - console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); - console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); - } else { - console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); - } -} catch (busiError) { - console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); -} -``` -### NdefMessage.makeExternalRecord9+ - -makeExternalRecord(domainName: string, serviceName: string, externalData: number[]): [NdefRecord](js-apis-nfcTag.md#ndefrecord9); - -根据应用程序特定的外部数据,构建NDEF标签的Record。 - -**系统能力**:SystemCapability.Communication.NFC -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| domainName | string | 是 | 外部数据发布组织的域名,一般是应用程序的包名。 | -| serviceName | string | 是 | 外部数据的指定类型。 | -| externalData | number[] | 是 | 外部数据内容。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9) | NDEF标签的Record,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: -// var ndefMessage = ndefTag.createNdefMessage(...); -// var ndefMessage = ndefTag.getNdefMessage(); - -try { - let domainName = "ohos.nfc.application"; // change it to be correct. - let type = "nfc"; // change it to be correct. - let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. - let ndefRecord = ndefMessage.makeExternalRecord(domainName, type, externalData); - if (ndefRecord != undefined) { - console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); - console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); - } else { - console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); - } -} catch (busiError) { - console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); -} -``` - -### NdefMessage.messageToBytes9+ - -messageToBytes(ndefMessage: [NdefMessage](#ndefmessage9)): number[]; - -把输入的NDEF消息数据对象,转换为字节格式的数据。 - -**系统能力**:SystemCapability.Communication.NFC -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ---- | -------------------------------------- | -| ndefMessage | [NdefMessage](#ndefmessage9) | 是 | NDEF消息数据对象。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| number[] | NDEF消息数据对象,所转换成的字节格式的数据。每个number十六进制表示,范围是0x00~0xFF。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see NdefTag, obtains ndefMessage from ndefTag.createNdefMessage or ndefTag.getNdefMessage. Such as: -// var ndefMessage = ndefTag.createNdefMessage(...); -// var ndefMessage = ndefTag.getNdefMessage(); - -try { - // the parameter 'ndefMessage' can be different from the instance object. - let rawData = ndefMessage.messageToBytes(ndefMessage); - console.log("ndefMessage messageToBytes rawData: " + rawData); -} catch (busiError) { - console.log("ndefMessage messageToBytes catched busiError: " + busiError); -} -``` - ## NdefTag9+ 提供对已格式化为NDEF的NFC标签的数据和操作的访问,继承自TagSession。 @@ -631,88 +432,13 @@ TagSession是所有NFC Tag技术类型的基类, 提供建立连接和发送 以下是NdefTag的独有接口。 -### NdefTag.createNdefMessage9+ - -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) - -使用原始字节数据创建NDEF标签的Message。该数据必须符合NDEF Record数据格式,如果不符合格式,则返回的NdeMessage数据对象,所包含的NDE Record列表会为空。 - -**系统能力**:SystemCapability.Communication.NFC - -**参数:** -| **参数名** | **类型** | **必填** | **说明** | -| -------- | -------- | -------- | -------- | -| data | number[] | 是 | 原始字节,每个number十六进制表示,范围是0x00~0xFF。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. -let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // change the raw data bytes to be correct. -let ndefMessage; -try { - ndefMessage = ndefTag.createNdefMessage(rawData); - console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); -} catch (busiError) { - console.log("ndef createNdefMessage busiError: " + busiError); -} -``` - -### NdefTag.createNdefMessage9+ - -createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) - -使用NDEF Records列表,创建NDEF Message。 - -**系统能力**:SystemCapability.Communication.NFC - -**参数:** -| **参数名** | **类型** | **必填** | **说明** | -| -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | 是 | NDEF标签的Record列表,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。 | - -**返回值:** -| **类型** | **说明** | -| ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF标签的Message,详见NDEF技术规范《NFCForum-TS-NDEF_1.0》。| - -**示例:** -```js -import tag from '@ohos.nfc.tag'; - -// see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. -let ndefRecords = [ - // record format: tnf, rtdType, id, payload - // 1st record: - {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, - - // 2nd record: - {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, - - // other record if has one ... -]; -let ndefMessage; -try { - ndefMessage = ndefTag.createNdefMessage(ndefRecords); - console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); -} catch (busiError) { - console.log("ndef createNdefMessage busiError: " + busiError); -} -``` - ### NdefTag.getNdefTagType9+ getNdefTagType(): NfcForumType 获取NDEF标签的类型。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -734,7 +460,7 @@ getNdefMessage(): NdefMessage 获取发现NDEF标签时,从标签读取的Message。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -756,7 +482,7 @@ isNdefWritable(): boolean; 检查NDEF标签是否可写。在调用写数据接口前,需要先判断是否支持写操作。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -780,7 +506,7 @@ readNdef(): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -826,7 +552,7 @@ readNdef(callback: AsyncCallback\<[NdefMessage](#ndefmessage9)>): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -874,7 +600,7 @@ writeNdef(msg: NdefMessage): Promise\; **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -893,8 +619,8 @@ import tag from '@ohos.nfc.tag'; // see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. // ndefMessage created from raw data, such as: -let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. -// or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // MUST can be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) // connect the tag at first if not connected. if (!ndefTag.isTagConnected()) { @@ -923,7 +649,7 @@ writeNdef(msg: NdefMessage, callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -943,8 +669,8 @@ import tag from '@ohos.nfc.tag'; // see 'tag.TagInfo' at 'js-apis-nfcTag.md', obtains the 'ndefTag' correctly. // ndefMessage created from raw data, such as: -let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. -// or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // MUST can be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) // connect the tag at first if not connected. if (!ndefTag.isTagConnected()) { @@ -975,7 +701,7 @@ canSetReadOnly(): boolean **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -1005,7 +731,7 @@ setReadOnly(): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **错误码:** 以下错误码的详细介绍请参见[NFC错误码](../errorcodes/errorcode-nfc.md)。 @@ -1046,7 +772,7 @@ setReadOnly(callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1092,7 +818,7 @@ getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): str 将NFC论坛类型,转换为NFC论坛中定义的字符串描述。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1134,7 +860,7 @@ authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1184,7 +910,7 @@ authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1237,7 +963,7 @@ readSingleBlock(blockIndex: number): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1289,7 +1015,7 @@ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1339,7 +1065,7 @@ writeSingleBlock(blockIndex: number, data: number[]): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1388,7 +1114,7 @@ writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1489,7 +1215,7 @@ incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1541,7 +1267,7 @@ decrementBlock(blockIndex: number, value: number): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1590,7 +1316,7 @@ decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1642,7 +1368,7 @@ transferToBlock(blockIndex: number): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1689,7 +1415,7 @@ transferToBlock(blockIndex: number, callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1739,7 +1465,7 @@ restoreFromBlock(blockIndex: number): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1786,7 +1512,7 @@ restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1834,7 +1560,7 @@ getSectorCount(): number 获取MIFARE Classic标签中的扇区数。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -1856,7 +1582,7 @@ getBlockCountInSector(sectorIndex: number): number 获取指定扇区中的块数。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1889,7 +1615,7 @@ getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) 获取MIFARE Classic标签的类型。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -1911,7 +1637,7 @@ getTagSize(): number 获取标签的存储空间大小,具体请参见[MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9)。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -1933,7 +1659,7 @@ isEmulatedTag(): boolean 检查标签是不是被模拟的。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **返回值:** | **类型** | **说明** | @@ -1955,7 +1681,7 @@ getBlockIndex(sectorIndex: number): number 获取特定扇区的第一个块的序号。 -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -1990,7 +1716,7 @@ getSectorIndex(blockIndex: number): number **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2033,7 +1759,7 @@ readMultiplePages(pageIndex: number): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** @@ -2087,7 +1813,7 @@ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2137,7 +1863,7 @@ writeSinglePage(pageIndex: number, data: number[]): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2186,7 +1912,7 @@ writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2298,8 +2024,8 @@ if (!ndefFormatable.isTagConnected()) { try { // ndefMessage created from raw data, such as: - let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. - // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // MUST can be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) ndefFormatable.format(ndefMessage).then(() => { console.log("ndefFormatable format Promise success."); @@ -2319,7 +2045,7 @@ format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): v **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2348,8 +2074,8 @@ if (!ndefFormatable.isTagConnected()) { try { // ndefMessage created from raw data, such as: - let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. - // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // MUST can be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) ndefFormatable.format(ndefMessage, (err)=> { if (err) { @@ -2371,7 +2097,7 @@ formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ **需要权限**:ohos.permission.NFC_TAG -**系统能力**:SystemCapability.Communication.NFC +**系统能力**:SystemCapability.Communication.NFC.Core **参数:** | 参数名 | 类型 | 必填 | 说明 | @@ -2400,8 +2126,8 @@ if (!ndefFormatable.isTagConnected()) { try { // ndefMessage created from raw data, such as: - let ndefMessage = ndefTag.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // change the raw data to be correct. - // or ndefMessage created from ndefTag.createNdefMessage(ndefRecords: NdefRecord[]) + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // MUST can be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) ndefFormatable.formatReadOnly(ndefMessage).then(() => { console.log("ndefFormatable formatReadOnly Promise success."); @@ -2421,7 +2147,7 @@ formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\ { if (err) { diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index 454ff579051073954699875f933493f999809aad..212c3514f0f15998814642c9c0c1ed6866b162ab 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -3414,6 +3414,8 @@ Notification.getSyncNotificationEnabledWithoutApp(userId) ## NotificationSubscriber +提供订阅者接收到新通知或取消通知时的回调方法。 + **系统API**:此接口为系统接口,三方应用不支持调用。 ### onConsume @@ -3424,7 +3426,7 @@ onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void **系统能力**:SystemCapability.Notification.Notification -**系统API**: 此接口为系统接口,三方应用不支持调用。 +**系统接口**: 此接口为系统接口,三方应用不支持调用。 **参数:** @@ -3834,6 +3836,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationActionButton +描述通知中显示的操作按钮。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3846,6 +3850,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationBasicContent +描述普通文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3857,6 +3863,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationLongTextContent +描述长文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3871,6 +3879,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationMultiLineContent +描述多行文本通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3885,6 +3895,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationPictureContent +描述附有图片的通知。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3899,6 +3911,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationContent +描述通知类型。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3912,9 +3926,11 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlagStatus8+ +描述通知标志状态。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification -**系统API**:此接口为系统接口,三方应用不支持调用。 +**系统接口**:此接口为系统接口,三方应用不支持调用。 | 名称 | 值 | 描述 | | -------------- | --- | --------------------------------- | @@ -3925,6 +3941,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlags8+ +描述通知标志的实例。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3935,6 +3953,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationRequest +描述通知的请求。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3947,10 +3967,10 @@ Notification.subscribe(subscriber, subscribeCallback); | deliveryTime | 是 | 是 | number | 通知发送时间。 | | tapDismissed | 是 | 是 | boolean | 通知是否自动清除。 | | autoDeletedTime | 是 | 是 | number | 自动清除的时间。 | -| wantAgent | 是 | 是 | WantAgent | 点击跳转的WantAgent。 | +| wantAgent | 是 | 是 | WantAgent | WantAgent封装了应用的行为意图,点击通知时触发该行为。 | | extraInfo | 是 | 是 | {[key: string]: any} | 扩展参数。 | -| color | 是 | 是 | number | 通知背景颜色。 | -| colorEnabled | 是 | 是 | boolean | 通知背景颜色是否使能。 | +| color | 是 | 是 | number | 通知背景颜色。暂不支持。 | +| colorEnabled | 是 | 是 | boolean | 通知背景颜色是否使能。暂不支持。 | | isAlertOnce | 是 | 是 | boolean | 设置是否仅有一次此通知警报。 | | isStopwatch | 是 | 是 | boolean | 是否显示已用时间。 | | isCountDown | 是 | 是 | boolean | 是否显示倒计时时间。 | @@ -3980,6 +4000,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## DistributedOptions8+ +描述分布式选项。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -3992,6 +4014,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSlot +描述通知槽 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | @@ -4012,6 +4036,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSorting +提供有关活动通知的排序信息。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**: 此接口为系统接口,三方应用不支持调用。 @@ -4025,6 +4051,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSortingMap +提供关于已订阅的所有通知中活动通知的排序信息 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**:此接口为系统接口,三方应用不支持调用。 @@ -4037,6 +4065,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationSubscribeInfo +设置订阅所需通知的发布者的信息。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统API**: 此接口为系统接口,三方应用不支持调用。 @@ -4049,6 +4079,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationTemplate8+ +通知模板。 + **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification | 名称 | 参数类型 | 可读 | 可写 | 说明 | @@ -4059,6 +4091,8 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationUserInput8+ +保存用户输入的通知消息。 + **系统能力**:SystemCapability.Notification.Notification | 名称 | 可读 | 可写 | 类型 | 描述 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md index 0043100ba5eaa5b540517d43d75dc813d0f70a8d..7cc29cfcc0989fe5067656ef9345c78358aac775 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-osAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-osAccount.md @@ -1594,7 +1594,7 @@ createOsAccount(localName: string, type: OsAccountType): Promise<OsAccountInf | 类型 | 说明 | | ---------------------------------------------- | ------------------------------------- | -| Promise<[OsAccountInfo](#osaccountinfo)> | Promis对象,返回新创建的系统帐号的信息。 | +| Promise<[OsAccountInfo](#osaccountinfo)> | Promise对象,返回新创建的系统帐号的信息。 | **错误码:** @@ -2503,7 +2503,7 @@ getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; getBundleIdFromUid(uid: number): Promise<number>; -通过uid查询对应的bundleId,使用Promis异步回调。 +通过uid查询对应的bundleId,使用Promise异步回调。 **系统接口:** 此接口为系统接口。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index c5d033039f5bd94227577636efe84e62941edd59..27b1bfc3f827854304bb83ebe8cd7e643491d11e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -89,7 +89,7 @@ isEmpty(): boolean const plainArray = new PlainArray(); let result = plainArray.isEmpty(); try { - plainArray.isEmpty.bind({})(); + plainArray.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -132,7 +132,7 @@ plainArray.has(1); plainArray.add(1, "squirrel"); let result1 = plainArray.has(1); try { - plainArray.has.bind({}, 1)(); + plainArray.has.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -175,7 +175,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); try { - plainArray.get.bind({}, 1)(); + plainArray.get.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -218,7 +218,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); try { - plainArray.getIndexOfKey.bind({}, 2)(); + plainArray.getIndexOfKey.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -261,7 +261,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); try { - plainArray.getIndexOfValue.bind({}, "squirrel")(); + plainArray.getIndexOfValue.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -304,7 +304,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); try { - plainArray.getKeyAt.bind({}, 1)(); + plainArray.getKeyAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -347,7 +347,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); try { - plainArray.getValueAt.bind({}, 1)(); + plainArray.getValueAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -388,7 +388,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); try { - plainArray.clone.bind({})(); + plainArray.clone.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -424,7 +424,7 @@ add(key: number, value: T): void let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); try { - plainArray.add.bind({}, "squirrel")(); + plainArray.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -465,10 +465,9 @@ remove(key: number): T let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -plainArray.remove(2); let result = plainArray.remove(2); try { - plainArray.remove.bind({}, 2)(); + plainArray.remove.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -509,10 +508,9 @@ removeAt(index: number): T let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); -plainArray.removeAt(1); let result = plainArray.removeAt(1); try { - plainArray.removeAt.bind({}, 1)(); + plainArray.removeAt.bind({}, 1)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -557,7 +555,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); try { - plainArray.removeRangeFrom.bind({}, 1, 3)(); + plainArray.removeRangeFrom.bind({}, 1, 3)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -601,7 +599,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); try { - plainArray.setValueAt.bind({}, 1, 3546)(); + plainArray.setValueAt.bind({}, 1, 3546)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -643,7 +641,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); try { - plainArray.toString.bind({})(); + plainArray.toString.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -674,7 +672,7 @@ plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); try { - plainArray.clear.bind({})(); + plainArray.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -723,7 +721,7 @@ plainArray.forEach((value, index) => { try { plainArray.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -774,7 +772,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - plainArray[Symbol.iterator].bind({})(); + plainArray[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-pointer.md b/zh-cn/application-dev/reference/apis/js-apis-pointer.md old mode 100644 new mode 100755 index 44cfe78aeed2ed070e4e8a09f40f9ae23de26377..ca40808f6481390185bfb8882b3a447e6ed4cc61 --- a/zh-cn/application-dev/reference/apis/js-apis-pointer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-pointer.md @@ -153,7 +153,7 @@ try { } console.log(`Set pointer speed success`); }); -} catch (err) { +} catch (error) { console.log(`Set pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -208,14 +208,14 @@ getPointerSpeed(callback: AsyncCallback<number>): void ```js try { - pointer.getPointerSpeed(speed, (error, speed) => { + pointer.getPointerSpeed((error, speed) => { if (error) { console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); return; } console.log(`Get pointer speed success, speed: ${JSON.stringify(speed)}`); }); -} catch (err) { +} catch (error) { console.log(`Get pointer speed failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -294,6 +294,12 @@ getPointerStyle(windowId: number): Promise<PointerStyle> **参数**: +| 参数 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------- | +| windowId | number | 是 | 窗口id。 | + +**返回值**: + | 参数 | 说明 | | ---------------------------------------- | ------------------- | | Promise<[PointerStyle](#pointerstyle9)> | Promise实例,异步返回鼠标样式类型。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-queue.md b/zh-cn/application-dev/reference/apis/js-apis-queue.md index d75d29a0b02e20d194bc3582d4bf32376f0cc32f..e6d713fce36bd5c91e0dd42e087f292a37392890 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-queue.md +++ b/zh-cn/application-dev/reference/apis/js-apis-queue.md @@ -92,13 +92,12 @@ add(element: T): boolean let queue = new Queue(); let result = queue.add("a"); let result1 = queue.add(1); -queue.add(1); let b = [1, 2, 3]; -queue.add(b); +let result2 = queue.add(b); let c = {name : "Dylon", age : "13"}; let result3 = queue.add(c); try { - queue.add.bind({}, "b")(); + queue.add.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -137,7 +136,7 @@ queue.add(2); queue.add(4); let result = queue.pop(); try { - queue.pop.bind({})(); + queue.pop.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -175,7 +174,7 @@ queue.add(5); queue.add(2); let result = queue.getFirst(); try { - queue.getFirst.bind({})(); + queue.getFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -227,7 +226,7 @@ queue.forEach((value, index) => { try { queue.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -276,7 +275,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - queue[Symbol.iterator].bind({})(); + queue[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md index 22f367d73a8c447c0123ae2600d6f52892b45c4e..cb945909331f089d2f98f384d7bfc9de65b28a5d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -35,7 +35,7 @@ publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number& **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -84,7 +84,7 @@ publishReminder(reminderReq: ReminderRequest): Promise<number> **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -126,7 +126,7 @@ cancelReminder(reminderId: number, callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -172,7 +172,7 @@ cancelReminder(reminderId: number): Promise<void> **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -210,7 +210,7 @@ getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -270,7 +270,7 @@ getValidReminders(): Promise<Array<ReminderRequest>> **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -328,7 +328,7 @@ cancelAllReminders(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -367,7 +367,7 @@ cancelAllReminders(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errcode-reminderAgentManager.md)错误码。 +以下错误码的详细介绍请参见[@ohos.reminderAgentManager (后台代理提醒)](../errorcodes/errorcode-reminderAgentManager.md)错误码。 | 错误码ID | 错误码信息 | | --------- | ------- | @@ -608,9 +608,9 @@ try { | actionButton | [ActionButton](#actionbutton) | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 | | wantAgent | [WantAgent](#wantagent) | 否 | 点击通知后需要跳转的目标ability信息。 | | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 | -| ringDuration | number | 否 | 指明响铃时长。 | +| ringDuration | number | 否 | 指明响铃时长(单位:秒)。 | | snoozeTimes | number | 否 | 指明延迟提醒次数。 | -| timeInterval | number | 否 | 执行延迟提醒间隔。 | +| timeInterval | number | 否 | 执行延迟提醒间隔(单位:秒)。 | | title | string | 否 | 指明提醒标题。 | | content | string | 否 | 指明提醒内容。 | | expiredContent | string | 否 | 指明提醒过期后需要显示的内容。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index 7a2a4623d5e4aab2f9f49985e87d25e2d00c09ab..fb3b971d29373fdadac3722b130b6a73c3b00945 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-request.md +++ b/zh-cn/application-dev/reference/apis/js-apis-request.md @@ -187,8 +187,8 @@ upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> url: 'https://patch', header: { key1: "value1", key2: "value2" }, method: "POST", - files: { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }, - data: { name: "name123", value: "123" }, + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], }; request.upload(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; @@ -264,7 +264,7 @@ uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> | Promise<[UploadTask](#uploadtask)> | 返回上传任务。 | **错误码:** -以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcode-request.md)。 | 错误码ID | 错误码信息 | | -------- | -------- | @@ -278,8 +278,8 @@ uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> url: 'https://patch', header: { key1: "value1", key2: "value2" }, method: "POST", - files: { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }, - data: { name: "name123", value: "123" }, + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], }; request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; @@ -308,7 +308,7 @@ uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&l | callback | AsyncCallback<[UploadTask](#uploadtask)> | 否 | 回调函数,异步返回UploadTask对象。 | **错误码:** -以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcode-request.md)。 | 错误码ID | 错误码信息 | | -------- | -------- | @@ -910,7 +910,7 @@ downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadT | Promise<[DownloadTask](#downloadtask)> | 返回下载任务。 | **错误码:** -以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcode-request.md)。 | 错误码ID | 错误码信息 | | -------- | -------- | @@ -949,7 +949,7 @@ downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallba | callback | AsyncCallback<[DownloadTask](#downloadtask)> | 否 | 下载接口的回调函数。 | **错误码:** -以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcode-request.md)。 | 错误码ID | 错误码信息 | | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md index b1ad40aa1b6748ad6a11598526aae234055b3a09..6e4cb79de19f291f726377d612f73ba1e2d232ce 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,6 +1,6 @@ # 资源管理 -资源管理模块,根据当前configuration(语言,区域,横竖屏,mccmnc)和device capability(设备类型,分辨率)提供获取应用资源信息读取接口。 +资源管理模块,根据当前configuration:语言、区域、横竖屏、Mcc(移动国家码)和Mnc(移动网络码)、Device capability(设备类型)、Density(分辨率)提供获取应用资源信息读取接口。 > **说明:** > @@ -16,9 +16,16 @@ import resourceManager from '@ohos.resourceManager'; ## 使用说明 从API Version9开始,Stage模型支持了通过context获取resourceManager对象的方式,再调用其内部获取资源的接口,无需再导入包,此方式FA模型不适用。 +Stage模型下Context的引用方法请参考[Stage模型的Context详细介绍](../../ability/context-userguide.md) ```ts -this.context.resourceManager; +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let resourceManager = context.resourceManager; + } +} ``` ## resourceManager.getResourceManager @@ -32,6 +39,7 @@ getResourceManager(callback: AsyncCallback<ResourceManager>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------------------- | | callback | AsyncCallback<[ResourceManager](#resourcemanager)> | 是 | callback方式返回ResourceManager对象 | @@ -65,6 +73,7 @@ getResourceManager(bundleName: string, callback: AsyncCallback<ResourceManage **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ----------------------------- | | bundleName | string | 是 | 指定应用的Bundle名称 | @@ -119,6 +128,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------ | ---- | ------------- | | bundleName | string | 是 | 指定应用的Bundle名称 | @@ -142,7 +152,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **系统能力**:SystemCapability.Global.ResourceManager -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | -------------------- | ---- | ---- | | DIRECTION_VERTICAL | 0 | 竖屏 | | DIRECTION_HORIZONTAL | 1 | 横屏 | @@ -154,7 +164,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **系统能力**:SystemCapability.Global.ResourceManager -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | -------------------- | ---- | ---- | | DEVICE_TYPE_PHONE | 0x00 | 手机 | | DEVICE_TYPE_TABLET | 0x01 | 平板 | @@ -170,7 +180,7 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **系统能力**:SystemCapability.Global.ResourceManager -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | -------------- | ---- | ---------- | | SCREEN_SDPI | 120 | 小规模的屏幕密度 | | SCREEN_MDPI | 160 | 中规模的屏幕密度 | @@ -186,8 +196,9 @@ getResourceManager(bundleName: string): Promise<ResourceManager> **系统能力**:SystemCapability.Global.ResourceManager +**参数:** -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | --------- | ----------------------- | ---- | ---- | -------- | | direction | [Direction](#direction) | 是 | 否 | 当前设备屏幕方向 | | locale | string | 是 | 否 | 当前系统语言 | @@ -209,8 +220,9 @@ resourceManager.getResourceManager((error, mgr) => { **系统能力**:SystemCapability.Global.ResourceManager +**参数:** -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ------------- | ------------------------------- | ---- | ---- | -------- | | screenDensity | [ScreenDensity](#screendensity) | 是 | 否 | 当前设备屏幕密度 | | deviceType | [DeviceType](#devicetype) | 是 | 否 | 当前设备类型 | @@ -232,11 +244,13 @@ resourceManager.getResourceManager((error, mgr) => { **系统能力:** SystemCapability.Global.ResourceManager -| 名称 | 类型 | 说明 | -| ------ | ------ | ------------------ | -| fd | number | rawfile的descriptor | -| offset | number | rawfile的起始偏移量 | -| length | number | rawfile的文件长度 | +**参数:** + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------------ | +| fd | number | 是 | 否 | rawfile的descriptor | +| offset | number | 是 | 否 | rawfile的起始偏移量 | +| length | number | 是 | 否 | rawfile的文件长度 | ## Resource9+ @@ -244,11 +258,13 @@ resourceManager.getResourceManager((error, mgr) => { **系统能力:** 以下各项对应的系统能力均为SystemCapability.Global.ResourceManager -| 名称 | 类型 | 说明 | -| ---------- | ------ | ----------- | -| bundleName | string | 应用的bundle名称 | -| moduleName | string | 应用的module名称 | -| id | number | 资源的id值 | +**参数:** + +| 名称 | 类型 | 可读 | 可写 |说明 | +| ---------- | ------ | ----- | ---- | ---------------| +| bundleName | string | 是 | 否 | 应用的bundle名称 | +| moduleName | string | 是 | 否 | 应用的module名称 | +| id | number | 是 | 否 | 资源的id值 | ## ResourceManager @@ -270,6 +286,7 @@ getStringValue(resId: number, callback: AsyncCallback<string>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------- | | resId | number | 是 | 资源ID值 | @@ -281,9 +298,9 @@ getStringValue(resId: number, callback: AsyncCallback<string>): void | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the module resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例Stage:** ```ts @@ -310,6 +327,7 @@ getStringValue(resId: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -321,11 +339,13 @@ getStringValue(resId: number): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -350,6 +370,7 @@ getStringValue(resource: Resource, callback: AsyncCallback<string>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -357,11 +378,13 @@ getStringValue(resource: Resource, callback: AsyncCallback<string>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -370,7 +393,7 @@ getStringValue(resource: Resource, callback: AsyncCallback<string>): void moduleName: "entry", id: $r('app.string.test').id }; - tyr { + try { this.context.resourceManager.getStringValue(resource, (error, value) => { if (error != null) { console.log("error is " + error); @@ -393,23 +416,26 @@ getStringValue(resource: Resource): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager -**参数:** +**参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | -**返回值:** +**返回值:** | 类型 | 说明 | | --------------------- | ---------------- | | Promise<string> | resource对象对应的字符串 | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -439,6 +465,7 @@ getStringArrayValue(resId: number, callback: AsyncCallback<Array<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------- | | resId | number | 是 | 资源ID值 | @@ -446,11 +473,13 @@ getStringArrayValue(resId: number, callback: AsyncCallback<Array<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -477,6 +506,7 @@ getStringArrayValue(resId: number): Promise<Array<string>> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -488,11 +518,13 @@ getStringArrayValue(resId: number): Promise<Array<string>> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -516,6 +548,7 @@ getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<stri **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -523,11 +556,13 @@ getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<stri 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -558,6 +593,7 @@ getStringArrayValue(resource: Resource): Promise<Array<string>> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -569,11 +605,13 @@ getStringArrayValue(resource: Resource): Promise<Array<string>> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -594,7 +632,7 @@ getStringArrayValue(resource: Resource): Promise<Array<string>> ``` -### getMediaContent +### getMediaContent9+ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void @@ -603,6 +641,7 @@ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------ | | resId | number | 是 | 资源ID值 | @@ -610,10 +649,12 @@ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts @@ -631,7 +672,7 @@ getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void ``` -### getMediaContent +### getMediaContent9+ getMediaContent(resId: number): Promise<Uint8Array> @@ -640,6 +681,7 @@ getMediaContent(resId: number): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -651,15 +693,17 @@ getMediaContent(resId: number): Promise<Uint8Array> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts try { - mgr.getMediaContent($r('app.media.test').id).then(value => { + this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => { let media = value; }).catch(error => { console.log("getMediaContent promise error is " + error); @@ -678,6 +722,7 @@ getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------ | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -685,10 +730,12 @@ getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts @@ -719,6 +766,7 @@ getMediaContent(resource: Resource): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -730,10 +778,12 @@ getMediaContent(resource: Resource): Promise<Uint8Array> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts @@ -754,7 +804,7 @@ getMediaContent(resource: Resource): Promise<Uint8Array> ``` -### getMediaContentBase64 +### getMediaContentBase649+ getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void @@ -763,6 +813,7 @@ getMediaContentBase64(resId: number, callback: AsyncCallback<string>): voi **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------ | | resId | number | 是 | 资源ID值 | @@ -770,15 +821,17 @@ getMediaContentBase64(resId: number, callback: AsyncCallback<string>): voi 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts try { - mgr.getMediaContentBase64($r('app.media.test').id, (error, value) => { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -791,7 +844,7 @@ getMediaContentBase64(resId: number, callback: AsyncCallback<string>): voi ``` -### getMediaContentBase64 +### getMediaContentBase649+ getMediaContentBase64(resId: number): Promise<string> @@ -800,6 +853,7 @@ getMediaContentBase64(resId: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -811,15 +865,17 @@ getMediaContentBase64(resId: number): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts try { - mgr.getMediaContentBase64($r('app.media.test').id).then(value => { + this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => { let media = value; }).catch(error => { console.log("getMediaContentBase64 promise error is " + error); @@ -837,7 +893,8 @@ getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>) **系统能力**:SystemCapability.Global.ResourceManager -**参数:** +**参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------ | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -845,10 +902,12 @@ getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>) 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts @@ -879,6 +938,7 @@ getMediaContentBase64(resource: Resource): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -890,10 +950,12 @@ getMediaContentBase64(resource: Resource): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | **示例:** ```ts @@ -923,6 +985,7 @@ getConfiguration(callback: AsyncCallback<Configuration>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------- | | callback | AsyncCallback<[Configuration](#configuration)> | 是 | 异步回调,用于返回设备的Configuration | @@ -977,6 +1040,7 @@ getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------- | | callback | AsyncCallback<[DeviceCapability](#devicecapability)> | 是 | 异步回调,用于返回设备的DeviceCapability | @@ -1022,7 +1086,7 @@ getDeviceCapability(): Promise<DeviceCapability> ``` -### getPluralStringValue +### getPluralStringValue9+ getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void @@ -1031,6 +1095,7 @@ getPluralStringValue(resId: number, num: number, callback: AsyncCallback<stri **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------- | | resId | number | 是 | 资源ID值 | @@ -1039,11 +1104,13 @@ getPluralStringValue(resId: number, num: number, callback: AsyncCallback<stri 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1061,7 +1128,7 @@ getPluralStringValue(resId: number, num: number, callback: AsyncCallback<stri ``` -### getPluralStringValue +### getPluralStringValue9+ getPluralStringValue(resId: number, num: number): Promise<string> @@ -1070,6 +1137,7 @@ getPluralStringValue(resId: number, num: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -1082,11 +1150,13 @@ getPluralStringValue(resId: number, num: number): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1110,6 +1180,7 @@ getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback< **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------------ | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -1118,11 +1189,13 @@ getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback< 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1154,6 +1227,7 @@ getPluralString(resource: Resource, num: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -1166,11 +1240,13 @@ getPluralString(resource: Resource, num: number): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1200,6 +1276,7 @@ getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ----------------------- | | path | string | 是 | rawfile文件路径 | @@ -1207,9 +1284,11 @@ getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001005 | If the resource not found by path. | **示例:** ```ts @@ -1236,6 +1315,7 @@ getRawFileContent(path: string): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1247,9 +1327,11 @@ getRawFileContent(path: string): Promise<Uint8Array> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001005 | If the resource not found by path. | **示例:** ```ts @@ -1274,16 +1356,19 @@ getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | 是 | rawfile文件路径 | -| callback | AsyncCallback<[getRawFd](#getrawfd9)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001005 | If the resource not found by path. | **示例:** ```ts @@ -1296,9 +1381,8 @@ getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void let offset = value.offset; let length = value.length; } - }); - } catch(error => { - console.log("getRawFd callback error is " + error); + }).catch(error => { + console.log("getRawFd callback error is " + error); }); ``` @@ -1311,6 +1395,7 @@ getRawFd(path: string): Promise<RawFileDescriptor> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1318,13 +1403,15 @@ getRawFd(path: string): Promise<RawFileDescriptor> **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------------- | -| Promise<[getRawFd](#getrawfd9-1)> | rawfile文件descriptor | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | rawfile文件descriptor | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001005 | If the resource not found by path. | **示例:** ```ts @@ -1350,6 +1437,7 @@ closeRawFileDescriptor(path: string, callback: AsyncCallback<void>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1375,6 +1463,7 @@ closeRawFileDescriptor(path: string): Promise<void> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1405,6 +1494,7 @@ closeRawFd(path: string, callback: AsyncCallback<void>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1412,6 +1502,8 @@ closeRawFd(path: string, callback: AsyncCallback<void>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | | 9001005 | The resource not found by path. | @@ -1419,7 +1511,7 @@ closeRawFd(path: string, callback: AsyncCallback<void>): void **示例:** ```ts try { - mgr.closeRawFd("test.xml", (error, value) => { + this.context.resourceManager.closeRawFd("test.xml", (error, value) => { if (error != null) { console.log("error is " + error); } @@ -1439,6 +1531,7 @@ closeRawFd(path: string): Promise<void> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -1450,14 +1543,16 @@ closeRawFd(path: string): Promise<void> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001005 | The resource not found by path. | +| 9001005 | If the resource not found by path. | **示例:** ```ts try { - mgr.closeRawFd("test.xml").then(value => { + this.context.resourceManager.closeRawFd("test.xml").then(value => { let result = value; }).catch(error => { console.log("closeRawFd promise error is " + error); @@ -1491,6 +1586,7 @@ getStringByName(resName: string, callback: AsyncCallback<string>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------- | | resName | string | 是 | 资源名称 | @@ -1498,11 +1594,13 @@ getStringByName(resName: string, callback: AsyncCallback<string>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1529,6 +1627,7 @@ getStringByName(resName: string): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1540,11 +1639,13 @@ getStringByName(resName: string): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1568,6 +1669,7 @@ getStringArrayByName(resName: string, callback: AsyncCallback<Array<string **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------- | | resName | string | 是 | 资源名称 | @@ -1575,11 +1677,13 @@ getStringArrayByName(resName: string, callback: AsyncCallback<Array<string 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1605,6 +1709,7 @@ getStringArrayByName(resName: string): Promise<Array<string>> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1616,11 +1721,13 @@ getStringArrayByName(resName: string): Promise<Array<string>> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1644,6 +1751,7 @@ getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------ | | resName | string | 是 | 资源名称 | @@ -1651,11 +1759,13 @@ getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1681,6 +1791,7 @@ getMediaByName(resName: string): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1692,11 +1803,13 @@ getMediaByName(resName: string): Promise<Uint8Array> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1720,6 +1833,7 @@ getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): vo **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------ | | resName | string | 是 | 资源名称 | @@ -1727,11 +1841,13 @@ getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): vo 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1757,6 +1873,7 @@ getMediaBase64ByName(resName: string): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1768,11 +1885,13 @@ getMediaBase64ByName(resName: string): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1796,6 +1915,7 @@ getPluralStringByName(resName: string, num: number, callback: AsyncCallback<s **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ----------------------------- | | resName | string | 是 | 资源名称 | @@ -1804,11 +1924,13 @@ getPluralStringByName(resName: string, num: number, callback: AsyncCallback<s 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1835,6 +1957,7 @@ getPluralStringByName(resName: string, num: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1847,11 +1970,13 @@ getPluralStringByName(resName: string, num: number): Promise<string> 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1875,6 +2000,7 @@ getStringSync(resId: number): string **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -1884,6 +2010,16 @@ getStringSync(resId: number): string | ------ | ----------- | | string | 资源ID值对应的字符串 | +以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 + +**错误码:** + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------- | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | + **示例:** ```ts try { @@ -1902,6 +2038,7 @@ getStringSync(resource: Resource): string **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -1913,11 +2050,13 @@ getStringSync(resource: Resource): string 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1942,6 +2081,7 @@ getStringByNameSync(resName: string): string **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -1953,11 +2093,13 @@ getStringByNameSync(resName: string): string 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -1977,6 +2119,7 @@ getBoolean(resId: number): boolean **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -1988,11 +2131,13 @@ getBoolean(resId: number): boolean 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2011,6 +2156,7 @@ getBoolean(resource: Resource): boolean **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -2022,11 +2168,13 @@ getBoolean(resource: Resource): boolean 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2051,6 +2199,7 @@ getBooleanByName(resName: string): boolean **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -2062,11 +2211,13 @@ getBooleanByName(resName: string): boolean 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2086,6 +2237,7 @@ getNumber(resId: number): number **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2097,11 +2249,13 @@ getNumber(resId: number): number 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2127,6 +2281,7 @@ getNumber(resource: Resource): number **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------- | ---- | ---- | | resource | [Resource](#resource9) | 是 | 资源信息 | @@ -2138,11 +2293,13 @@ getNumber(resource: Resource): number 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001001 | The resId invalid. | -| 9001002 | The resource not found by resId. | -| 9001006 | The resource re-ref too much. | +| 9001001 | If the resId invalid. | +| 9001002 | If the resource not found by resId. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2167,6 +2324,7 @@ getNumberByName(resName: string): number **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ------- | ------ | ---- | ---- | | resName | string | 是 | 资源名称 | @@ -2178,11 +2336,13 @@ getNumberByName(resName: string): number 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 +**错误码:** + | 错误码ID | 错误信息 | | -------- | ---------------------------------------- | -| 9001003 | The resName invalid. | -| 9001004 | The resource not found by resName. | -| 9001006 | The resource re-ref too much. | +| 9001003 | If the resName invalid. | +| 9001004 | If the resource not found by resName. | +| 9001006 | If the resource re-ref too much. | **示例:** ```ts @@ -2211,6 +2371,7 @@ getString(resId: number, callback: AsyncCallback<string>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | --------------- | | resId | number | 是 | 资源ID值 | @@ -2241,6 +2402,7 @@ getString(resId: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2273,6 +2435,7 @@ getStringArray(resId: number, callback: AsyncCallback<Array<string>> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------- | | resId | number | 是 | 资源ID值 | @@ -2303,6 +2466,7 @@ getStringArray(resId: number): Promise<Array<string>> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2335,6 +2499,7 @@ getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ------------------ | | resId | number | 是 | 资源ID值 | @@ -2365,6 +2530,7 @@ getMedia(resId: number): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2397,6 +2563,7 @@ getMediaBase64(resId: number, callback: AsyncCallback<string>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------ | | resId | number | 是 | 资源ID值 | @@ -2427,6 +2594,7 @@ getMediaBase64(resId: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2459,6 +2627,7 @@ getPluralString(resId: number, num: number): Promise<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | | resId | number | 是 | 资源ID值 | @@ -2492,6 +2661,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback<string> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------- | ---- | ------------------------------- | | resId | number | 是 | 资源ID值 | @@ -2523,6 +2693,7 @@ getRawFile(path: string, callback: AsyncCallback<Uint8Array>): void **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------- | ---- | ----------------------- | | path | string | 是 | rawfile文件路径 | @@ -2553,6 +2724,7 @@ getRawFile(path: string): Promise<Uint8Array> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | @@ -2585,6 +2757,7 @@ getRawFileDescriptor(path: string, callback: AsyncCallback<RawFileDescriptor& **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | 是 | rawfile文件路径 | @@ -2616,6 +2789,7 @@ getRawFileDescriptor(path: string): Promise<RawFileDescriptor> **系统能力**:SystemCapability.Global.ResourceManager **参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---- | ------ | ---- | ----------- | | path | string | 是 | rawfile文件路径 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 6d0e97241064cd8dd8ef07c78a0738f3371b083b..e9e9138c2d7c5b64df80b6745c90f69437010f0a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -26,7 +26,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen 后台应用申请延迟挂起。 -延迟挂起时间一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 +延迟挂起时间一般情况下默认值为3分钟,低电量(依据系统低电量广播)时默认值为1分钟。 **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -576,8 +576,8 @@ try { | LOCATION | 4 | 定位导航。 | | BLUETOOTH_INTERACTION | 5 | 蓝牙相关。 | | MULTI_DEVICE_CONNECTION | 6 | 多设备互联。 | -| WIFI_INTERACTION | 7 | WLAN相关
此接口为系统接口。 | -| VOIP | 8 | 音视频通话
此接口为系统接口。 | +| WIFI_INTERACTION | 7 | WLAN相关(此接口为系统接口)。 | +| VOIP | 8 | 音视频通话(此接口为系统接口)。 | | TASK_KEEPING | 9 | 计算任务(仅在特定设备生效)。 | ## EfficiencyResourcesRequest @@ -605,13 +605,13 @@ try { **系统API**: 此接口为系统接口。 -| 参数名 | 参数值 | 描述 | -| ----------------------- | ---- | --------------------- | -| CPU | 1 | CPU资源,申请后不被挂起。 | -| COMMON_EVENT | 2 | 公共事件,申请后挂起状态下不被代理掉。 | -| TIMER | 4 | 计时器,申请后挂起状态下不被代理掉。 | -| WORK_SCHEDULER | 8 | 延迟任务,申请后有更长的执行时间。 | -| BLUETOOTH | 16 | 蓝牙相关,申请后挂起状态下不被代理掉。 | -| GPS | 32 | GPS相关,申请后挂起状态下不被代理掉。 | -| AUDIO | 64 | 音频资源,申请后挂起状态下不被代理掉。 | +| 参数名 | 描述 | +| ----------------------- | --------------------- | +| CPU | CPU资源,申请后不被挂起。 | +| COMMON_EVENT | 公共事件,申请后挂起状态下不被代理掉。 | +| TIMER | 计时器,申请后挂起状态下不被代理掉。 | +| WORK_SCHEDULER | 延迟任务,申请后有更长的执行时间。 | +| BLUETOOTH | 蓝牙相关,申请后挂起状态下不被代理掉。 | +| GPS | GPS相关,申请后挂起状态下不被代理掉。 | +| AUDIO | 音频资源,申请后挂起状态下不被代理掉。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index 3b9a1ebbe44a3efd2051ae690f88ac7c7a7bb50b..b6bc46eae0e8acd671ce83cfab9859ba07f29e92 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -46,7 +46,7 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -93,7 +93,7 @@ isIdleState(bundleName: string): Promise<boolean> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -133,7 +133,7 @@ queryAppGroup(): Promise<number> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -175,7 +175,7 @@ queryAppGroup(callback: AsyncCallback<number>): void **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -225,7 +225,7 @@ queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback<Bun **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -285,7 +285,7 @@ queryBundleStatsInfos(begin: number, end: number): Promise<BundleStatsMap> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -339,7 +339,7 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -398,7 +398,7 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -449,7 +449,7 @@ queryBundleEvents(begin: number, end: number, callback: AsyncCallback<Array&l **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -507,7 +507,7 @@ queryBundleEvents(begin: number, end: number): Promise<Array<BundleEvents& **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -554,7 +554,7 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback< **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -608,7 +608,7 @@ queryCurrentBundleEvents(begin: number, end: number): Promise<Array<Bundle **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -657,7 +657,7 @@ queryModuleUsageRecords(): Promise<Array<HapModuleInfo>> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -707,7 +707,7 @@ queryModuleUsageRecords(callback: AsyncCallback<Array<HapModuleInfo>> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -764,7 +764,7 @@ queryModuleUsageRecords(maxNum: number): Promise<Array<HapModuleInfo>&g **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -814,7 +814,7 @@ queryModuleUsageRecords(maxNum: number, callback: AsyncCallback<Array<HapM **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -871,7 +871,7 @@ queryAppGroup(bundleName : string): Promise<number> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -920,7 +920,7 @@ queryAppGroup(bundleName : string, callback: AsyncCallback<number>): void **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -947,7 +947,6 @@ queryAppGroup(bundleName : string, callback: AsyncCallback<number>): void } catch (error) { console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); } -}); ``` ## usageStatistics.setAppGroup @@ -971,7 +970,7 @@ setAppGroup(bundleName: string, newGroup: GroupType): Promise<void> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -992,7 +991,7 @@ setAppGroup(bundleName: string, newGroup: GroupType): Promise<void> ```javascript let bundleName = "com.example.deviceUsageStatistics"; - let newGroup = bundleState.GroupType.ACTIVE_GROUP_DAILY; + let newGroup = usageStatistics.GroupType.DAILY_GROUP; try{ usageStatistics.setAppGroup(bundleName, newGroup).then( () => { @@ -1027,7 +1026,7 @@ setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback< **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1042,7 +1041,7 @@ setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback< ```javascript let bundleName = "com.example.deviceUsageStatistics"; - let newGroup = bundleState.GroupType.ACTIVE_GROUP_DAILY; + let newGroup = usageStatistics.GroupType.DAILY_GROUP; try{ usageStatistics.setAppGroup(bundleName, newGroup, (err) => { @@ -1077,7 +1076,7 @@ registerAppGroupCallBack(groupCallback: Callback<AppGroupCallbackInfo>): P **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1136,7 +1135,7 @@ registerAppGroupCallBack(groupCallback: Callback<AppGroupCallbackInfo>, ca **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1193,7 +1192,7 @@ unregisterAppGroupCallBack(): Promise<void> **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1237,7 +1236,7 @@ unregisterAppGroupCallBack(callback: AsyncCallback<void>): void; **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1290,7 +1289,7 @@ queryDeviceEventStats(begin: number, end: number): Promise<Array<DeviceEve **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1338,7 +1337,7 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Arr **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1393,7 +1392,7 @@ queryNotificationEventStats(begin: number, end: number): Promise<Array<Dev **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | @@ -1441,7 +1440,7 @@ queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback& **错误码**: -以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errcode-DeviceUsageStatistics.md)。 +以下错误码的详细介绍请参见[设备信息使用统计错误码](../errorcodes/errorcode-DeviceUsageStatistics.md)。 | 错误码ID | 错误信息 | | ---------- | ---------------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index f796d0fde9d0e8d20bc425c0b7b93b9ff47d544b..f2121dedb1f78979caf71a9784fd070e615c75e9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -437,45 +437,45 @@ isLastWorkTimeOut(workId: number): Promise\ **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler -| 名称 | 默认值 | 说明 | -| ---------------------- | ---- | ----------------------- | -| NETWORK_TYPE_ANY | 0 | 表示这个触发条件是任何类型的网络连接。 | -| NETWORK_TYPE_MOBILE | 1 | 表示这个触发条件是Mobile网络连接。 | -| NETWORK_TYPE_WIFI | 2 | 表示这个触发条件是Wifi类型的网络连接。 | -| NETWORK_TYPE_BLUETOOTH | 3 | 表示这个触发条件是Bluetooth网络连接。 | -| NETWORK_TYPE_WIFI_P2P | 4 | 表示这个触发条件是Wifi P2P网络连接。 | -| NETWORK_TYPE_ETHERNET | 5 | 表示这个触发条件是有线网络连接。 | +| 名称 | 说明 | +| ---------------------- | ----------------------- | +| NETWORK_TYPE_ANY | 表示这个触发条件是任何类型的网络连接。 | +| NETWORK_TYPE_MOBILE | 表示这个触发条件是Mobile网络连接。 | +| NETWORK_TYPE_WIFI | 表示这个触发条件是Wifi类型的网络连接。 | +| NETWORK_TYPE_BLUETOOTH | 表示这个触发条件是Bluetooth网络连接。 | +| NETWORK_TYPE_WIFI_P2P | 表示这个触发条件是Wifi P2P网络连接。 | +| NETWORK_TYPE_ETHERNET | 表示这个触发条件是有线网络连接。 | ## ChargingType 触发工作的充电类型。 **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler -| 名称 | 默认值 | 说明 | -| ------------------------- | ---- | -------------------- | -| CHARGING_PLUGGED_ANY | 0 | 表示这个触发条件是任何类型的充电器连接。 | -| CHARGING_PLUGGED_AC | 1 | 表示这个触发条件是直流充电器连接。 | -| CHARGING_PLUGGED_USB | 2 | 表示这个触发条件是USB充连接。 | -| CHARGING_PLUGGED_WIRELESS | 3 | 表示这个触发条件是无线充电器连接。 | +| 名称 | 说明 | +| ------------------------- | -------------------- | +| CHARGING_PLUGGED_ANY | 表示这个触发条件是任何类型的充电器连接。 | +| CHARGING_PLUGGED_AC | 表示这个触发条件是直流充电器连接。 | +| CHARGING_PLUGGED_USB | 表示这个触发条件是USB充连接。 | +| CHARGING_PLUGGED_WIRELESS | 表示这个触发条件是无线充电器连接。 | ## BatteryStatus 触发工作的电池状态。 **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler -| 名称 | 默认值 | 说明 | -| -------------------------- | ---- | -------------------------- | -| BATTERY_STATUS_LOW | 0 | 表示这个触发条件是低电告警。 | -| BATTERY_STATUS_OKAY | 1 | 表示这个触发条件是从低电恢复到正常电量。 | -| BATTERY_STATUS_LOW_OR_OKAY | 2 | 表示这个触发条件是从低电恢复到正常电量或者低电告警。 | +| 名称 | 说明 | +| -------------------------- | -------------------------- | +| BATTERY_STATUS_LOW | 表示这个触发条件是低电告警。 | +| BATTERY_STATUS_OKAY | 表示这个触发条件是从低电恢复到正常电量。 | +| BATTERY_STATUS_LOW_OR_OKAY | 表示这个触发条件是从低电恢复到正常电量或者低电告警。 | ## StorageRequest 触发工作的存储状态。 **系统能力**:SystemCapability.ResourceSchedule.WorkScheduler -| 名称 | 默认值 | 说明 | -| ------------------------- | ---- | ------------------------------ | -| STORAGE_LEVEL_LOW | 0 | 表示这个触发条件是存储空间不足。 | -| STORAGE_LEVEL_OKAY | 1 | 表示这个触发条件是从存储空间不足恢复到正常。 | -| STORAGE_LEVEL_LOW_OR_OKAY | 2 | 表示这个触发条件是从存储空间不足恢复到正常或者存储空间不足。 | \ No newline at end of file +| 名称 | 说明 | +| ------------------------- | ------------------------------ | +| STORAGE_LEVEL_LOW | 表示这个触发条件是存储空间不足。 | +| STORAGE_LEVEL_OKAY | 表示这个触发条件是从存储空间不足恢复到正常。 | +| STORAGE_LEVEL_LOW_OR_OKAY | 表示这个触发条件是从存储空间不足恢复到正常或者存储空间不足。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md index 17f1f4702f2feedf93d98c3690484a9d527137b9..4f674091308c1d77fc23dc6edc7229930653bf86 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,387 +1,369 @@ # 锁屏管理 -锁屏管理服务是OpenHarmony中系统服务,为锁屏应用提供注册亮屏、灭屏、开启屏幕、结束休眠、退出动画、请求解锁结果监听,并提供回调结果给锁屏应用。锁屏管理服务向三方应用提供请求解锁、查询锁屏状态、查询是否设置锁屏密码的能力。 +锁屏管理服务是OpenHarmony中的系统服务,为锁屏应用提供注册亮屏、灭屏、开启屏幕、结束休眠、退出动画、请求解锁结果监听,并提供回调结果给锁屏应用。锁屏管理服务向三方应用提供请求解锁、查询锁屏状态、查询是否设置锁屏密码的能力。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> **说明:** +> > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 - ```js import screenlock from '@ohos.screenLock'; ``` - ## screenlock.isScreenLocked isScreenLocked(callback: AsyncCallback<boolean>): void -判断屏幕是否锁屏,使用callback作为异步方法。 +判断屏幕是否锁屏,使用callback异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 -> -> 从 API version 7开始支持。 +> +>从 API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock **参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | 是 | 回调函数,返回true表示屏幕已锁屏,返回false表示屏幕未锁屏。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ----------------------------------------------------------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数,返回true表示屏幕已锁屏,返回false表示屏幕未锁屏。 | **示例:** - - ```js - screenlock.isScreenLocked((err, data)=>{ - if (err) { - console.error('isScreenLocked callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('isScreenLocked callback success data -> ${JSON.stringify(data)}'); - }); - ``` +```js +screenlock.isScreenLocked((err, data)=>{ + if (err) { + console.error('isScreenLocked callback error -> ${JSON.stringify(err)}'); + return; + } + console.info('isScreenLocked callback success data -> ${JSON.stringify(data)}'); +}); +``` ## screenlock.isScreenLocked isScreenLocked(): Promise<boolean> -判断屏幕是否锁屏,使用Promise作为异步方法。 +判断屏幕是否锁屏,使用Promise异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 -> -> 从 API version 7开始支持。 +> +> 从API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.isLocked9+](#screenlockislocked9)代替。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**返回值**: - - | 类型 | 说明 | - | -------- | -------- | - | Promise<boolean> | 以Promise形式返回结果。 | +**返回值:** -**示例**: +| 类型 | 说明 | +| ---------------------- | ------------------------------------------- | +| Promise<boolean> | Promise对象,返回判断结果。返回true表示屏幕已锁屏,返回false表示屏幕未锁屏。 | - ```js - screenlock.isScreenLocked().then((data) => { - console.log('isScreenLocked success: data -> ${JSON.stringify(data)}'); - }).catch((err) => { - console.error('isScreenLocked fail, promise: err -> ${JSON.stringify(err)}'); - }); - ``` +**示例:** +```js +screenlock.isScreenLocked().then((data) => { + console.log('isScreenLocked success: data -> ${JSON.stringify(data)}'); +}).catch((err) => { + console.error('isScreenLocked fail, promise: err -> ${JSON.stringify(err)}'); +}); +``` ## screenlock.isLocked9+ -isLocked(): boolean; +isLocked(): boolean 判断屏幕是否锁屏,使用同步方法。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**返回值**: - - | 类型 | 说明 | - | -------- | -------- | - | boolean | 返回true表示当前屏幕已锁定,返回false表示当前屏幕未锁定。 | +**返回值:** -**示例**: +| 类型 | 说明 | +| ------- | ------------------------------------------------- | +| boolean | 返回true表示屏幕已锁屏,返回false表示屏幕未锁屏。 | - ```js - var isLocked = screenlock.isLocked(); - ``` +**示例:** +```js +let isLocked = screenlock.isLocked(); +``` ## screenlock.isSecureMode isSecureMode(callback: AsyncCallback<boolean>): void -判断设备是否处于安全模式下,使用callback作为异步方法。 +判断设备是否处于安全模式下,使用callback异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 -> -> 从 API version 7开始支持。 +> +> 从 API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**参数**: +**参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示屏幕处于安全模式下,返回false表示屏幕当前不在安全模式下。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ------------------------ | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示屏幕处于安全模式下,返回false表示屏幕当前不在安全模式下。 | -**示例**: - - ```js - screenlock.isSecureMode((err, data)=>{ - if (err) { - console.error('isSecureMode callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('isSecureMode callback success data -> ${JSON.stringify(err)}'); - }); - ``` +**示例:** +```js +screenlock.isSecureMode((err, data)=>{ + if (err) { + console.error('isSecureMode callback error -> ${JSON.stringify(err)}'); + return; + } + console.info('isSecureMode callback success data -> ${JSON.stringify(err)}'); +}); +``` ## screenlock.isSecureMode isSecureMode(): Promise<boolean> -判断设备是否处于安全模式下,使用Promise作为异步方法。 +判断设备是否处于安全模式下,使用Promise异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 -> -> 从 API version 7开始支持。 - -**系统能力**: SystemCapability.MiscServices.ScreenLock +> +> 从 API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.isSecure9+](#screenlockissecure9)代替。 -**返回值**: +**系统能力:** SystemCapability.MiscServices.ScreenLock - | 类型 | 说明 | - | -------- | -------- | - | Promise<boolean> | 以Promise形式返回结果。 | +**返回值:** -**示例**: +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示屏幕处于安全模式下,返回false表示屏幕当前不在安全模式下。 | - ```js - screenlock.isSecureMode().then((data) => { - console.log('isSecureMode success: data->${JSON.stringify(data)}'); - }).catch((err) => { - console.error('isSecureMode fail, promise: err->${JSON.stringify(err)}'); - }); - ``` +**示例:** +```js +screenlock.isSecureMode().then((data) => { + console.log('isSecureMode success: data->${JSON.stringify(data)}'); +}).catch((err) => { + console.error('isSecureMode fail, promise: err->${JSON.stringify(err)}'); +}); +``` ## screenlock.isSecure9+ -isSecure(): boolean; - -判断设备是否处于安全模式下,使用同步方法。 +isSecure(): boolean -**系统能力**: SystemCapability.MiscServices.ScreenLock +判断设备是否处于安全模式下。 -**返回值**: +**系统能力:** SystemCapability.MiscServices.ScreenLock - | 类型 | 说明 | - | -------- | -------- | - | boolean | 返回true表示屏幕处于安全模式下,返回false表示屏幕当前不在安全模式下。 | +**返回值:** -**示例**: +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示屏幕处于安全模式下,返回false表示屏幕当前不在安全模式下。 | - ```js - var isSecure = screenlock.isSecure(); - ``` +**示例:** +```js +let isSecure = screenlock.isSecure(); +``` ## screenlock.unlockScreen unlockScreen(callback: AsyncCallback<void>): void -解锁屏幕,使用callback作为异步方法。 +解锁屏幕,使用callback异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 -> -> 从 API version 7开始支持。 +> +> 从 API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**参数**: +**参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 回调函数,失败时返回错误信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | --------------- | +| callback | AsyncCallback<void> | 是 | 回调函数,失败时返回错误信息。 | -**示例**: - - ```js - screenlock.unlockScreen((err) => { - if (err) { - console.error('unlockScreen callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('unlockScreen callback success'); - }); - ``` +**示例:** +```js +screenlock.unlockScreen((err) => { + if (err) { + console.error('unlockScreen callback error -> ${JSON.stringify(err)}'); + return; + } + console.info('unlockScreen callback success'); +}); +``` ## screenlock.unlockScreen unlockScreen(): Promise<void> -解锁屏幕,使用Promise作为异步方法。 +解锁屏幕,使用Promise异步回调。 > **说明:** -> 从API version 9开始废弃。建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 -> -> 从 API version 7开始支持。 +> +> 从 API version 7开始支持,从API version 9开始废弃。建议使用[screenlock.unlock9+](#screenlockunlock9)代替。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**返回值**: +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | 以Promise形式返回结果。 | +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | -**示例**: - - ```js - screenlock.unlockScreen().then(() => { - console.log('unlockScreen success'); - }).catch((err) => { - console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}'); - }); - ``` +**示例:** +```js +screenlock.unlockScreen().then(() => { + console.log('unlockScreen success'); +}).catch((err) => { + console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}'); +}); +``` ## screenlock.unlock9+ unlock(callback: AsyncCallback<boolean>): void -解锁屏幕,使用callback作为异步方法。 +解锁屏幕,使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**参数**: +**参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 回调函数。返回true表示屏幕解锁成功,返回false表示屏幕解锁失败。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ------------------------- | +| callback | AsyncCallback<void> | 是 | 回调函数。返回true表示屏幕解锁成功,返回false表示屏幕解锁失败。 | -**示例**: - - ```js - screenlock.unlock((err,data) => { - if (err) { - console.error('unlock error -> ${JSON.stringify(err)}'); - return; - } - console.info('unlock success data -> ${JSON.stringify(data)}'); - }); - ``` +**示例:** +```js +screenlock.unlock((err,data) => { + if (err) { + console.error('unlock error -> ${JSON.stringify(err)}'); + return; + } + console.info('unlock success data -> ${JSON.stringify(data)}'); +}); +``` ## screenlock.unlock9+ unlock(): Promise<boolean> -解锁屏幕,使用Promise作为异步方法。 +解锁屏幕,使用Promise异步回调。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**返回值**: +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | 以Promise形式返回结果。 | +| 类型 | 说明 | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise对象。返回true表示屏幕解锁成功,返回false表示屏幕解锁失败。 | -**示例**: - - ```js - screenlock.unlock().then((data) => { - console.log('unlock success'); - }).catch((err) => { - console.error('unlock fail, : err->${JSON.stringify(err)}'); - }); - ``` +**示例:** +```js +screenlock.unlock().then((data) => { + console.log('unlock success'); +}).catch((err) => { + console.error('unlock fail, : err->${JSON.stringify(err)}'); +}); +``` ## screenlock.lock9+ lock(callback: AsyncCallback<boolean>): void -锁定屏幕,使用callback作为异步方法。 +锁定屏幕,使用callback异步回调。 + +**系统能力:** SystemCapability.MiscServices.ScreenLock -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 -**系统接口**:此接口为系统接口,三方应用不支持调用。 +**参数:** -**参数**: +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示屏幕锁定成功,返回false表示屏幕锁定失败。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | 是 | 回调函数。返回true表示屏幕锁定成功,返回false表示屏幕锁定失败。 | +**示例:** -**示例**: - - ```js - screenlock.lock((err) => { - if (err) { - console.error('lock callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('lock callback success'); - }); - ``` +```js +screenlock.lock((err,data) => { + if (err) { + console.error('lock callback error -> ${JSON.stringify(err)}'); + return; + } + console.info('lock callback success'); +}); +``` ## screenlock.lock9+ lock(): Promise<boolean> -锁定屏幕,使用Promise作为异步方法。 +锁定屏幕,使用Promise异步回调。 + +**系统能力:** SystemCapability.MiscServices.ScreenLock -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 -**系统接口**:此接口为系统接口,三方应用不支持调用。 +**返回值:** -**返回值**: +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回true表示屏幕锁定成功,返回false表示屏幕锁定失败。 | - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | 以Promise形式返回结果。 | +**示例:** -**示例**: - - ```js - screenlock.lock().then(() => { - console.log('lock success'); - }).catch((err) => { - console.error('lock fail, promise: err->${JSON.stringify(err)}'); - }); - ``` +```js +screenlock.lock().then((data) => { + console.log('lock success'); +}).catch((err) => { + console.error('lock fail, promise: err->${JSON.stringify(err)}'); +}); +``` ## EventType 定义系统事件类型。 -**系统能力**: SystemCapability.MiscServices.ScreenLock - - | 名称 | 说明 | - | -------- | -------- | - | beginWakeUp | 表示事件开始时开始唤醒。 | - | endWakeUp | 表示事件结束时结束唤醒。 | - | beginScreenOn | 表示事件开始时开始亮屏。 | - | endScreenOn | 表示事件结束时结束亮屏。 | - | beginScreenOff | 表示事件开始时开始灭屏。 | - | endScreenOff | 表示事件结束时结束灭屏。 | - | unlockScreen | 表示请求解锁屏幕。 | - | lockScreen | 表示请求锁定屏幕。 | - | beginExitAnimation | 表示动画开始退场。 | - | beginSleep | 表示开始休眠。 | - | endSleep | 表示结束休眠。 | - | changeUser | 表示切换用户。 | - | screenlockEnabled | 表示锁屏是否启用。 | - | serviceRestart | 表示锁屏服务进行重启。 | +**系统能力:** SystemCapability.MiscServices.ScreenLock + +| 名称 | 说明 | +| ------------------ | ------------------------ | +| beginWakeUp | 表示事件开始时开始唤醒。 | +| endWakeUp | 表示事件结束时结束唤醒。 | +| beginScreenOn | 表示事件开始时开始亮屏。 | +| endScreenOn | 表示事件结束时结束亮屏。 | +| beginScreenOff | 表示事件开始时开始灭屏。 | +| endScreenOff | 表示事件结束时结束灭屏。 | +| unlockScreen | 表示请求解锁屏幕。 | +| lockScreen | 表示请求锁定屏幕。 | +| beginExitAnimation | 表示动画开始退场。 | +| beginSleep | 表示开始休眠。 | +| endSleep | 表示结束休眠。 | +| changeUser | 表示切换用户。 | +| screenlockEnabled | 表示锁屏是否启用。 | +| serviceRestart | 表示锁屏服务进行重启。 | ## SystemEvent 定义系统事件回调参数结构。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock - | 名称 | 说明 | - | -------- | -------- | - | eventType | 系统事件类型。 | - | params | 系统事件的事件参数。 | +| 名称 | 说明 | +| --------- | -------------------- | +| eventType | 系统事件类型。 | +| params | 系统事件的事件参数。 | ## screenlock.onSystemEvent9+ @@ -389,89 +371,86 @@ onSystemEvent(callback: Callback\): boolean 注册锁屏相关的系统事件。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**系统接口**:此接口为系统接口,三方应用不支持调用。 +**系统接口**:此接口为系统接口。 -**参数**: +**参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | Callback\ | 是 | 锁屏相关的系统事件回调函数 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ---------------------------- | +| callback | Callback\<[SystemEvent](#systemevent)> | 是 | 锁屏相关的系统事件回调函数。 | **返回值:** - | 类型 | 说明 | - | ------- | -------------------------------------------- | - | boolean | 返回true表示锁屏系统事件注册成功,否则返回false| - -**示例**: - - ```js - let isSuccess = screenlock.onSystemEvent((err, event)=>{ - console.log(`onSystemEvent:callback:${event.eventType}`) - if (err) { - console.log(`onSystemEvent callback error -> ${JSON.stringify(err)}`); - } - }); - if (!isSuccess) { - console.log(`onSystemEvent result is false`) - } - ``` +| 类型 | 说明 | +| ------- | ------------------------------------------------- | +| boolean | 返回true表示锁屏系统事件注册成功,否则返回false。 | + +**示例:** + +```js +let isSuccess = screenlock.onSystemEvent((event)=>{ + console.log(`onSystemEvent:callback:${event.eventType}`) +}); +if (!isSuccess) { + console.log(`onSystemEvent result is false`) +} +``` ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback\): void +sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback\): void -应用发送事件到锁屏服务,异步方法。 +应用发送事件到锁屏服务,使用callback异步回调。 -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统能力:** SystemCapability.MiscServices.ScreenLock -**系统接口**:此接口为系统接口,三方应用不支持调用。 +**系统接口**:此接口为系统接口。 -**参数**: +**参数:** - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "screenDrawDone",表示屏幕绘制完成。 | - | parameter | number | 是 | 解锁状态。
- parameter为0,表示解锁成功。
- parameter为1,表示解锁失败。
- parameter为2,表示解锁取消。 | - | callback | AsyncCallback\ | 是 | 表示执行结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------ | ---- | -------------------- | +| event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "screenDrawDone",表示屏幕绘制完成。 | +| parameter | number | 是 | 解锁状态。
- parameter为0,表示解锁成功。
- parameter为1,表示解锁失败。
- parameter为2,表示解锁取消。 | +| callback | AsyncCallback\ | 是 | 回调函数,返回执行的结果。true表示执行成功,false表示执行失败。 | -**示例**: - - ```js - screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { - console.log('sending result:' + result); - }); - ``` +**示例:** + +```js +screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { + console.log('sending result:' + result); +}); +``` ## screenlock.sendScreenLockEvent9+ -sendScreenLockEvent(event: String, parameter: number): Promise\ +sendScreenLockEvent(event: String, parameter: number): Promise\ + +应用发送事件到锁屏服务,使用Promise异步回调。 -应用发送事件到锁屏服务,异步方法。 +**系统能力:** SystemCapability.MiscServices.ScreenLock -**系统能力**: SystemCapability.MiscServices.ScreenLock +**系统接口**:此接口为系统接口。 -**系统接口**:此接口为系统接口,三方应用不支持调用。 +**参数:** -**参数**: +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------------------------------------- | +| event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "screenDrawDone",表示屏幕绘制完成。 | +| parameter | number | 是 | 解锁状态。
- parameter为0,表示解锁成功。
- parameter为1,表示解锁失败。
- parameter为2,表示解锁取消。 | - | 参数名 | 类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | event | String | 是 | 事件类型,支持如下取值:
- "unlockScreenResult",表示解锁结果。
- "screenDrawDone",表示屏幕绘制完成。 | - | parameter | number | 是 | 解锁状态。
- parameter为0,表示解锁成功。
- parameter为1,表示解锁失败。
- parameter为2,表示解锁取消。 | +**返回值:** -**返回值**: +| 类型 | 说明 | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回执行的结果。true表示执行成功,false表示执行失败。 | - | 类型 | 说明 | - | -------- | -------- | - | Promise\ | 以Promise形式返回执行结果。 | +**示例:** -**示例**: - - ```js - screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => { - console.log('sending result:' + result); - }); - ``` +```js +screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => { + console.log('sending result:' + result); +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index de9ec2ae2b856bbf0f36bb7a98e41d90f0f584b1..b84278e0b8a1e335580d3686b760cfda81acbbdc 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -1,15 +1,6 @@ # 传感器 -sensor模块提供订阅传感器数据基本能力,包括订阅、取消订阅传感器数据,获取传感器列表,以及通用的传感器算法接口如通过气压值计算海拔高度、通过旋转矩阵计算设备方向等。 - -传感器是指用于侦测环境中所发生事件或变化,并将此消息发送至其他电子设备(如中央处理器)的设备,通常由敏感组件和转换组件组成。传感器是实现物联网智能化的重要基石,为实现全场景智慧化战略,支撑“1+8+N”产品需求,需要构筑统一的传感器管理框架,达到为各产品/业务提供低时延、低功耗的感知数据的目的。根据用途可分为以下六大类: - -- 运动类:加速度、陀螺仪、重力、线性加速度传感器等 -- 姿态类:旋转矢量、方向传感器等 -- 环境类:磁力计、气压、湿度传感器等 -- 光线类:环境光、接近光、色温传感器等 -- 健康类:心率、心跳传感器等 -- 其它:霍尔传感器、手握传感器等 +sensor模块提供了获取传感器数据的能力,包括获取传感器属性列表,订阅传感器数据,以及一些通用的传感器算法。 > **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -27,19 +18,19 @@ import sensor from '@ohos.sensor'; on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>,options?: Options): void -订阅加速度计传感器数据。 +订阅加速度传感器数据。 -**需要权限**:ohos.permission.ACCELEROMETER +**需要权限**:ohos.permission.ACCELEROMETER **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的加速度传感器类型为 ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -53,13 +44,13 @@ on(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse> ```js try { - sensor.on(sensor.SensorId.ACCELEROMETER,function(data){ + sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -67,7 +58,7 @@ try { on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>,options?: Options): void -订阅未校准的加速度计传感器数据。 +订阅未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -77,9 +68,9 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准加速度传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).ACCELEROMETER_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -93,16 +84,16 @@ on(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Acceleromete ```js try { - sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED,function(data){ + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -116,11 +107,11 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | -| type | [SensorId](#sensorid9) | 是 | 要订阅的环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | --------------------------------------------------- | +| type | [SensorId](#sensorid9).AMBIENT_LIGHT | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LightResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -134,11 +125,11 @@ on(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>, option ```js try { - sensor.on(sensor.SensorId.AMBIENT_LIGHT,function(data){ - console.info('Illumination: ' + data.intensity); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('The ambient light intensity: ' + data.intensity); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -146,7 +137,7 @@ try { on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>,options?: Options): void -订阅环境温度传感器数据。 +订阅温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -154,9 +145,9 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).AMBIENT_TEMPERATURE | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AmbientTemperatureResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -170,11 +161,11 @@ on(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureR ```js try { - sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE,function(data){ - console.info('Temperature: ' + data.temperature); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Temperature: ' + data.temperature); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -188,11 +179,11 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).BAROMETER | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为BarometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -206,11 +197,11 @@ on(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>, option ```js try { - sensor.on(sensor.SensorId.BAROMETER,function(data){ - console.info('Atmospheric pressure: ' + data.pressure); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.BAROMETER, function (data) { + console.info('Atmospheric pressure: ' + data.pressure); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -224,11 +215,11 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | -| type | [SensorId](#sensorid9) | 是 | 要订阅的重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------- | +| type | [SensorId](#sensorid9).GRAVITY | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GravityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -242,13 +233,13 @@ on(type: SensorId.GRAVITY, callback: Callback<GravityResponse>,options?: O ```js try { - sensor.on(sensor.SensorId.GRAVITY,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -264,11 +255,11 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 返回注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).GYROSCOPE | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -282,13 +273,13 @@ on(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>,options ```js try { - sensor.on(sensor.SensorId.GYROSCOPE,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -297,7 +288,7 @@ try { on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>, options?: Options): void -订阅未经校准的陀螺仪传感器数据 +订阅未校准陀螺仪传感器数据 **需要权限**:ohos.permission.GYROSCOPE @@ -307,9 +298,9 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).GYROSCOPE_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -323,16 +314,16 @@ on(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalib ```js try { - sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -346,11 +337,11 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | -------------------------------------------------- | +| type | [SensorId](#sensorid9).HALL | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HallResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -364,11 +355,11 @@ on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Option ```js try { - sensor.on(sensor.SensorId.HALL,function(data){ - console.info('Status: ' + data.status); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, function (data) { + console.info('Hall status: ' + data.status); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -384,11 +375,11 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).HEART_RATE | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HeartRateResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -402,11 +393,11 @@ on(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>,option ```js try { - sensor.on(sensor.SensorId.HEART_RATE,function(data){ + sensor.on(sensor.SensorId.HEART_RATE, function (data) { console.info('Heart rate: ' + data.heartRate); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -420,11 +411,11 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------ | +| type | [SensorId](#sensorid9).HUMIDITY | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HumidityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -438,11 +429,11 @@ on(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>,options?: ```js try { - sensor.on(sensor.SensorId.HUMIDITY,function(data){ - console.info('Humidity: ' + data.humidity); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, function (data) { + console.info('Humidity: ' + data.humidity); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -461,9 +452,9 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的线性加速度传感器类型为LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).LINEAR_ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELEROMETER。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LinearAccelerometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -477,13 +468,13 @@ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAcceleromete ```js try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -491,17 +482,17 @@ try { on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>,options?: Options): void -订阅磁场传感器数据。 +订阅地磁传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -515,13 +506,13 @@ on(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse> ```js try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -529,7 +520,7 @@ try { on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void -订阅未校准的磁场传感器数据 +订阅未校准地磁传感器数据 **系统能力**:SystemCapability.Sensors.Sensor @@ -537,9 +528,9 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldUncalibratedResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -553,16 +544,16 @@ on(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFie ```js try { - sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -570,7 +561,7 @@ try { on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,options?: Options): void -订阅定向传感器数据。 +订阅方向传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -584,23 +575,23 @@ on(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>,opt **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | [SensorId](#sensorid9).ORIENTATION | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 回调函数,异步上报的传感器数据固定为OrientationResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **示例:** ```js try { - sensor.on(sensor.SensorId.ORIENTATION,function(data){ - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, function (data) { + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -624,21 +615,21 @@ on(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>, option **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).PEDOMETER | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **示例:** ```js try { - sensor.on(sensor.SensorId.PEDOMETER,function(data){ - console.info('Steps: ' + data.steps); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, function (data) { + console.info('Step count: ' + data.steps); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -647,7 +638,7 @@ try { on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>, options?: Options): void -订阅计步器检测传感器数据。 +订阅计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -657,9 +648,9 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerDetectionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -673,11 +664,11 @@ on(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionR ```js try { - sensor.on(sensor.SensorId.PEDOMETER_DETECTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, function (data) { + console.info('Pedometer scalar: ' + data.scalar); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -685,17 +676,17 @@ try { on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, options?: Options): void -订阅接近传感器数据。 +订阅接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).PROXIMITY | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为ProximityResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -709,11 +700,11 @@ on(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>, option ```js try { - sensor.on(sensor.SensorId.PROXIMITY,function(data){ - console.info('Distance: ' + data.distance); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, function (data) { + console.info('Distance: ' + data.distance); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -730,9 +721,9 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).ROTATION_VECTOR | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 回调函数,异步上报的传感器数据固定为RotationVectorResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -746,14 +737,14 @@ on(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse& ```js try { - sensor.on(sensor.SensorId.ROTATION_VECTOR,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -762,7 +753,7 @@ try { on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>, options?: Options): void -订阅重要的运动传感器数据。 +订阅大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -770,9 +761,9 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的大幅动作传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为SignificantMotionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -786,11 +777,11 @@ on(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionRes ```js try { - sensor.on(sensor.SensorId.SIGNIFICANT_MOTION,function(data){ - console.info('Scalar data: ' + data.scalar); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Scalar data: ' + data.scalar); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -805,11 +796,11 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要订阅的佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).WEAR_DETECTION | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为WearDetectionResponse。 | +| options | [Options](#options) | 否 | 设置上报频率,默认值为200000000ns。 | **错误码**: @@ -823,11 +814,11 @@ on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse> ```js try { - sensor.on(sensor.SensorId.WEAR_DETECTION,function(data){ - console.info('Wear status: ' + data.value); - }, {interval: 10000000} ); -} catch(err) { - console.info('on fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info('Wear status: ' + data.value); + }, { interval: 10000000 }); +} catch (err) { + console.error('On fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -837,7 +828,7 @@ try { once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse>): void -订阅一次加速度计传感器数据。 +获取一次加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -845,10 +836,10 @@ once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse&g **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 加速度传感器类型为ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册一次加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerResponse。 | **错误码**: @@ -862,14 +853,13 @@ once(type: SensorId.ACCELEROMETER, callback: Callback<AccelerometerResponse&g ```js try { - sensor.once(sensor.SensorId.ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -877,7 +867,7 @@ try { once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<AccelerometerUncalibratedResponse>): void -订阅一次未校准的加速度计传感器数据。 +获取一次未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -887,8 +877,8 @@ once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Accelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准加速度传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册一次未校准加速度传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| type | [SensorId](#sensorid9).ACCELEROMETER_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AccelerometerUncalibratedResponse。 | **错误码**: @@ -902,17 +892,16 @@ once(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback: Callback<Accelerome ```js try { - sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -920,16 +909,16 @@ try { once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): void -订阅环境光传感器数据一次。 +获取一次环境光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册一次环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------- | ---- | --------------------------------------------------- | +| type | [SensorId](#sensorid9).AMBIENT_LIGHT | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LightResponse。 | **错误码**: @@ -943,12 +932,11 @@ once(type: SensorId.AMBIENT_LIGHT, callback: Callback<LightResponse>): voi ```js try { - sensor.once(sensor.SensorId.AMBIENT_LIGHT, function(data) { - console.info('Illumination: ' + data.intensity); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_LIGHT, function (data) { + console.info('The ambient light intensity: ' + data.intensity); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -956,7 +944,7 @@ try { once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatureResponse>): void -一次订阅环境温度传感器数据。 +获取一次温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -964,8 +952,8 @@ once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatur | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册一次环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| type | [SensorId](#sensorid9).AMBIENT_TEMPERATURE | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 回调函数,异步上报的传感器数据固定为AmbientTemperatureResponse。 | **错误码**: @@ -979,12 +967,11 @@ once(type: SensorId.AMBIENT_TEMPERATURE, callback: Callback<AmbientTemperatur ```js try { - sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function(data) { - console.info('Temperature: ' + data.temperature); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.AMBIENT_TEMPERATURE, function (data) { + console.info('Temperature: ' + data.temperature); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -992,16 +979,16 @@ try { once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): void -订阅一次气压计传感器数据。 +获取一次气压计传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册一次气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).BAROMETER | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为BarometerResponse。 | **错误码**: @@ -1015,12 +1002,11 @@ once(type: SensorId.BAROMETER, callback: Callback<BarometerResponse>): voi ```js try { - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function (data) { + console.info('Atmospheric pressure: ' + data.pressure); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1028,16 +1014,16 @@ try { once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void -订阅一次重力传感器数据。 +获取一次重力传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册一次重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------- | +| type | [SensorId](#sensorid9).GRAVITY | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GravityResponse。 | **错误码**: @@ -1051,14 +1037,13 @@ once(type: SensorId.GRAVITY, callback: Callback<GravityResponse>): void ```js try { - sensor.once(sensor.SensorId.GRAVITY, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GRAVITY, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1066,7 +1051,7 @@ try { once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): void -订阅一次陀螺仪传感器数据。 +获取一次陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1074,10 +1059,10 @@ once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): voi **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册一次陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).GYROSCOPE | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeResponse。 | **错误码**: @@ -1091,14 +1076,13 @@ once(type: SensorId.GYROSCOPE, callback: Callback<GyroscopeResponse>): voi ```js try { - sensor.once(sensor.SensorId.GYROSCOPE, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.GYROSCOPE, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1106,7 +1090,7 @@ try { once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncalibratedResponse>): void -一次订阅未校准的陀螺仪传感器数据。 +获取一次未校准陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1116,8 +1100,8 @@ once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册一次未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| type | [SensorId](#sensorid9).GYROSCOPE_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为GyroscopeUncalibratedResponse。 | **错误码**: @@ -1131,17 +1115,16 @@ once(type: SensorId.GYROSCOPE_UNCALIBRATED, callback: Callback<GyroscopeUncal ```js try { - sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function(data) { + sensor.once(sensor.SensorId.GYROSCOPE_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1149,16 +1132,16 @@ try { once(type: SensorId.HALL, callback: Callback<HallResponse>): void -订阅一次霍尔传感器数据。 +获取霍尔传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册一次霍尔传感器的回调函数,上报的数据类型为HallResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | -------------------------------------------------- | +| type | [SensorId](#sensorid9).HALL | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HallResponse。 | **错误码**: @@ -1172,12 +1155,11 @@ once(type: SensorId.HALL, callback: Callback<HallResponse>): void ```js try { - sensor.once(sensor.SensorId.HALL, function(data) { + sensor.once(sensor.SensorId.HALL, function (data) { console.info('Status: ' + data.status); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1185,7 +1167,7 @@ try { once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): void -订阅一次心率传感器数据。 +获取一次心率传感器数据。 **需要权限**:ohos.permission.READ_HEALTH_DATA @@ -1193,10 +1175,10 @@ once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): vo **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).HEART_RATE | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HeartRateResponse。 | **错误码**: @@ -1210,12 +1192,11 @@ once(type: SensorId.HEART_RATE, callback: Callback<HeartRateResponse>): vo ```js try { - sensor.once(sensor.SensorId.HEART_BEAT_RATE, function(data) { + sensor.once(sensor.SensorId.HEART_BEAT_RATE, function (data) { console.info('Heart rate: ' + data.heartRate); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1223,16 +1204,16 @@ try { once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void -订阅一次湿度传感器数据。 +获取一次湿度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册一次湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------ | +| type | [SensorId](#sensorid9).HUMIDITY | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为HumidityResponse。 | **错误码**: @@ -1246,12 +1227,11 @@ once(type: SensorId.HUMIDITY, callback: Callback<HumidityResponse>): void ```js try { - sensor.once(sensor.SensorId.HUMIDITY, function(data) { + sensor.once(sensor.SensorId.HUMIDITY, function (data) { console.info('Humidity: ' + data.humidity); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1259,7 +1239,7 @@ try { once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void -订阅一次线性加速度传感器数据。 +获取一次线性加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1269,8 +1249,8 @@ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 线性加速度传感器类型为LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| type | [SensorId](#sensorid9).LINEAR_ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELEROMETER。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为LinearAccelerometerResponse。 | **错误码**: @@ -1284,14 +1264,13 @@ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerome ```js try { - sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function(data) { + sensor.once(sensor.SensorId.LINEAR_ACCELEROMETER, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1299,16 +1278,16 @@ try { once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse>): void -订阅一次磁场传感器数据。 +获取一次磁场传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册一次磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldResponse。 | **错误码**: @@ -1322,14 +1301,13 @@ once(type: SensorId.MAGNETIC_FIELD, callback: Callback<MagneticFieldResponse& ```js try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.MAGNETIC_FIELD, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1337,7 +1315,7 @@ try { once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticFieldUncalibratedResponse>): void -订阅一次未经校准的磁场传感器数据。 +获取一次未经校准的磁场传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1345,8 +1323,8 @@ once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticF | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册一次未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 回调函数,异步上报的传感器数据固定为MagneticFieldUncalibratedResponse。 | **错误码**: @@ -1360,17 +1338,16 @@ once(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback: Callback<MagneticF ```js try { - sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function(data) { + sensor.once(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, function (data) { console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1378,16 +1355,16 @@ try { once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): void -订阅一次定向传感器数据。 +获取一次方向传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册一次方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | --------------------------------------------------------- | +| type | [SensorId](#sensorid9).ORIENTATION | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 回调函数,异步上报的传感器数据固定为OrientationResponse。 | **错误码**: @@ -1401,14 +1378,13 @@ once(type: SensorId.ORIENTATION, callback: Callback<OrientationResponse>): ```js try { - sensor.once(sensor.SensorId.ORIENTATION, function(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ORIENTATION, function (data) { + console.info('The device rotates at an angle around the X axis: ' + data.beta); + console.info('The device rotates at an angle around the Y axis: ' + data.gamma); + console.info('The device rotates at an angle around the Z axis: ' + data.alpha); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1416,7 +1392,7 @@ try { once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): void -订阅一次计步器传感器数据。 +获取一次计步器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -1424,10 +1400,10 @@ once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): voi **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册一次计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).PEDOMETER | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerResponse。 | **错误码**: @@ -1441,20 +1417,18 @@ once(type: SensorId.PEDOMETER, callback: Callback<PedometerResponse>): voi ```js try { - sensor.once(sensor.SensorId.PEDOMETER, function(data) { - console.info('Steps: ' + data.steps); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PEDOMETER, function (data) { + console.info('Step count: ' + data.steps); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` ### PEDOMETER_DETECTION9+ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectionResponse>): void - -订阅一次计步器检测传感器数据。 +获取一次计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -1464,8 +1438,8 @@ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectio | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册一次计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为PedometerDetectionResponse。 | **错误码**: @@ -1479,12 +1453,11 @@ once(type: SensorId.PEDOMETER_DETECTION, callback: Callback<PedometerDetectio ```js try { - sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function(data) { + sensor.once(sensor.SensorId.PEDOMETER_DETECTION, function (data) { console.info('Scalar data: ' + data.scalar); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1492,16 +1465,16 @@ try { once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): void -订阅一次接近传感器数据。 +获取一次接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册一次接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------- | +| type | [SensorId](#sensorid9).PROXIMITY | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 回调函数,异步上报的传感器数据固定为ProximityResponse。 | **错误码**: @@ -1515,12 +1488,11 @@ once(type: SensorId.PROXIMITY, callback: Callback<ProximityResponse>): voi ```js try { - sensor.once(sensor.SensorId.PROXIMITY, function(data) { - console.info('Distance: ' + data.distance); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.PROXIMITY, function (data) { + console.info('Distance: ' + data.distance); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1528,7 +1500,7 @@ try { once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorResponse>): void -订阅一次旋转矢量传感器数据。 +获取一次旋转矢量传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1536,8 +1508,8 @@ once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorRespons | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册一次旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| type | [SensorId](#sensorid9).ROTATION_VECTOR | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 回调函数,异步上报的传感器数据固定为RotationVectorResponse。 | **错误码**: @@ -1551,15 +1523,14 @@ once(type: SensorId.ROTATION_VECTOR, callback: Callback<RotationVectorRespons ```js try { - sensor.once(sensor.SensorId.ROTATION_VECTOR, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.ROTATION_VECTOR, function (data) { + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('Scalar quantity: ' + data.w); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1567,7 +1538,7 @@ try { once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionResponse>): void -订阅一次重要的运动传感器数据。 +获取一次大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1575,8 +1546,8 @@ once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 有效运动传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册一次有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为SignificantMotionResponse。 | **错误码**: @@ -1590,12 +1561,11 @@ once(type: SensorId.SIGNIFICANT_MOTION, callback: Callback<SignificantMotionR ```js try { - sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function(data) { - console.info('Scalar data: ' + data.scalar); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.SIGNIFICANT_MOTION, function (data) { + console.info('Scalar data: ' + data.scalar); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1603,16 +1573,16 @@ try { once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -订阅一次佩戴检测传感器数据。 +获取一次佩戴检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册一次穿戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorId](#sensorid9).WEAR_DETECTION | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 回调函数,异步上报的传感器数据固定为WearDetectionResponse。 | **错误码**: @@ -1626,12 +1596,11 @@ once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse& ```js try { - sensor.once(sensor.SensorId.WEAR_DETECTION, function(data) { - console.info("Wear status: "+ data.value); - } - ); -} catch(err) { - console.info('once fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.once(sensor.SensorId.WEAR_DETECTION, function (data) { + console.info("Wear status: " + data.value); + }); +} catch (err) { + console.error('Once fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1641,7 +1610,7 @@ try { off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse>): void -取消订阅加速度计传感器数据。 +取消订阅加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1651,21 +1620,27 @@ off(type: SensorId.ACCELEROMETER, callback?: Callback<AccelerometerResponse&g | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的加速度传感器类型为ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 取消注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| type | [SensorId](#sensorid9).ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 否 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('x-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.ACCELEROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER, callback1); + // 取消SensorId.ACCELEROMETER类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1673,7 +1648,7 @@ try { off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<AccelerometerUncalibratedResponse>): void -取消订阅未校准的加速度计传感器数据。 +取消订阅未校准加速度传感器数据。 **需要权限**:ohos.permission.ACCELEROMETER @@ -1683,24 +1658,27 @@ off(type: SensorId.ACCELEROMETER_UNCALIBRATED, callback?: Callback<Accelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准加速度计传感器类型为ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 取消注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| type | [SensorId](#sensorid9).ACCELEROMETER_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED, callback1); + // 取消注册SensorId.ACCELEROMETER_UNCALIBRATED类型的所有回调 + sensor.off(sensor.SensorId.ACCELEROMETER_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1716,27 +1694,35 @@ off(type: SensorId.AMBIENT_LIGHT, callback?: Callback<LightResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的环境光传感器类型为AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 取消注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| type | [SensorId](#sensorid9).AMBIENT_LIGHT | 是 | 传感器类型,该值固定为SensorId.AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js -try { - function callback(data) { - console.info('Illumination: ' + data.intensity); - } - sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); } +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} +try { + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback1); + sensor.on(sensor.SensorId.AMBIENT_LIGHT, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_LIGHT, callback1); + // 取消注册SensorId.AMBIENT_LIGHT的所有回调 + sensor.off(sensor.SensorId.AMBIENT_LIGHT); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); +}V ``` ### AMBIENT_TEMPERATURE9+ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatureResponse>): void -取消订阅环境温度传感器数据。 +取消订阅温度传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1744,19 +1730,27 @@ off(type: SensorId.AMBIENT_TEMPERATURE, callback?: Callback<AmbientTemperatur | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的环境温度传感器类型为AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 取消注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| type | [SensorId](#sensorid9).AMBIENT_TEMPERATURE | 是 | 传感器类型,该值固定为SensorId.AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Temperature: ' + data.temperature); - } - sensor.off( sensor.SensorId.AMBIENT_TEMPERATURE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + sensor.on(sensor.SensorId.AMBIENT_TEMPERATURE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE, callback1); + // 取消注册SensorId.AMBIENT_TEMPERATURE的所有回调 + sensor.off(sensor.SensorId.AMBIENT_TEMPERATURE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1772,19 +1766,27 @@ off(type: SensorId.BAROMETER, callback?: Callback<BarometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的气压计传感器类型为BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 取消注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| type | [SensorId](#sensorid9).BAROMETER | 是 | 传感器类型,该值固定为SensorId.BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Atmospheric pressure: ' + data.pressure); - } - sensor.off(sensor.SensorId.BAROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.BAROMETER, callback1); + sensor.on(sensor.SensorId.BAROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.BAROMETER, callback1); + // 取消注册SensorId.BAROMETER的所有回调 + sensor.off(sensor.SensorId.BAROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1800,21 +1802,27 @@ off(type: SensorId.GRAVITY, callback?: Callback<GravityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的重力传感器类型为GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 取消注册注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| type | [SensorId](#sensorid9).GRAVITY | 是 | 传感器类型,该值固定为SensorId.GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off( sensor.SensorId.GRAVITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GRAVITY, callback1); + sensor.on(sensor.SensorId.GRAVITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GRAVITY, callback1); + // 取消注册SensorId.GRAVITY的所有回调 + sensor.off(sensor.SensorId.GRAVITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1832,21 +1840,27 @@ off(type: SensorId.GYROSCOPE, callback?: Callback<GyroscopeResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的陀螺仪传感器类型为GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 取消注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| type | [SensorId](#sensorid9).GYROSCOPE | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.GYROSCOPE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE, callback1); + sensor.on(sensor.SensorId.GYROSCOPE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE, callback1); + // 取消注册SensorId.GYROSCOPE的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1854,7 +1868,7 @@ try { off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void - 取消订阅未校准的陀螺仪传感器数据。 + 取消订阅未校准陀螺仪传感器数据。 **需要权限**:ohos.permission.GYROSCOPE @@ -1864,21 +1878,27 @@ off(type: SensorId.GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncal | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准陀螺仪传感器类型为GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 取消注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| type | [SensorId](#sensorid9).GYROSCOPE_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED, callback1); + // 取消注册SensorId.GYROSCOPE_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.GYROSCOPE_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1894,19 +1914,27 @@ off(type: SensorId.HALL, callback?: Callback<HallResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的霍尔传感器类型为HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 取消注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | +| type | [SensorId](#sensorid9).HALL | 是 | 传感器类型,该值固定为SensorId.HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Status: ' + data.status); - } - sensor.off(sensor.SensorId.HALL, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HALL, callback1); + sensor.on(sensor.SensorId.HALL, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HALL, callback1); + // 取消注册SensorId.HALL的所有回调 + sensor.off(sensor.SensorId.HALL); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1924,19 +1952,27 @@ off(type: SensorId.HEART_RATE, callback?: Callback<HeartRateResponse>): vo | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的心率传感器类型为HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| type | [SensorId](#sensorid9).HEART_RATE | 是 | 传感器类型,该值固定为SensorId.HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info("Heart rate: " + data.heartRate); - } - sensor.off(sensor.SensorId.HEART_RATE, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HEART_RATE, callback1); + sensor.on(sensor.SensorId.HEART_RATE, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HEART_RATE, callback1); + // 取消注册SensorId.HEART_RATE的所有回调 + sensor.off(sensor.SensorId.HEART_RATE); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1952,19 +1988,27 @@ off(type: SensorId.HUMIDITY, callback?: Callback<HumidityResponse>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的湿度传感器类型为HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 取消注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| type | [SensorId](#sensorid9).HUMIDITY | 是 | 传感器类型,该值固定为SensorId.HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Humidity: ' + data.humidity); - } - sensor.off(sensor.SensorId.HUMIDITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.HUMIDITY, callback1); + sensor.on(sensor.SensorId.HUMIDITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.HUMIDITY, callback1); + // 取消注册SensorId.HUMIDITY的所有回调 + sensor.off(sensor.SensorId.HUMIDITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -1982,21 +2026,27 @@ off(type: SensorId.LINEAR_ACCELEROMETER, callback?: Callback<LinearAccelerome | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的线性加速度传感器类型为LINEAR_ACCELERATION。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| type | [SensorId](#sensorid9).LINEAR_ACCELEROMETER | 是 | 传感器类型,该值固定为SensorId.LINEAR_ACCELERATION。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER, callback1); + // 取消注册SensorId.LINEAR_ACCELEROMETER的所有回调 + sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2012,21 +2062,27 @@ off(type: SensorId.MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的磁场传感器类型为MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 取消注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD, callback1); + // 取消注册SensorId.MAGNETIC_FIELD的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2042,24 +2098,27 @@ off(type: SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback?: Callback<MagneticF | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的未校准磁场传感器类型为MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 取消注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| type | [SensorId](#sensorid9).MAGNETIC_FIELD_UNCALIBRATED | 是 | 传感器类型,该值固定为SensorId.MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); - console.info('Y-coordinate bias: ' + data.biasY); - console.info('Z-coordinate bias: ' + data.biasZ); - } - sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + sensor.on(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED, callback1); + // 取消注册SensorId.MAGNETIC_FIELD_UNCALIBRATED的所有回调 + sensor.off(sensor.SensorId.MAGNETIC_FIELD_UNCALIBRATED); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2075,21 +2134,27 @@ off(type: SensorId.ORIENTATION, callback?: Callback<OrientationResponse>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的方向传感器类型为ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 取消注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| type | [SensorId](#sensorid9).ORIENTATION | 是 | 传感器类型,该值固定为SensorId.ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('The device rotates at an angle around the X axis: ' + data.beta); - console.info('The device rotates at an angle around the Y axis: ' + data.gamma); - console.info('The device rotates at an angle around the Z axis: ' + data.alpha); - } - sensor.off(sensor.SensorId.ORIENTATION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ORIENTATION, callback1); + sensor.on(sensor.SensorId.ORIENTATION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ORIENTATION, callback1); + // 取消注册SensorId.ORIENTATION的所有回调 + sensor.off(sensor.SensorId.ORIENTATION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2107,19 +2172,27 @@ off(type: SensorId.PEDOMETER, callback?: Callback<PedometerResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的计步传感器类型为PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 取消注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| type | [SensorId](#sensorid9).PEDOMETER | 是 | 传感器类型,该值固定为SensorId.PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Steps: ' + data.steps); - } - sensor.off(sensor.SensorId.PEDOMETER, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER, callback1); + sensor.on(sensor.SensorId.PEDOMETER, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER, callback1); + // 取消注册SensorId.PEDOMETER的所有回调 + sensor.off(sensor.SensorId.PEDOMETER); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2127,7 +2200,7 @@ try { off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectionResponse>): void -取消订阅计步器检测传感器数据。 +取消订阅计步检测器传感器数据。 **需要权限**:ohos.permission.ACTIVITY_MOTION @@ -2137,19 +2210,27 @@ off(type: SensorId.PEDOMETER_DETECTION, callback?: Callback<PedometerDetectio | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的计步检测传感器类型为PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 取消注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| type | [SensorId](#sensorid9).PEDOMETER_DETECTION | 是 | 传感器类型,该值固定为SensorId.PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Scalar data: ' + data.scalar); - } - sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback1); + sensor.on(sensor.SensorId.PEDOMETER_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION, callback1); + // 取消注册SensorId.PEDOMETER_DETECTION的所有回调 + sensor.off(sensor.SensorId.PEDOMETER_DETECTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2157,7 +2238,7 @@ try { off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): void -取消订阅接近传感器数据。 +取消订阅接近光传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2165,19 +2246,27 @@ off(type: SensorId.PROXIMITY, callback?: Callback<ProximityResponse>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的接近光传感器类型为PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 取消注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| type | [SensorId](#sensorid9).PROXIMITY | 是 | 传感器类型,该值固定为SensorId.PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Distance: ' + data.distance); - } - sensor.off(sensor.SensorId.PROXIMITY, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.PROXIMITY, callback1); + sensor.on(sensor.SensorId.PROXIMITY, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.PROXIMITY, callback1); + // 取消注册SensorId.PROXIMITY的所有回调 + sensor.off(sensor.SensorId.PROXIMITY); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2193,22 +2282,27 @@ off(type: SensorId.ROTATION_VECTOR, callback?: Callback<RotationVectorRespons | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的旋转矢量传感器类型为ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 取消注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| type | [SensorId](#sensorid9).ROTATION_VECTOR | 是 | 传感器类型,该值固定为SensorId.ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('Scalar quantity: ' + data.w); - } - sensor.off(sensor.SensorId.ROTATION_VECTOR, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback1); + sensor.on(sensor.SensorId.ROTATION_VECTOR, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.ROTATION_VECTOR, callback1); + // 取消注册SensorId.ROTATION_VECTOR的所有回调 + sensor.off(sensor.SensorId.ROTATION_VECTOR); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2216,7 +2310,7 @@ try { off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionResponse>): void -取消订阅重要的运动传感器数据。 +取消大幅动作检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2224,19 +2318,27 @@ off(type: SensorId.SIGNIFICANT_MOTION, callback?: Callback<SignificantMotionR | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的大幅动作传感器类型为SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 取消注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| type | [SensorId](#sensorid9).SIGNIFICANT_MOTION | 是 | 传感器类型,该值固定为SensorId.SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function callback(data) { - console.info('Scalar data: ' + data.scalar); - } - sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + sensor.on(sensor.SensorId.SIGNIFICANT_MOTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION, callback1); + // 取消注册SensorId.SIGNIFICANT_MOTION的所有回调 + sensor.off(sensor.SensorId.SIGNIFICANT_MOTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2252,19 +2354,27 @@ off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse& | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorId](#sensorid9) | 是 | 要取消订阅的佩戴检测传感器类型为WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 取消注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| type | [SensorId](#sensorid9).WEAR_DETECTION | 是 | 传感器类型,该值固定为SensorId.WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 需要取消订阅的回调函数,若无此参数,则取消订阅当前类型的所有回调函数。 | **示例:** ```js +function callback1(data) { + console.info('Callback1 data: ' + JSON.stringify(data)); +} +function callback2(data) { + console.info('Callback2 data: ' + JSON.stringify(data)); +} try { - function accCallback(data) { - console.info('Wear status: ' + data.value); - } - sensor.off(sensor.SensorId.WEAR_DETECTION, accCallback); -} catch(err) { - console.info('off fail, errCode: ' + err.code + ' ,msg: ' + err.message); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback1); + sensor.on(sensor.SensorId.WEAR_DETECTION, callback2); + // 仅取消callback1的注册 + sensor.off(sensor.SensorId.WEAR_DETECTION, callback1); + // 取消注册SensorId.WEAR_DETECTION的所有回调 + sensor.off(sensor.SensorId.WEAR_DETECTION); +} catch (err) { + console.error('Off fail, errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -2272,7 +2382,7 @@ try { getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void -获取地球上特定位置的地磁场 。 +获取某时刻地球上特定位置的地磁场信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2280,9 +2390,9 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callbac | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置。 | -| timeMillis | number | 是 | 表示获取磁偏角的时间,单位为毫秒。 | -| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | 是 | 返回磁场信息。 | +| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置,包括经度、纬度和海拔高度。 | +| timeMillis | number | 是 | 获取磁偏角的时间,unix时间戳,单位毫秒。 | +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | 是 | 回调函数,返回地磁场信息。 | **错误码**: @@ -2296,13 +2406,21 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number, callbac ```js try { - sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000, function(data) { - console.info('sensor_getGeomagneticInfo_callback x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); + sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000, function (err, data) { + if (err) { + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info("GeomagneticInfo x" + data.x); + console.info("GeomagneticInfo y" + data.y); + console.info("GeomagneticInfo z" + data.z); + console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); + console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); }); } catch (err) { - console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2310,7 +2428,7 @@ try { getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> -获取地球上特定位置的地磁场 。 +获取某时刻地球上特定位置的地磁场信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2318,14 +2436,14 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promis | 参数名 | 类型 | 必填 | 说明 | | --------------- | ----------------------------------- | ---- | ---------------------------------- | -| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置。 | -| timeMillis | number | 是 | 表示获取磁偏角的时间,单位为毫秒。 | +| locationOptions | [LocationOptions](#locationoptions) | 是 | 地理位置,包括经度、纬度和海拔高度。 | +| timeMillis | number | 是 | 获取磁偏角的时间,unix时间戳,单位毫秒。 | **返回值:** | 类型 | 说明 | | ---------------------------------------------------------- | -------------- | -| Promise<[GeomagneticResponse](#geomagneticresponse)> | 返回磁场信息。 | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise对象,返回地磁场信息。 | **错误码**: @@ -2339,16 +2457,20 @@ getGeomagneticInfo(locationOptions: LocationOptions, timeMillis: number): Promis ```js try { - const promise = sensor.getGeomagneticInfo({latitude:80, longitude:0, altitude:0}, 1580486400000); - promise.then((data) => { - console.info('sensor_getGeomagneticInfo_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }).catch((reason) => { - console.info('Operation failed.'); - }) + const promise = sensor.getGeomagneticInfo({ latitude: 80, longitude: 0, altitude: 0 }, 1580486400000); + promise.then((data) => { + console.info("GeomagneticInfo x" + data.x); + console.info("GeomagneticInfo y" + data.y); + console.info("GeomagneticInfo z" + data.z); + console.info("GeomagneticInfo geomagneticDip" + data.geomagneticDip); + console.info("GeomagneticInfo deflectionAngle" + data.deflectionAngle); + console.info("GeomagneticInfo levelIntensity" + data.levelIntensity); + console.info("GeomagneticInfo totalIntensity" + data.totalIntensity); + }, (err)=>{ + console.error('Get geomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getGeomagneticInfo failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get geomagneticInfo. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2356,7 +2478,7 @@ try { getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -根据当前气压获取设备所在的海拔高度。 +根据气压值获取海拔高度。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2364,9 +2486,9 @@ getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncC | 参数名 | 类型 | 必填 | 说明 | | --------------- | --------------------------- | ---- | ------------------------------------- | -| seaPressure | number | 是 | 表示海平面气压值,单位为hPa。 | -| currentPressure | number | 是 | 表示设备所在高度的气压值,单位为hPa。 | -| callback | AsyncCallback<number> | 是 | 返回设备所在的海拔高度,单位为米。 | +| seaPressure | number | 是 | 海平面气压值,单位为hPa。 | +| currentPressure | number | 是 | 指定的气压值,单位为hPa。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回指定的气压值对应的海拔高度,单位为米。 | **错误码**: @@ -2380,11 +2502,17 @@ getDeviceAltitude(seaPressure: number, currentPressure: number, callback: AsyncC ```js try { - sensor.getDeviceAltitude(0, 200, function(data) { - console.info('Successed to get getDeviceAltitude interface get data: ' + data); - }); + let seaPressure = 1013.2; + let currentPressure = 1500.0; + sensor.getDeviceAltitude(seaPressure, currentPressure, function (err, data) { + if (err) { + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('altitude: ' + data); + }); } catch (err) { - console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2392,7 +2520,7 @@ try { getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<number> -根据当前气压获取设备所在的海拔高度。 +根据气压值获取海拔高度。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2400,14 +2528,14 @@ getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<numb | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------ | ---- | ------------------------------------- | -| seaPressure | number | 是 | 表示海平面气压值,单位为hPa。 | -| currentPressure | number | 是 | 表示设备所在高度的气压值,单位为hPa。 | +| seaPressure | number | 是 | 海平面气压值,单位为hPa。 | +| currentPressure | number | 是 | 指定的气压值,单位为hPa。 | **返回值:** | 类型 | 说明 | | --------------------- | ------------------------------------ | -| Promise<number> | 返回设备所在的海拔高度(单位:米)。 | +| Promise<number> | Promise对象,返回指定的气压值对应的海拔高度,单位为米。 | **错误码**: @@ -2421,14 +2549,16 @@ getDeviceAltitude(seaPressure: number, currentPressure: number): Promise<numb ```js try { - const promise = sensor.getDeviceAltitude (0, 200); - promise.then((data) => { - console.info('sensor_getDeviceAltitude_Promise success', data); - }).catch((err) => { - console.error("Operation failed"); - }) + let seaPressure = 1013.2; + let currentPressure = 1500.0; + const promise = sensor.getDeviceAltitude(seaPressure, currentPressure); + promise.then((data) => { + console.info('sensor_getDeviceAltitude_Promise success', data); + }, (err) => { + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getDeviceAltitude failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get altitude failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2436,7 +2566,7 @@ try { getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -从倾角矩阵计算地磁倾角的弧度。 +根据倾斜矩阵计算地磁倾角。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2444,8 +2574,8 @@ getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | ----------------- | --------------------------- | ---- | ---------------------------- | -| inclinationMatrix | Array<number> | 是 | 表示倾斜矩阵。 | -| callback | AsyncCallback<number> | 是 | 返回地磁倾斜角,单位为弧度。 | +| inclinationMatrix | Array<number> | 是 | 倾斜矩阵。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回地磁倾角,单位为弧度。 | **错误码**: @@ -2459,11 +2589,21 @@ getInclination(inclinationMatrix: Array<number>, callback: AsyncCallback&l ```js try { - sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1], function(data) { - console.info('Successed to get getInclination interface get data: ' + data); - }) + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + sensor.getInclination(inclinationMatrix, function (err, data) { + if (err) { + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('Inclination: ' + data); + }) } catch (err) { - console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2471,7 +2611,7 @@ try { getInclination(inclinationMatrix: Array<number>): Promise<number> - 从倾角矩阵计算地磁倾角的弧度。 +根据倾斜矩阵计算地磁倾角。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2479,13 +2619,13 @@ try { | 参数名 | 类型 | 必填 | 说明 | | ----------------- | ------------------- | ---- | -------------- | -| inclinationMatrix | Array<number> | 是 | 表示倾斜矩阵。 | +| inclinationMatrix | Array<number> | 是 | 倾斜矩阵。 | **返回值:** | 类型 | 说明 | | --------------------- | ---------------------------- | -| Promise<number> | 返回地磁倾斜角,单位为弧度。 | +| Promise<number> | Promise对象,返回地磁倾斜角,单位为弧度。 | **错误码**: @@ -2499,14 +2639,20 @@ try { ```js try { - const promise = sensor.getInclination ([1, 0, 0, 0, 1, 0, 0, 0, 1]); - promise.then((data) => { - console.info('getInclination_promise successed', data); - }).catch((err) => { - console.error("Operation failed"); - }) + // inclinationMatrix可以为3*3,或者4*4 + let inclinationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ] + const promise = sensor.getInclination(inclinationMatrix); + promise.then((data) => { + console.info('Inclination: ' + data); + }, (err) => { + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getInclination failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get inclination failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2515,7 +2661,7 @@ try { getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback): void -得到两个旋转矩阵之间的角度变化。 +计算两个旋转矩阵之间的角度变化。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2523,9 +2669,9 @@ try { | 参数名 | 类型 | 必填 | 说明 | | --------------------- | ---------------------------------------- | ---- | --------------------------------- | -| currentRotationMatrix | Array<number> | 是 | 表示当前旋转矩阵。 | -| preRotationMatrix | Array<number> | 是 | 表示旋转矩阵。 | -| callback | AsyncCallback<Array<number>> | 是 | 返回z、x、y轴方向的旋转角度变化。 | +| currentRotationMatrix | Array<number> | 是 | 当前旋转矩阵。 | +| preRotationMatrix | Array<number> | 是 | 相对旋转矩阵。 | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,返回绕z、x、y轴方向的旋转角度。 | **错误码**: @@ -2539,13 +2685,31 @@ try { ```js try { - sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(data) { - for (var i=0; i < data.length; i++) { - console.info("data[" + i + "]: " + data[i]); - } - }) + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix, function (err, data) { + if (err) { + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + if (data.length < 3) { + console.error("Get angle variation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }) } catch (err) { - console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2561,14 +2725,14 @@ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: | 参数名 | 类型 | 必填 | 说明 | | --------------------- | ------------------- | ---- | ------------------ | -| currentRotationMatrix | Array<number> | 是 | 表示当前旋转矩阵。 | -| preRotationMatrix | Array<number> | 是 | | +| currentRotationMatrix | Array<number> | 是 | 当前旋转矩阵。 | +| preRotationMatrix | Array<number> | 是 | 相对旋转矩阵 | **返回值:** | 类型 | 说明 | | ---------------------------------- | --------------------------------- | -| Promise<Array<number>> | 返回z、x、y轴方向的旋转角度变化。 | +| Promise<Array<number>> | Promise对象,返回绕z、x、y轴方向的旋转角度。 | **错误码**: @@ -2581,17 +2745,31 @@ getAngleVariation(currentRotationMatrix: Array<number>, preRotationMatrix: **示例:** ```js -try { - const promise = sensor.getAngleVariation([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); - promise.then((data) => { - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((reason) => { - console.info('promise::catch ', reason); - }) +try { + // 旋转矩阵可以为3*3,或者4*4 + let currentRotationMatrix = [ + 1, 0, 0, + 0, 1, 0, + 0, 0, 1 + ]; + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getAngleVariation(currentRotationMatrix, preRotationMatrix); + promise.then((data) => { + if (data.length < 3) { + console.error("Get angle variation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }, (err) => { + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getAngleVariation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get angle variation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2599,7 +2777,7 @@ try { getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback): void -将旋转向量转换为旋转矩阵。 +根据旋转矢量获取旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2607,8 +2785,8 @@ getRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback -将旋转向量转换为旋转矩阵。 +根据旋转矢量获取旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2644,13 +2827,13 @@ getRotationMatrix(rotationVector: Array<number>): Promise { - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((reason) => { - console.info('promise::catch ', reason); - }) + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + const promise = sensor.getRotationMatrix(rotationVector); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2682,7 +2866,7 @@ try { transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback): void -旋转提供的旋转矩阵,使其可以以不同的方式表示坐标系。 +根据指定坐标系映射旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2690,11 +2874,11 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor | 参数名 | 类型 | 必填 | 说明 | | ---------------- | ----------------------------------------- | ---- | ---------------------- | -| inRotationVector | Array<number> | 是 | 表示旋转矩阵。 | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 表示坐标系方向。 | -| callback | AsyncCallback<Array<number>> | 是 | 返回转换后的旋转矩阵。 | +| inRotationVector | Array<number> | 是 | 旋转矩阵。 | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 指定坐标系方向。 | +| callback | AsyncCallback<Array<number>> | 是 | 回调函数,返回映射后的旋转矩阵。 | -**错误码**: +**错误码**: 以下错误码的详细介绍请参见 [sensor.transformRotationMatrix错误码](../errorcodes/errorcode-sensor.md)。 @@ -2706,13 +2890,22 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor ```js try { - sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, function(data) { - for (var i=0; i < data.length; i++) { - console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }, function (err, data) { + if (err) { + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + '] = ' + data[i]); } }) } catch (err) { - console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2720,7 +2913,7 @@ try { transformRotationMatrix(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise -旋转提供的旋转矩阵,使其可以以不同的方式表示坐标系。 +根据指定坐标系映射旋转矩阵。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2728,14 +2921,14 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor | 参数名 | 类型 | 必填 | 说明 | | ---------------- | ----------------------------------------- | ---- | ---------------- | -| inRotationVector | Array<number> | 是 | 表示旋转矩阵。 | -| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 表示坐标系方向。 | +| inRotationVector | Array<number> | 是 | 旋转矩阵。 | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | 是 | 指定坐标系方向。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | ---------------------- | -| Promise<Array<number>> | 返回转换后的旋转矩阵。 | +| Promise<Array<number>> | Promise对象,返回转换后的旋转矩阵。 | **错误码**: @@ -2749,16 +2942,21 @@ transformRotationMatrix(inRotationVector: Array<number>, coordinates: Coor ```js try { - const promise = sensor.transformRotationMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}); + let rotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.transformRotationMatrix(rotationMatrix, { x: 1, y: 3 }); promise.then((data) => { - for (var i=0; i < data.length; i++) { - console.info('transformRotationMatrix data[' + i + '] = ' + data[i]); + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); } - }).catch((err) => { - console.info("Operation failed"); -}) + }, (err) => { + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('transformRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Transform rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2766,7 +2964,7 @@ try { getQuaternion(rotationVector: Array<number>, callback: AsyncCallback): void -将旋转向量转换为归一化四元数。 +根据旋转向量计算归一化四元数。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2774,8 +2972,8 @@ getQuaternion(rotationVector: Array<number>, callback: AsyncCallback -将旋转向量转换为归一化四元数。 +根据旋转向量计算归一化四元数。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2811,13 +3014,13 @@ getQuaternion(rotationVector: Array<number>): Promise | 参数名 | 类型 | 必填 | 说明 | | -------------- | ------------------- | ---- | -------------- | -| rotationVector | Array<number> | 是 | 表示旋转矢量。 | +| rotationVector | Array<number> | 是 | 旋转矢量。 | **返回值:** | 类型 | 说明 | | ---------------------------------- | ------------ | -| Promise<Array<number>> | 返回四元数。 | +| Promise<Array<number>> | Promise,对象返归一化回四元数。 | **错误码**: @@ -2831,17 +3034,17 @@ getQuaternion(rotationVector: Array<number>): Promise ```js try { - const promise = sensor.getQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); - promise.then((data) => { - console.info('getQuaternionn_promise successed'); - for (var i=0; i < data.length; i++) { - console.info('data[' + i + ']: ' + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) + let rotationVector = [0.20046076, 0.21907, 0.73978853, 0.60376877]; + const promise = sensor.getQuaternion(rotationVector); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { + console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getQuaternion failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get quaternion failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2849,7 +3052,7 @@ try { getOrientation(rotationMatrix: Array<number>, callback: AsyncCallback): void -根据旋转矩阵计算设备的方向。 +根据旋转矩阵计算设备方向。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2857,8 +3060,8 @@ getOrientation(rotationMatrix: Array<number>, callback: AsyncCallbackSuccessed to get getOrientation interface get data: " + data); - for (var i = 1; i < data.length; i++) { - console.info('sensor_getOrientation_callback ' + data[i]); - } - }) + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + sensor.getOrientation(preRotationMatrix, function (err, data) { + if (err) { + console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + if (data.length < 3) { + console.error("Get orientation failed, length" + data.length); + } + console.info("Z: " + data[0]); + console.info("X: " + data[1]); + console.info("Y : " + data[2]); + }) } catch (err) { - console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get orientation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2895,13 +3109,13 @@ getOrientation(rotationMatrix: Array<number>): Promise { - console.info('sensor_getOrientation_Promise success', data); - for (var i = 1; i < data.length; i++) { - console.info('sensor_getOrientation_promise ' + data[i]); - } - }).catch((err) => { - console.info('promise failed'); - }) -} catch (err) { + let preRotationMatrix = [ + 1, 0, 0, + 0, 0.87, -0.50, + 0, 0.50, 0.87 + ]; + const promise = sensor.getOrientation(preRotationMatrix); + promise.then((data) => { + for (var i = 0; i < data.length; i++) { + console.info('data[' + i + ']: ' + data[i]); + } + }, (err) => { console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); + }); +} catch (err) { + console.error('getOrientation failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2941,9 +3159,9 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------------------------------------------------ | ---- | -------------- | -| gravity | Array<number> | 是 | 表示重力向量。 | -| geomagnetic | Array<number> | 是 | 表示地磁矢量。 | -| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | 是 | 返回旋转矩阵。 | +| gravity | Array<number> | 是 | 重力矢量。 | +| geomagnetic | Array<number> | 是 | 地磁矢量。 | +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | 是 | 回调函数,返回旋转矩阵。 | **错误码**: @@ -2957,11 +3175,17 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> ```js try { - sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(data) { - console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); - }) + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + sensor.getRotationMatrix(gravity, geomagnetic, function (err, data) => { + if (err) { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('RotationMatrix' + JSON.stringify(data)); + }) } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -2977,14 +3201,14 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> | 参数名 | 类型 | 必填 | 说明 | | ----------- | ------------------- | ---- | -------------- | -| gravity | Array<number> | 是 | 表示重力向量。 | -| geomagnetic | Array<number> | 是 | 表示地磁矢量。 | +| gravity | Array<number> | 是 | 重力向量。 | +| geomagnetic | Array<number> | 是 | 地磁矢量。 | **返回值:** | 类型 | 说明 | | ------------------------------------------------------------ | -------------- | -| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | 返回旋转矩阵。 | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise对象,返回旋转矩阵。 | **错误码**: @@ -2998,20 +3222,22 @@ getRotationMatrix(gravity: Array<number>, geomagnetic: Array<number> ```js try { - const promise = sensor.getRotationMatrix ([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); - promise.then((data) => { - console.info('sensor_getRotationMatrix_callback ' + JSON.stringify(data)); - }).catch((err) => { - console.info('promise failed'); - }) + let gravity = [-0.27775216, 0.5351276, 9.788099]; + let geomagnetic = [210.87253, -78.6096, -111.44444]; + const promise = sensor.getRotationMatrix(gravity, geomagnetic); + promise.then((data) => { + console.info('RotationMatrix' + JSON.stringify(data)); + }, (err) => { + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + }); } catch (err) { - console.error('getRotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get rotationMatrix failed. Error code: ' + err.code + '; message: ' + err.message); } ``` ## sensor.getSensorList9+ - getSensorList(callback: AsyncCallback): void +getSensorList(callback: AsyncCallback): void 获取设备上的所有传感器信息。 @@ -3021,7 +3247,7 @@ try { | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback | 是 | 返回传感器列表。 | +| callback | AsyncCallback | 是 | 回调函数,返回传感器属性列表。 | **错误码**: @@ -3035,14 +3261,17 @@ try { ```js try { - sensor.getSensorList((data) => { - console.info('getSensorList callback in ' + data.length); + sensor.getSensorList((err, data) => { + if (err) { + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); + console.info('data[' + i + ']: ' + JSON.stringify(data[i])); } }); } catch (err) { - console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3058,7 +3287,7 @@ try { | 参数名 | 类型 | 必填 | 说明 | | ------- | ---------------------------------------- | ---- | ---------------- | -| promise | Promise | 是 | 返回传感器列表。 | +| promise | Promise | 是 | Promise对象,返回传感器属性列表。 | **错误码**: @@ -3073,15 +3302,14 @@ try { ```js try { sensor.getSensorList().then((data) => { - console.info('getSensorList promise in ' + data.length); for (var i = 0; i < data.length; i++) { - console.info("getSensorList " + JSON.stringify(data[i])); + console.info('data[' + i + ']: ' + JSON.stringify(data[i])); } - }, (error)=>{ - console.error('getSensorList failed'); + }, (err) => { + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); }); } catch (err) { - console.error('getSensorList failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get sensorList failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3089,7 +3317,7 @@ try { getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void -获取指定类型的传感器信息。 +获取指定传感器类型的属性信息。 **系统能力**:SystemCapability.Sensors.Sensor @@ -3097,8 +3325,8 @@ getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | --------------------------------------- | ---- | ---------------- | -| type | [SensorId](#sensorid9) | 是 | 传感器类型。 | -| callback | AsyncCallback<[Sensor](#sensor9)> | 是 | 返回传感器信息。 | +| type | [SensorId](#sensorid9) | 是 | 指定传感器类型。 | +| callback | AsyncCallback<[Sensor](#sensor9)> | 是 | 回调函数,返回指定传感器的属性信息。 | **错误码**: @@ -3112,11 +3340,15 @@ getSingleSensor(type: SensorId, callback: AsyncCallback<Sensor>): void ```js try { - sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { - console.info('getSingleSensor ' + JSON.stringify(data)); + sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER, (err, data) => { + if (err) { + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('Sensor: ' + JSON.stringify(data)); }); } catch (err) { - console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3153,12 +3385,12 @@ try { ```js try { sensor.getSingleSensor(sensor.SensorId.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { - console.info('getSingleSensor '+ JSON.stringify(data)); - }, (error)=>{ - console.error('getSingleSensor failed'); + console.info('Sensor: ' + JSON.stringify(data)); + }, (err) => { + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); }); } catch (err) { - console.error('getSingleSensor failed. Error code: ' + err.code + '; message: ' + err.message); + console.error('Get singleSensor failed. Error code: ' + err.code + '; message: ' + err.message); } ``` @@ -3168,29 +3400,29 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 默认值 | 说明 | -| --------------------------- | ------ | ---------------------- | -| ACCELEROMETER | 1 | 加速度传感器。 | -| GYROSCOPE | 2 | 陀螺仪传感器。 | -| AMBIENT_LIGHT | 5 | 环境光传感器。 | -| MAGNETIC_FIELD | 6 | 磁场传感器。 | -| BAROMETER | 8 | 气压计传感器。 | -| HALL | 10 | 霍尔传感器。 | -| PROXIMITY | 12 | 接近光传感器。 | -| HUMIDITY | 13 | 湿度传感器。 | -| ORIENTATION | 256 | 方向传感器。 | -| GRAVITY | 257 | 重力传感器。 | -| LINEAR_ACCELEROMETER | 258 | 线性加速度传感器。 | -| ROTATION_VECTOR | 259 | 旋转矢量传感器。 | -| AMBIENT_TEMPERATURE | 260 | 环境温度传感器。 | -| MAGNETIC_FIELD_UNCALIBRATED | 261 | 未校准磁场传感器。 | -| GYROSCOPE_UNCALIBRATED | 263 | 未校准陀螺仪传感器。 | -| SIGNIFICANT_MOTION | 264 | 有效运动传感器。 | -| PEDOMETER_DETECTION | 265 | 计步检测传感器。 | -| PEDOMETER | 266 | 计步传感器。 | -| HEART_RATE | 278 | 心率传感器。 | -| WEAR_DETECTION | 280 | 佩戴检测传感器。 | -| ACCELEROMETER_UNCALIBRATED | 281 | 未校准加速度计传感器。 | +| 名称 | 值 | 说明 | +| --------------------------- | ---- | ---------------------- | +| ACCELEROMETER | 1 | 加速度传感器。 | +| GYROSCOPE | 2 | 陀螺仪传感器。 | +| AMBIENT_LIGHT | 5 | 环境光传感器。 | +| MAGNETIC_FIELD | 6 | 磁场传感器。 | +| BAROMETER | 8 | 气压计传感器。 | +| HALL | 10 | 霍尔传感器。 | +| PROXIMITY | 12 | 接近光传感器。 | +| HUMIDITY | 13 | 湿度传感器。 | +| ORIENTATION | 256 | 方向传感器。 | +| GRAVITY | 257 | 重力传感器。 | +| LINEAR_ACCELEROMETER | 258 | 线性加速度传感器。 | +| ROTATION_VECTOR | 259 | 旋转矢量传感器。 | +| AMBIENT_TEMPERATURE | 260 | 环境温度传感器。 | +| MAGNETIC_FIELD_UNCALIBRATED | 261 | 未校准磁场传感器。 | +| GYROSCOPE_UNCALIBRATED | 263 | 未校准陀螺仪传感器。 | +| SIGNIFICANT_MOTION | 264 | 有效运动传感器。 | +| PEDOMETER_DETECTION | 265 | 计步检测传感器。 | +| PEDOMETER | 266 | 计步传感器。 | +| HEART_RATE | 278 | 心率传感器。 | +| WEAR_DETECTION | 280 | 佩戴检测传感器。 | +| ACCELEROMETER_UNCALIBRATED | 281 | 未校准加速度计传感器。 | ## SensorType(deprecated) @@ -3199,29 +3431,29 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 默认值 | 说明 | -| ------------------------------------------ | ------ | ---------------------- | -| SENSOR_TYPE_ID_ACCELEROMETER | 1 | 加速度传感器。 | -| SENSOR_TYPE_ID_GYROSCOPE | 2 | 陀螺仪传感器。 | -| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | 环境光传感器。 | -| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | 磁场传感器。 | -| SENSOR_TYPE_ID_BAROMETER | 8 | 气压计传感器。 | -| SENSOR_TYPE_ID_HALL | 10 | 霍尔传感器。 | -| SENSOR_TYPE_ID_PROXIMITY | 12 | 接近光传感器。 | -| SENSOR_TYPE_ID_HUMIDITY | 13 | 湿度传感器。 | -| SENSOR_TYPE_ID_ORIENTATION | 256 | 方向传感器。 | -| SENSOR_TYPE_ID_GRAVITY | 257 | 重力传感器。 | -| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | 线性加速度传感器。 | -| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | 旋转矢量传感器。 | -| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | 环境温度传感器。 | -| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | 未校准磁场传感器。 | -| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | 未校准陀螺仪传感器。 | -| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | 有效运动传感器。 | -| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | 计步检测传感器。 | -| SENSOR_TYPE_ID_PEDOMETER | 266 | 计步传感器。 | -| SENSOR_TYPE_ID_HEART_RATE | 278 | 心率传感器。 | -| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | 佩戴检测传感器。 | -| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | 未校准加速度计传感器。 | +| 名称 | 值 | 说明 | +| ------------------------------------------ | ---- | ---------------------- | +| SENSOR_TYPE_ID_ACCELEROMETER | 1 | 加速度传感器。 | +| SENSOR_TYPE_ID_GYROSCOPE | 2 | 陀螺仪传感器。 | +| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | 环境光传感器。 | +| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | 磁场传感器。 | +| SENSOR_TYPE_ID_BAROMETER | 8 | 气压计传感器。 | +| SENSOR_TYPE_ID_HALL | 10 | 霍尔传感器。 | +| SENSOR_TYPE_ID_PROXIMITY | 12 | 接近光传感器。 | +| SENSOR_TYPE_ID_HUMIDITY | 13 | 湿度传感器。 | +| SENSOR_TYPE_ID_ORIENTATION | 256 | 方向传感器。 | +| SENSOR_TYPE_ID_GRAVITY | 257 | 重力传感器。 | +| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | 线性加速度传感器。 | +| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | 旋转矢量传感器。 | +| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | 环境温度传感器。 | +| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | 未校准磁场传感器。 | +| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | 未校准陀螺仪传感器。 | +| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | 有效运动传感器。 | +| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | 计步检测传感器。 | +| SENSOR_TYPE_ID_PEDOMETER | 266 | 计步传感器。 | +| SENSOR_TYPE_ID_HEART_RATE | 278 | 心率传感器。 | +| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | 佩戴检测传感器。 | +| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | 未校准加速度计传感器。 | ## Response @@ -3230,9 +3462,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | -------- | ---- | ---- | ------------------------ | -| timestamp | number | 是 | 是 | 传感器数据上报的时间戳。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | ------------------------ | +| timestamp | number | 是 | 是 | 传感器数据上报的时间戳。 | ## Sensor9+ @@ -3240,18 +3472,18 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 说明 | -| --------------- | -------- | ---------------------- | -| sensorName | string | 传感器名称。 | -| venderName | string | 传感器供应商。 | -| firmwareVersion | string | 传感器固件版本。 | -| hardwareVersion | string | 传感器硬件版本。 | -| sensorId | number | 传感器类型id。 | -| maxRange | number | 传感器的最大测量范围。 | -| minSamplePeriod | number | 允许的最小采样周期。 | -| maxSamplePeriod | number | 允许的最大采样周期。 | -| precision | number | 传感器精度。 | -| power | number | 传感器电源。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | -------- | ---------------------- | ---------------------- | ---------------------- | +| sensorName | string | 是 | 是 | 传感器名称。 | +| venderName | string | 是 | 是 | 传感器供应商。 | +| firmwareVersion | string | 是 | 是 | 传感器固件版本。 | +| hardwareVersion | string | 是 | 是 | 传感器硬件版本。 | +| sensorId | number | 是 | 是 | 传感器类型id。 | +| maxRange | number | 是 | 是 | 传感器测量范围的最大值。 | +| minSamplePeriod | number | 是 | 是 | 允许的最小采样周期。 | +| maxSamplePeriod | number | 是 | 是 | 允许的最大采样周期。 | +| precision | number | 是 | 是 | 传感器精度。 | +| power | number | 是 | 是 | 传感器功率。 | ## AccelerometerResponse @@ -3260,11 +3492,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ------------------------------------ | -| x | number | 是 | 是 | 施加在设备x轴的加速度,单位 : m/s2。 | -| y | number | 是 | 是 | 施加在设备y轴的加速度,单位 : m/s2。 | -| z | number | 是 | 是 | 施加在设备z轴的加速度,单位 : m/s2。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ------------------------------------ | +| x | number | 是 | 是 | 施加在设备x轴的加速度,单位 : m/s2。 | +| y | number | 是 | 是 | 施加在设备y轴的加速度,单位 : m/s2。 | +| z | number | 是 | 是 | 施加在设备z轴的加速度,单位 : m/s2。 | ## LinearAccelerometerResponse @@ -3274,11 +3506,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ---------------------------------------- | -| x | number | 是 | 是 | 施加在设备x轴的线性加速度,单位 : m/s2。 | -| y | number | 是 | 是 | 施加在设备y轴的线性加速度,单位 : m/s2。 | -| z | number | 是 | 是 | 施加在设备z轴的线性加速度,单位 : m/s2。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| x | number | 是 | 是 | 施加在设备x轴的线性加速度,单位 : m/s2。 | +| y | number | 是 | 是 | 施加在设备y轴的线性加速度,单位 : m/s2。 | +| z | number | 是 | 是 | 施加在设备z轴的线性加速度,单位 : m/s2。 | ## AccelerometerUncalibratedResponse @@ -3288,14 +3520,14 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | ------------------------------------------------ | -| x | number | 是 | 是 | 施加在设备x轴未校准的加速度,单位 : m/s2。 | -| y | number | 是 | 是 | 施加在设备y轴未校准的加速度,单位 : m/s2。 | -| z | number | 是 | 是 | 施加在设备z轴未校准的加速度,单位 : m/s2。 | -| biasX | number | 是 | 是 | 施加在设备x轴未校准的加速度偏量,单位 : m/s2。 | -| biasY | number | 是 | 是 | 施加在设备上y轴未校准的加速度偏量,单位 : m/s2。 | -| biasZ | number | 是 | 是 | 施加在设备z轴未校准的加速度偏量,单位 : m/s2。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ------------------------------------------------ | +| x | number | 是 | 是 | 施加在设备x轴未校准的加速度,单位 : m/s2。 | +| y | number | 是 | 是 | 施加在设备y轴未校准的加速度,单位 : m/s2。 | +| z | number | 是 | 是 | 施加在设备z轴未校准的加速度,单位 : m/s2。 | +| biasX | number | 是 | 是 | 施加在设备x轴未校准的加速度偏量,单位 : m/s2。 | +| biasY | number | 是 | 是 | 施加在设备上y轴未校准的加速度偏量,单位 : m/s2。 | +| biasZ | number | 是 | 是 | 施加在设备z轴未校准的加速度偏量,单位 : m/s2。 | ## GravityResponse @@ -3305,11 +3537,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ---------------------------------------- | -| x | number | 是 | 是 | 施加在设备x轴的重力加速度,单位 : m/s2。 | -| y | number | 是 | 是 | 施加在设备y轴的重力加速度,单位 : m/s2。 | -| z | number | 是 | 是 | 施加在设备z轴的重力加速度,单位 : m/s2。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| x | number | 是 | 是 | 施加在设备x轴的重力加速度,单位 : m/s2。 | +| y | number | 是 | 是 | 施加在设备y轴的重力加速度,单位 : m/s2。 | +| z | number | 是 | 是 | 施加在设备z轴的重力加速度,单位 : m/s2。 | ## OrientationResponse @@ -3319,11 +3551,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | --------------------------------- | -| alpha | number | 是 | 是 | 设备围绕Z轴的旋转角度,单位:度。 | -| beta | number | 是 | 是 | 设备围绕X轴的旋转角度,单位:度。 | -| gamma | number | 是 | 是 | 设备围绕Y轴的旋转角度,单位:度。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | --------------------------------- | +| alpha | number | 是 | 是 | 设备围绕Z轴的旋转角度,单位:度。 | +| beta | number | 是 | 是 | 设备围绕X轴的旋转角度,单位:度。 | +| gamma | number | 是 | 是 | 设备围绕Y轴的旋转角度,单位:度。 | ## RotationVectorResponse @@ -3333,12 +3565,12 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ----------------- | -| x | number | 是 | 是 | 旋转矢量x轴分量。 | -| y | number | 是 | 是 | 旋转矢量y轴分量。 | -| z | number | 是 | 是 | 旋转矢量z轴分量。 | -| w | number | 是 | 是 | 标量。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ----------------- | +| x | number | 是 | 是 | 旋转矢量x轴分量。 | +| y | number | 是 | 是 | 旋转矢量y轴分量。 | +| z | number | 是 | 是 | 旋转矢量z轴分量。 | +| w | number | 是 | 是 | 标量。 | ## GyroscopeResponse @@ -3348,11 +3580,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | -------------------------------- | -| x | number | 是 | 是 | 设备x轴的旋转角速度,单位rad/s。 | -| y | number | 是 | 是 | 设备y轴的旋转角速度,单位rad/s。 | -| z | number | 是 | 是 | 设备z轴的旋转角速度,单位rad/s。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | -------------------------------- | +| x | number | 是 | 是 | 设备x轴的旋转角速度,单位rad/s。 | +| y | number | 是 | 是 | 设备y轴的旋转角速度,单位rad/s。 | +| z | number | 是 | 是 | 设备z轴的旋转角速度,单位rad/s。 | ## GyroscopeUncalibratedResponse @@ -3362,14 +3594,14 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | ------------------------------------------ | -| x | number | 是 | 是 | 设备x轴未校准的旋转角速度,单位rad/s。 | -| y | number | 是 | 是 | 设备y轴未校准的旋转角速度,单位rad/s。 | -| z | number | 是 | 是 | 设备z轴未校准的旋转角速度,单位rad/s。 | -| biasX | number | 是 | 是 | 设备x轴未校准的旋转角速度偏量,单位rad/s。 | -| biasY | number | 是 | 是 | 设备y轴未校准的旋转角速度偏量,单位rad/s。 | -| biasZ | number | 是 | 是 | 设备z轴未校准的旋转角速度偏量,单位rad/s。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ------------------------------------------ | +| x | number | 是 | 是 | 设备x轴未校准的旋转角速度,单位rad/s。 | +| y | number | 是 | 是 | 设备y轴未校准的旋转角速度,单位rad/s。 | +| z | number | 是 | 是 | 设备z轴未校准的旋转角速度,单位rad/s。 | +| biasX | number | 是 | 是 | 设备x轴未校准的旋转角速度偏量,单位rad/s。 | +| biasY | number | 是 | 是 | 设备y轴未校准的旋转角速度偏量,单位rad/s。 | +| biasZ | number | 是 | 是 | 设备z轴未校准的旋转角速度偏量,单位rad/s。 | ## SignificantMotionResponse @@ -3379,9 +3611,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| scalar | number | 是 | 是 | 表示剧烈运动程度。测量三个物理轴(x、y 和 z)上,设备是否存在大幅度运动;如果取值为1则代表存在大幅度运动,取值为0则代表没有大幅度运动。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | 是 | 是 | 表示剧烈运动程度。测量三个物理轴(x、y 和 z)上,设备是否存在大幅度运动;如果取值为1则代表存在大幅度运动,取值为0则代表没有大幅度运动。 | ## ProximityResponse @@ -3391,9 +3623,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | ---- | ---- | ------------------------------------------------------ | -| distance | number | 是 | 是 | 可见物体与设备显示器的接近程度。0表示接近,1表示远离。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ------------------------------------------------------ | +| distance | number | 是 | 是 | 可见物体与设备显示器的接近程度。0表示接近,1表示远离。 | ## LightResponse @@ -3403,9 +3635,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | -------- | ---- | ---- | ---------------------- | -| intensity | number | 是 | 是 | 光强(单位:勒克斯)。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | ---------------------- | +| intensity | number | 是 | 是 | 光强(单位:勒克斯)。 | ## HallResponse @@ -3415,9 +3647,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| status | number | 是 | 是 | 显示霍尔状态。测量设备周围是否存在磁力吸引,0表示没有,大于0表示有。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| status | number | 是 | 是 | 显示霍尔状态。测量设备周围是否存在磁力吸引,0表示没有,大于0表示有。 | ## MagneticFieldResponse @@ -3427,11 +3659,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ---------------------------- | -| x | number | 是 | 是 | x轴环境磁场强度,单位 : μT。 | -| y | number | 是 | 是 | y轴环境磁场强度,单位 : μT。 | -| z | number | 是 | 是 | z轴环境磁场强度,单位 : μT。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ---------------------------- | +| x | number | 是 | 是 | x轴环境磁场强度,单位 : μT。 | +| y | number | 是 | 是 | y轴环境磁场强度,单位 : μT。 | +| z | number | 是 | 是 | z轴环境磁场强度,单位 : μT。 | ## MagneticFieldUncalibratedResponse @@ -3441,14 +3673,14 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | -------------------------------------- | -| x | number | 是 | 是 | x轴未校准环境磁场强度,单位 : μT。 | -| y | number | 是 | 是 | y轴未校准环境磁场强度,单位 : μT。 | -| z | number | 是 | 是 | z轴未校准环境磁场强度,单位 : μT。 | -| biasX | number | 是 | 是 | x轴未校准环境磁场强度偏量,单位 : μT。 | -| biasY | number | 是 | 是 | y轴未校准环境磁场强度偏量,单位 : μT。 | -| biasZ | number | 是 | 是 | z轴未校准环境磁场强度偏量,单位 : μT。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | -------------------------------------- | +| x | number | 是 | 是 | x轴未校准环境磁场强度,单位 : μT。 | +| y | number | 是 | 是 | y轴未校准环境磁场强度,单位 : μT。 | +| z | number | 是 | 是 | z轴未校准环境磁场强度,单位 : μT。 | +| biasX | number | 是 | 是 | x轴未校准环境磁场强度偏量,单位 : μT。 | +| biasY | number | 是 | 是 | y轴未校准环境磁场强度偏量,单位 : μT。 | +| biasZ | number | 是 | 是 | z轴未校准环境磁场强度偏量,单位 : μT。 | ## PedometerResponse @@ -3458,9 +3690,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | ---------------- | -| steps | number | 是 | 是 | 用户的行走步数。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ---------------- | +| steps | number | 是 | 是 | 用户的行走步数。 | ## HumidityResponse @@ -3470,9 +3702,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | ---- | ---- | --------------------------------------------------------- | -| humidity | number | 是 | 是 | 湿度值。测量环境的相对湿度,以百分比 (%) 表示。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | --------------------------------------------------------- | +| humidity | number | 是 | 是 | 湿度值。测量环境的相对湿度,以百分比 (%) 表示。 | ## PedometerDetectionResponse @@ -3482,9 +3714,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| scalar | number | 是 | 是 | 计步器检测。检测用户的计步动作,如果取值为1则代表用户产生了计步行走的动作,取值为0则代表用户没有发生运动。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ------------------------------------------------------------ | +| scalar | number | 是 | 是 | 计步器检测。检测用户的计步动作,如果取值为1则代表用户产生了计步行走的动作,取值为0则代表用户没有发生运动。 | ## AmbientTemperatureResponse @@ -3494,9 +3726,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----------- | -------- | ---- | ---- | -------------------------- | -| temperature | number | 是 | 是 | 环境温度(单位:摄氏度)。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | ------ | ---- | ---- | -------------------------- | +| temperature | number | 是 | 是 | 环境温度(单位:摄氏度)。 | ## BarometerResponse @@ -3506,9 +3738,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | ---- | ---- | ------------------------ | -| pressure | number | 是 | 是 | 压力值(单位:帕斯卡)。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ------------------------ | +| pressure | number | 是 | 是 | 压力值(单位:帕斯卡)。 | ## HeartRateResponse @@ -3518,9 +3750,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | -------- | ---- | ---- | --------------------------------------- | -| heartRate | number | 是 | 是 | 心率值。测量用户的心率数值,单位:bpm。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | --------------------------------------- | +| heartRate | number | 是 | 是 | 心率值。测量用户的心率数值,单位:bpm。 | ## WearDetectionResponse @@ -3530,9 +3762,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ----- | -------- | ---- | ---- | ------------------------------------------------ | -| value | number | 是 | 是 | 表示设备是否被穿戴(1表示已穿戴,0表示未穿戴)。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----- | ------ | ---- | ---- | ------------------------------------------------ | +| value | number | 是 | 是 | 表示设备是否被穿戴(1表示已穿戴,0表示未穿戴)。 | ## Options @@ -3541,9 +3773,9 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 说明 | -| -------- | -------- | ------------------------------------------- | -| interval | number | 表示传感器的上报频率,默认值为200000000ns。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | ------ | ---- | ---- | ------------------------------------------- | +| interval | number | 是 | 是 | 表示传感器的上报频率,默认值为200000000ns。 | ## RotationMatrixResponse @@ -3551,7 +3783,7 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| 名称 | 类型 | 可读 | 可写 | 说明 | | ----------- | ------------------- | ---- | ---- | ---------- | | rotation | Array<number> | 是 | 是 | 旋转矩阵。 | | inclination | Array<number> | 是 | 是 | 倾斜矩阵。 | @@ -3563,10 +3795,10 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ---- | -------- | ---- | ---- | ----------- | -| x | number | 是 | 是 | x坐标方向。 | -| y | number | 是 | 是 | y坐标方向。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ---- | ------ | ---- | ---- | ----------- | +| x | number | 是 | 是 | x坐标方向。 | +| y | number | 是 | 是 | y坐标方向。 | ## GeomagneticResponse @@ -3575,15 +3807,15 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------------- | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | 是 | 是 | 地磁场的北分量。 | -| y | number | 是 | 是 | 地磁场的东分量。 | -| z | number | 是 | 是 | 地磁场的垂直分量。 | -| geomagneticDip | number | 是 | 是 | 地磁倾角,即地球磁场线与水平面的夹角。 | -| deflectionAngle | number | 是 | 是 | 地磁偏角,即地磁北方向与正北方向在水平面上的角度。 | -| levelIntensity | number | 是 | 是 | 地磁场的水平强度。 | -| totalIntensity | number | 是 | 是 | 地磁场的总强度。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------------- | ------ | ---- | ---- | -------------------------------------------------- | +| x | number | 是 | 是 | 地磁场的北分量。 | +| y | number | 是 | 是 | 地磁场的东分量。 | +| z | number | 是 | 是 | 地磁场的垂直分量。 | +| geomagneticDip | number | 是 | 是 | 地磁倾角,即地球磁场线与水平面的夹角。 | +| deflectionAngle | number | 是 | 是 | 地磁偏角,即地磁北方向与正北方向在水平面上的角度。 | +| levelIntensity | number | 是 | 是 | 地磁场的水平强度。 | +| totalIntensity | number | 是 | 是 | 地磁场的总强度。 | ## LocationOptions @@ -3591,11 +3823,11 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.Sensor -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | -------- | ---- | ---- | ---------- | -| latitude | number | 是 | 是 | 纬度。 | -| longitude | number | 是 | 是 | 经度。 | -| altitude | number | 是 | 是 | 海拔高度。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | ---------- | +| latitude | number | 是 | 是 | 纬度。 | +| longitude | number | 是 | 是 | 经度。 | +| altitude | number | 是 | 是 | 海拔高度。 | ## sensor.on(deprecated) @@ -3613,11 +3845,11 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<Acceler **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER | 是 | 要订阅的加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -3645,11 +3877,11 @@ on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Line **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_LINEAR_ACCELERATION | 是 | 要订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | ### ACCELEROMETER_UNCALIBRATED(deprecated) @@ -3665,11 +3897,11 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的未校准加速度计传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 是 | 要订阅的未校准加速度计传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3697,11 +3929,11 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityRespons **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GRAVITY | 是 | 要订阅的重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3728,11 +3960,11 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE | 是 | 要订阅的陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3759,11 +3991,11 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:Callback<G **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 是 | 要订阅的未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率。 | **示例:** ```js @@ -3791,11 +4023,11 @@ on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: Callback<Sig **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的大幅动作传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 是 | 要订阅的大幅动作传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3820,11 +4052,11 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: Callback<Pe **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER_DETECTION | 是 | 要订阅的计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3849,11 +4081,11 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER | 是 | 要订阅的计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3876,11 +4108,11 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:Callback<Ambi **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 是 | 要订阅的环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -3904,11 +4136,11 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<Magneti **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD | 是 | 要订阅的磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -3934,11 +4166,11 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callbac **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 是 | 要订阅的未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3966,11 +4198,11 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PROXIMITY | 是 | 要订阅的接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -3993,11 +4225,11 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityRespo **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HUMIDITY | 是 | 要订阅的湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4021,11 +4253,11 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_BAROMETER | 是 | 要订阅的气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4049,11 +4281,11 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse>, **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HALL | 是 | 要订阅的霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4076,11 +4308,11 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_LIGHT | 是 | 要订阅的环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** @@ -4104,11 +4336,11 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<Orientatio **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的方向传感器类型为SENSOR_TYPE_ID_ORIENTATION | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ORIENTATION | 是 | 要订阅的方向传感器类型为SENSOR_TYPE_ID_ORIENTATION | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4137,7 +4369,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateRe | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HEART_RATE | 是 | 要订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | | callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | ### ROTATION_VECTOR(deprecated) @@ -4152,11 +4384,11 @@ on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<Rotatio **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ROTATION_VECTOR | 是 | 要订阅的旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4182,11 +4414,11 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDet **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要订阅的佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_WEAR_DETECTION | 是 | 要订阅的佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | **示例:** ```js @@ -4213,10 +4445,10 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: Callback<Accele **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册一次加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER | 是 | 加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 注册一次加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | **示例:** ```js @@ -4242,10 +4474,10 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Li **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_LINEAR_ACCELERATION | 是 | 线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | ### ACCELEROMETER_UNCALIBRATED(deprecated) @@ -4261,10 +4493,10 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callba **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 未校准加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册一次未校准加速度传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 是 | 未校准加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 注册一次未校准加速度传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | **示例:** ``` @@ -4291,10 +4523,10 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: Callback<GravityRespo **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册一次重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GRAVITY | 是 | 重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 注册一次重力传感器的回调函数,上报的数据类型为GravityResponse。 | **示例:** ```js @@ -4320,10 +4552,10 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: Callback<GyroscopeR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册一次陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE | 是 | 陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 注册一次陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | **示例:** ```js @@ -4349,10 +4581,10 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback: Callback&l **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册一次未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 是 | 未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 注册一次未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | **示例:** ```js @@ -4379,10 +4611,10 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback: Callback<Si **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 有效运动传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册一次有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 是 | 有效运动传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 注册一次有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | **示例:** ```js @@ -4406,10 +4638,10 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback: Callback<P **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册一次计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER_DETECTION | 是 | 计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 注册一次计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | **示例:** ```js @@ -4433,10 +4665,10 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: Callback<PedometerR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册一次计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER | 是 | 计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 注册一次计步传感器的回调函数,上报的数据类型为PedometerResponse。 | **示例:** ```js @@ -4458,10 +4690,10 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback: Callback<A **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册一次环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 是 | 环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 注册一次环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | **示例:** ```js @@ -4483,10 +4715,10 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: Callback<Magne **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | -| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册一次磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD | 是 | 磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 注册一次磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | **示例:** ```js @@ -4510,10 +4742,10 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callb **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册一次未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 是 | 未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 注册一次未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | **示例:** ```js @@ -4540,10 +4772,10 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: Callback<ProximityR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册一次接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PROXIMITY | 是 | 接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 注册一次接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | **示例:** ```js @@ -4565,10 +4797,10 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: Callback<HumidityRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册一次湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HUMIDITY | 是 | 湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 注册一次湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | **示例:** ```js @@ -4590,10 +4822,10 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: Callback<BarometerR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册一次气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_BAROMETER | 是 | 气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 注册一次气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | **示例:** ```js @@ -4615,10 +4847,10 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: Callback<HallResponse> **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册一次霍尔传感器的回调函数,上报的数据类型为HallResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HALL | 是 | 霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 是 | 注册一次霍尔传感器的回调函数,上报的数据类型为HallResponse。 | **示例:** ```js @@ -4640,10 +4872,10 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: Callback<LightR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册一次环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_LIGHT | 是 | 环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 是 | 注册一次环境光传感器的回调函数,上报的数据类型为LightResponse。 | **示例:** @@ -4666,10 +4898,10 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: Callback<Orientat **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 方向传感器类型为SENSOR_TYPE_ID_ORIENTATION。 | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册一次方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ORIENTATION | 是 | 方向传感器类型为SENSOR_TYPE_ID_ORIENTATION。 | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 注册一次方向传感器的回调函数,上报的数据类型为OrientationResponse。 | **示例:** ```js @@ -4693,10 +4925,10 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: Callback<Rota **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册一次旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ROTATION_VECTOR | 是 | 旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 注册一次旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | **示例:** ```js @@ -4723,10 +4955,10 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRate **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HEART_RATE | 是 | 心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | ### WEAR_DETECTION(deprecated) @@ -4740,10 +4972,10 @@ once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearD **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册一次穿戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_WEAR_DETECTION | 是 | 佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 注册一次穿戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | **示例:** ```js @@ -4769,10 +5001,10 @@ off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback?: Callback<Accele **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 是 | 取消注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER | 是 | 要取消订阅的加速度传感器类型为SENSOR_TYPE_ID_ACCELEROMETER。 | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | 否 | 取消注册加速度传感器的回调函数,上报的数据类型为AccelerometerResponse。 | **示例:** @@ -4799,10 +5031,10 @@ off(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback?: Callb **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的未校准加速度计传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 是 | 取消注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 是 | 要取消订阅的未校准加速度计传感器类型为SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED。 | +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | 否 | 取消注册未校准加速度计传感器的回调函数,上报的数据类型为AccelerometerUncalibratedResponse。 | **示例:** @@ -4830,10 +5062,10 @@ off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback?: Callback<LightR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | -| callback | Callback<[LightResponse](#lightresponse)> | 是 | 取消注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_LIGHT | 是 | 要取消订阅的环境光传感器类型为SENSOR_TYPE_ID_AMBIENT_LIGHT。 | +| callback | Callback<[LightResponse](#lightresponse)> | 否 | 取消注册环境光传感器的回调函数,上报的数据类型为LightResponse。 | **示例:** @@ -4856,10 +5088,10 @@ off(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback?: Callback< **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 是 | 取消注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 是 | 要取消订阅的环境温度传感器类型为SENSOR_TYPE_ID_AMBIENT_TEMPERATURE。 | +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | 否 | 取消注册环境温度传感器的回调函数,上报的数据类型为AmbientTemperatureResponse。 | **示例:** @@ -4882,10 +5114,10 @@ off(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback?: Callback<BarometerR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | -| callback | Callback<[BarometerResponse](#barometerresponse)> | 是 | 取消注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_BAROMETER | 是 | 要取消订阅的气压计传感器类型为SENSOR_TYPE_ID_BAROMETER。 | +| callback | Callback<[BarometerResponse](#barometerresponse)> | 否 | 取消注册气压计传感器的回调函数,上报的数据类型为BarometerResponse。 | **示例:** @@ -4908,10 +5140,10 @@ off(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback?: Callback<GravityRespo **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | -| callback | Callback<[GravityResponse](#gravityresponse)> | 是 | 取消注册注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GRAVITY | 是 | 要取消订阅的重力传感器类型为SENSOR_TYPE_ID_GRAVITY。 | +| callback | Callback<[GravityResponse](#gravityresponse)> | 否 | 取消注册注册重力传感器的回调函数,上报的数据类型为GravityResponse。 | **示例:** @@ -4938,10 +5170,10 @@ off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback?: Callback<GyroscopeR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 是 | 取消注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE | 是 | 要取消订阅的陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE。 | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | 否 | 取消注册陀螺仪传感器的回调函数,上报的数据类型为GyroscopeResponse。 | **示例:** @@ -4968,10 +5200,10 @@ off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback& **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 是 | 取消注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 是 | 要取消订阅的未校准陀螺仪传感器类型为SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED。 | +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | 否 | 取消注册未校准陀螺仪传感器的回调函数,上报的数据类型为GyroscopeUncalibratedResponse。 | **示例:** @@ -4996,10 +5228,10 @@ off(type: SensorType.SENSOR_TYPE_ID_HALL, callback?: Callback<HallResponse> **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | -| callback | Callback<[HallResponse](#hallresponse)> | 是 | 取消注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HALL | 是 | 要取消订阅的霍尔传感器类型为SENSOR_TYPE_ID_HALL。 | +| callback | Callback<[HallResponse](#hallresponse)> | 否 | 取消注册霍尔传感器的回调函数,上报的数据类型为 HallResponse。 | **示例:** @@ -5026,8 +5258,8 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRate | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HEART_RATE | 是 | 要取消订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 否 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | ### HUMIDITY(deprecated) @@ -5041,10 +5273,10 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityRes **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | -| callback | Callback<[HumidityResponse](#humidityresponse)> | 是 | 取消注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_HUMIDITY | 是 | 要取消订阅的湿度传感器类型为SENSOR_TYPE_ID_HUMIDITY。 | +| callback | Callback<[HumidityResponse](#humidityresponse)> | 否 | 取消注册湿度传感器的回调函数,上报的数据类型为HumidityResponse。 | **示例:** @@ -5069,10 +5301,10 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_LINEAR_ACCELERATION | 是 | 要取消订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 否 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | ### MAGNETIC_FIELD(deprecated) @@ -5086,10 +5318,10 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | -| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 是 | 取消注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD | 是 | 要取消订阅的磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD。 | +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | 否 | 取消注册磁场传感器的回调函数,上报的数据类型为MagneticFieldResponse。 | **示例:** @@ -5114,10 +5346,10 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 是 | 取消注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 是 | 要取消订阅的未校准磁场传感器类型为SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED。 | +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | 否 | 取消注册未校准磁场传感器的回调函数,上报的数据类型为MagneticFieldUncalibratedResponse。 | **示例:** @@ -5145,10 +5377,10 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callbac **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的方向传感器类型为SENSOR_TYPE_ID_ORIENTATION | -| callback | Callback<[OrientationResponse](#orientationresponse)> | 是 | 取消注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ORIENTATION | 是 | 要取消订阅的方向传感器类型为SENSOR_TYPE_ID_ORIENTATION | +| callback | Callback<[OrientationResponse](#orientationresponse)> | 否 | 取消注册方向传感器的回调函数,上报的数据类型为OrientationResponse。 | **示例:** @@ -5175,10 +5407,10 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback<PedometerR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | 是 | 取消注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER | 是 | 要取消订阅的计步传感器类型为SENSOR_TYPE_ID_PEDOMETER。 | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | 否 | 取消注册计步传感器的回调函数,上报的数据类型为PedometerResponse。 | **示例:** @@ -5203,10 +5435,10 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback?: Callback< **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 是 | 取消注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PEDOMETER_DETECTION | 是 | 要取消订阅的计步检测传感器类型为SENSOR_TYPE_ID_PEDOMETER_DETECTION。 | +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | 否 | 取消注册计步检测传感器的回调函数,上报的数据类型为PedometerDetectionResponse。 | **示例:** @@ -5229,10 +5461,10 @@ off(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback?: Callback<ProximityR **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | -| callback | Callback<[ProximityResponse](#proximityresponse)> | 是 | 取消注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_PROXIMITY | 是 | 要取消订阅的接近光传感器类型为SENSOR_TYPE_ID_PROXIMITY。 | +| callback | Callback<[ProximityResponse](#proximityresponse)> | 否 | 取消注册接近光传感器的回调函数,上报的数据类型为ProximityResponse。 | **示例:** @@ -5255,10 +5487,10 @@ off(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback?: Callback<Rota **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 是 | 取消注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_ROTATION_VECTOR | 是 | 要取消订阅的旋转矢量传感器类型为SENSOR_TYPE_ID_ROTATION_VECTOR。 | +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | 否 | 取消注册旋转矢量传感器的回调函数,上报的数据类型为RotationVectorResponse。 | **示例:** @@ -5284,10 +5516,10 @@ off(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback?: Callback<S **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的大幅动作传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 是 | 取消注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 是 | 要取消订阅的大幅动作传感器类型为SENSOR_TYPE_ID_SIGNIFICANT_MOTION。 | +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | 否 | 取消注册有效运动传感器的回调函数,上报的数据类型为SignificantMotionResponse。 | **示例:** @@ -5310,10 +5542,10 @@ off(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback?: Callback<WearD **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 是 | 取消注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | [SensorType](#sensortype).SENSOR_TYPE_ID_WEAR_DETECTION | 是 | 要取消订阅的佩戴检测传感器类型为SENSOR_TYPE_ID_WEAR_DETECTION。 | +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | 否 | 取消注册佩戴检测传感器的回调函数,上报的数据类型为WearDetectionResponse。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md index 37d5bcf23cc85414837cd682251f7018124d8aac..7c8b7c69b8253cbff98b304c9c595efa5a80d09c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @@ -13,16 +13,18 @@ ServiceExtensionContext模块提供ServiceExtensionAbility具有的能力和接 在使用ServiceExtensionContext的功能前,需要通过ServiceExtensionAbility子类实例获取。 -```js - import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; +```ts + import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; + + let context = undefined; class MainAbility extends ServiceExtensionAbility { - onCreate() { - let context = this.context; - } + onCreate() { + context = this.context; + } } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void; @@ -39,18 +41,57 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; | want | [Want](js-apis-application-Want.md) | 是 | Want类型参数,传入需要启动的ability的信息,如ability名称,包名等。 | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility"}; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, options?: StartOptions): Promise\; @@ -73,22 +114,60 @@ startAbility(want: Want, options?: StartOptions): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```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)); - }); + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + var options = { + windowMode: 0, + }; + try { + this.context.startAbility(want, options) + .then((data) => { + // 执行正常业务 + console.log('startAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## startAbility +## ServiceExtensionContext.startAbility startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void @@ -106,20 +185,58 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& | options | [StartOptions](js-apis-application-StartOptions.md) | 是 | 启动Ability所携带的参数。 | | callback | AsyncCallback<void> | 是 | callback形式返回启动结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - - ```js + + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startAbilityWithAccount @@ -140,20 +257,58 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startAbilityWithAccount(want, accountId, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); - ``` + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` ## ServiceExtensionContext.startAbilityWithAccount @@ -174,21 +329,60 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca | options | [StartOptions](js-apis-application-StartOptions.md) | 否 | 启动Ability所携带的参数。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options, (err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` @@ -216,25 +410,60 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { - windowMode: 0, + windowMode: 0 }; - this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { - console.log('---------- startAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // 执行正常业务 + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbility @@ -254,17 +483,48 @@ startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 启动Ability的want信息。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want, (err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbility @@ -289,21 +549,48 @@ startServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.startServiceExtensionAbility(want) - .then((data) => { - console.log('---------- startServiceExtensionAbility success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbilityWithAccount @@ -326,18 +613,51 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 启动Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startServiceExtensionAbilityWithAccount @@ -365,22 +685,50 @@ startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.startServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbility @@ -400,17 +748,45 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; | want | [Want](js-apis-application-Want.md) | 是 | 停止Ability的want信息。 | | callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want, (err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbility @@ -435,21 +811,45 @@ stopServiceExtensionAbility(want: Want): Promise\; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; - this.context.stopServiceExtensionAbility(want) - .then((data) => { - console.log('---------- stopServiceExtensionAbility success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount @@ -472,18 +872,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: | accountId | number | 是 | 需要停止的系统帐号的帐号ID,详情参考[getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess)。 | | callback | AsyncCallback\ | 是 | 停止Ability的回调函数。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }); + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.stopServiceExtensionAbilityWithAccount @@ -511,22 +940,47 @@ stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\< | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; - this.context.stopServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); - }) - .catch((err) => { - console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); - }) + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // 执行正常业务 + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.terminateSelf @@ -545,11 +999,29 @@ terminateSelf(callback: AsyncCallback<void>): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + this.context.terminateSelf((error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('terminateSelf succeed'); }); ``` @@ -569,19 +1041,33 @@ terminateSelf(): Promise<void>; | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts this.context.terminateSelf().then((data) => { - console.log('success:' + JSON.stringify(data)); + // 执行正常业务 + console.log('terminateSelf succeed'); }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); + // 处理业务逻辑错误 + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); }); ``` -## ServiceExtensionContext.connectAbility +## ServiceExtensionContext.connectServiceExtensionAbility -connectAbility(want: Want, options: ConnectOptions): number; +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; 将一个Ability与服务类型的Ability绑定。 @@ -602,24 +1088,44 @@ connectAbility(want: Want, options: ConnectOptions): number; | -------- | -------- | | number | 返回一个number,后续根据这个number去断开连接。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" }; - let options = { + var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - let connection = this.context.connectAbility(want,options); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.connectAbilityWithAccount +## ServiceExtensionContext.connectServiceExtensionAbilityWithAccount -connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; 使用AbilityInfo.AbilityType.SERVICE模板和account将当前能力连接到一个能力。 @@ -641,13 +1147,26 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions | -------- | -------- | | number | 返回Ability连接的结果code。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js + ```ts var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + deviceId: "", + bundleName: "com.extreme.test", + abilityName: "MainAbility" }; var accountId = 100; var options = { @@ -655,13 +1174,20 @@ connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions onDisconnect(elementName) { console.log('----------- onDisconnect -----------') }, onFailed(code) { console.log('----------- onFailed -----------') } } - const result = this.context.connectAbilityWithAccount(want, accountId, options); - console.log('----------- connectAbilityResult: ------------', result); + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.disconnectAbility +## ServiceExtensionContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number, callback:AsyncCallback<void>): void; +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback<void>): void; 将一个Ability与绑定的服务类型的Ability解绑。 @@ -676,19 +1202,44 @@ disconnectAbility(connection: number, callback:AsyncCallback<void>): void; | connection | number | 是 | 在connectAbility中返回的number。 | | callback | AsyncCallback<void> | 否 | 回调函数,返回接口调用是否成功的结果。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let connection=1 - this.context.disconnectAbility(connection, (err) => { - // connection为connectAbility中的返回值 - console.log('terminateSelf result:' + JSON.stringify(err)); + ```ts + // connection为connectServiceExtensionAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` -## ServiceExtensionContext.disconnectAbility +## ServiceExtensionContext.disconnectServiceExtensionAbility -disconnectAbility(connection: number): Promise<void>; +disconnectServiceExtensionAbility(connection: number): Promise<void>; 将一个Ability与绑定的服务类型的Ability解绑。通过Promise返回结果。 @@ -707,17 +1258,40 @@ disconnectAbility(connection: number): Promise<void>; | 类型 | 说明 | | -------- | -------- | | Promise<void> | 返回一个Promise,包含接口的结果。 | - + +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + **示例:** - ```js - let connection=1 - this.context.disconnectAbility(connection).then((data) => { - // connection为connectAbility中的返回值 - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); + ```ts + // connection为connectAbility中的返回值 + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // 执行正常业务 + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // 处理业务逻辑错误 + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` ## ServiceExtensionContext.startAbilityByCall @@ -742,10 +1316,26 @@ startAbilityByCall(want: Want): Promise<Caller>; | -------- | -------- | | Promise<Caller> | 获取要通讯的caller对象。 | +**错误码:** + +| 错误码ID | 错误信息 | +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000050 | Internal Error. | + **示例:** - ```js - let caller = undefined; + 后台启动: + + ```ts + var caller = undefined; // 后台启动Ability,不配置parameters var wantBackground = { @@ -754,13 +1344,29 @@ startAbilityByCall(want: Want): Promise<Caller>; abilityName: "MainAbility", deviceId: "" }; - this.context.startAbilityByCall(wantBackground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller Success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + 前台启动: + + ```ts + var caller = undefined; // 前台启动Ability,将parameters中的"ohos.aafwk.param.callAbilityToForeground"配置为true var wantForeground = { @@ -772,12 +1378,22 @@ startAbilityByCall(want: Want): Promise<Caller>; "ohos.aafwk.param.callAbilityToForeground": true } }; - this.context.startAbilityByCall(wantForeground) - .then((obj) => { + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // 执行正常业务 caller = obj; - console.log('GetCaller success'); - }).catch((error) => { - console.log(`GetCaller failed with ${error}`); - }); + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // 处理业务逻辑错误 + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // 处理入参错误异常 + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-stack.md b/zh-cn/application-dev/reference/apis/js-apis-stack.md index cb71700c6191fa6c2546a7a0a111b4432a233e84..3abca73aad6110eb4d9f13e40eb2e444515c4f87 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-stack.md +++ b/zh-cn/application-dev/reference/apis/js-apis-stack.md @@ -95,11 +95,11 @@ let stack = new Stack(); let result = stack.push("a"); let result1 = stack.push(1); let b = [1, 2, 3]; -stack.push(b); +let result2 = stack.push(b); let c = {name : "Dylon", age : "13"}; let result3 = stack.push(c); try { - stack.push.bind({}, "b")(); + stack.push.bind({}, "b")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -138,7 +138,7 @@ stack.push(2); stack.push(4); let result = stack.pop(); try { - stack.pop.bind({})(); + stack.pop.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -176,7 +176,7 @@ stack.push(5); stack.push(2); let result = stack.peek(); try { - stack.peek.bind({})(); + stack.peek.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -220,7 +220,7 @@ stack.push(5); stack.push(2); let result = stack.locate(2); try { - stack.locate.bind({}, 2)(); + stack.locate.bind({}, 2)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -272,7 +272,7 @@ stack.forEach((value, index) => { try { stack.forEach.bind({}, (value, index) => { console.log("value:" + value, index); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -310,7 +310,7 @@ stack.push(5); stack.push(4); let result = stack.isEmpty(); try { - stack.isEmpty.bind({})(); + stack.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -359,7 +359,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - stack[Symbol.iterator].bind({})(); + stack[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-package.md b/zh-cn/application-dev/reference/apis/js-apis-system-package.md index b8138d9d985f899aa02592ae330f9e195e7008cd..b9eac4c952ba2a7bed4624d84ea439e7cafa785c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-package.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-package.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > -> - 从API Version 7 开始,该接口不再维护,推荐使用新接口[`@ohos.bundle`](js-apis-Bundle.md)。 +> - 从API version 9开始不再维护,推荐使用该模块[`@ohos.bundle.bundleManager`](js-apis-bundleManager.md)。 > > - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -16,7 +16,8 @@ import pkg from '@system.package'; ``` -## package.hasInstalled +## package.hasInstalled(deprecated) +> 从API version 9开始不再维护,推荐使用该模块[`@ohos.bundle.bundleManager`](js-apis-bundleManager.md)。 hasInstalled(Object): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-time.md b/zh-cn/application-dev/reference/apis/js-apis-system-time.md index 2147c418222723f385189fe4256a0259f443e754..d71b6e72fbadc966cd6a51bbc42658513da0b96d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-time.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-time.md @@ -2,22 +2,21 @@ 本模块主要由系统时间和系统时区功能组成。开发者可以设置、获取系统时间及系统时区。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** ->- 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> **说明:** +> +> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 - -``` +```js import systemTime from '@ohos.systemTime'; ``` - ## systemTime.setTime setTime(time : number, callback : AsyncCallback<void>) : void -设置系统时间。 +设置系统时间,使用callback异步回调。 **需要权限:** ohos.permission.SET_TIME @@ -25,31 +24,30 @@ setTime(time : number, callback : AsyncCallback<void>) : void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------- | ---- | ---------------- | | time | number | 是 | 目标时间戳(ms)。 | -| callback | AsyncCallback<void> | 是 | 回调函数,可以在回调函数中处理接口返回值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** - ```js - // time对应的时间为2021-01-20 02:36:25 - var time = 1611081385000; - systemTime.setTime(time, (error, data) => { - if (error) { - console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.setTime success data : ` + JSON.stringify(data)); - }); - ``` - +```js +// time对应的时间为2021-01-20 02:36:25 +let time = 1611081385000; +systemTime.setTime(time, (error, data) => { + if (error) { + console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.setTime setTime(time : number) : Promise<void> -设置系统时间。 +设置系统时间,使用Promise异步回调。 **需要权限:** ohos.permission.SET_TIME @@ -63,285 +61,276 @@ setTime(time : number) : Promise<void> **返回值:** -| 类型 | 说明 | -| ------------------- | -------------------- | -| Promise<void> | 返回的异步回调函数。 | +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** - ```js - // time对应的时间为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)); - }); - ``` - +```js +// time对应的时间为2021-01-20 02:36:25 +let time = 1611081385000; +systemTime.setTime(time).then((data) => { + console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.getCurrentTime8+ getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void -获取自 Unix 纪元以来经过的时间,使用callback形式返回结果。 +获取自Unix纪元以来经过的时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 是 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| -| callback | AsyncCallback<number> | 是 | 回调函数,返回自 Unix 纪元以来经过的时间。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------- | ---- | ------------------ | +| isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | +| callback | AsyncCallback<number> | 是 | 回调函数,返回自Unix纪元以来经过的时间。 | **示例:** - ```js - systemTime.getCurrentTime(true, (error, data) => { - if (error) { - console.error(`failed to systemTime.getCurrentTime because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getCurrentTime success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getCurrentTime(true, (error, data) => { + if (error) { + console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getCurrentTime8+ getCurrentTime(callback: AsyncCallback<number>): void -获取自 Unix 纪元以来经过的时间,使用callback形式返回结果。 +获取自Unix纪元以来经过的时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<number> | 是 | 回调函数,返回自 Unix 纪元以来经过的时间。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------- | ---- | ---------------------------------- | +| callback | AsyncCallback<number> | 是 | 回调函数,返回自Unix纪元以来经过的时间。 | **示例:** - ```js - systemTime.getCurrentTime((error, data) => { - if (error) { - console.error(`failed to systemTime.getCurrentTime because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getCurrentTime success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getCurrentTime((error, data) => { + if (error) { + console.error(`Succeeded in getting systemTime. Data:` + JSON.stringify(error)); + return; + } + console.log(`Failed to get systemTime. Cause:` + JSON.stringify(data)); +}); +``` ## systemTime.getCurrentTime8+ getCurrentTime(isNano?: boolean): Promise<number> -获取自 Unix 纪元以来经过的时间,使用Promise形式返回结果。 +获取自Unix纪元以来经过的时间,使用Promise异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 否 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------- | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------------------------------------------ | -| Promise<number> | 以Promise形式返回结果,返回自 Unix 纪元以来经过的时间。 | +| 类型 | 说明 | +| --------------------- | --------------------------- | +| Promise<number> | Promise对象,返回自Unix纪元以来经过的时间。 | **示例:** - ```js - systemTime.getCurrentTime().then((data) => { - console.log(`systemTime.getCurrentTime success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.getCurrentTime because ` + JSON.stringify(error)); - }); - ``` - +```js +systemTime.getCurrentTime().then((data) => { + console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.getRealActiveTime8+ getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void -获取自系统启动以来经过的时间,不包括深度睡眠时间,使用callback形式返回结果。 +获取自系统启动以来经过的时间,不包括深度睡眠时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 是 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------- | ---- | -------------------------- | +| isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,但不包括度睡眠时间。 | **示例:** - ```js - systemTime.getRealActiveTime(true, (error, data) => { - if (error) { - console.error(`failed to systemTime.getRealActiveTimebecause ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getRealActiveTime(true, (error, data) => { + if (error) { + console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getRealActiveTime8+ getRealActiveTime(callback: AsyncCallback<number>): void -获取自系统启动以来经过的时间,不包括深度睡眠时间,使用callback形式返回结果。 +获取自系统启动以来经过的时间,不包括深度睡眠时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,但不包括度睡眠时间。 | **示例:** - ```js - systemTime.getRealActiveTime((error, data) => { - if (error) { - console.error(`failed to systemTime.getRealActiveTimebecause ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getRealActiveTime((error, data) => { + if (error) { + console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getRealActiveTime8+ getRealActiveTime(isNano?: boolean): Promise<number> -获取自系统启动以来经过的时间,不包括深度睡眠时间,使用Promise形式返回结果。 +获取自系统启动以来经过的时间,不包括深度睡眠时间,使用Promise异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 否 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ----------------------------------- | +| isNano | boolean | 否 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------------------------------------------ | -| Promise<number> | 以Promise形式返回结果,返回自系统启动以来经过的时间,但不包括深度睡眠时间。 | +| 类型 | 说明 | +| -------------- | -------------------------------- | +| Promise<number> | Promise对象,返回自系统启动以来经过的时间,但不包括深度睡眠时间。 | **示例:** - ```js - systemTime.getRealActiveTime().then((data) => { - console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.getRealActiveTime because ` + JSON.stringify(error)); - }); - ``` - +```js +systemTime.getRealActiveTime().then((data) => { + console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.getRealTime8+ getRealTime(isNano: boolean, callback: AsyncCallback<number>): void -获取自系统启动以来经过的时间,包括深度睡眠时间,使用callback形式返回结果。 +获取自系统启动以来经过的时间,包括深度睡眠时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 是 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------- | ---- | ------------------------------- | +| isNano | boolean | 是 | 返回结果是否为纳秒数。
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,包括深度睡眠时间。 | **示例:** - ```js - systemTime.getRealTime(true, (error, data) => { - if (error) { - console.error(`failed to systemTime.getRealTime because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getRealTime success data: ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getRealTime(true, (error, data) => { + if (error) { + console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getRealTime8+ getRealTime(callback: AsyncCallback<number>): void -获取自系统启动以来经过的时间,包括深度睡眠时间,使用callback形式返回结果。 +获取自系统启动以来经过的时间,包括深度睡眠时间,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------- | ---- | --------------------------- | | callback | AsyncCallback<number> | 是 | 回调函数,返回自系统启动以来经过的时间,包括深度睡眠时间。 | **示例:** - ```js - systemTime.getRealTime((error, data) => { - if (error) { - console.error(`failed to systemTime.getRealTime because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getRealTime success data: ` + JSON.stringify(data)); - }); - ``` +```js +systemTime.getRealTime((error, data) => { + if (error) { + console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getRealTime8+ getRealTime(isNano?: boolean): Promise<number> -获取自系统启动以来经过的时间,包括深度睡眠时间,使用Promise形式返回结果。 +获取自系统启动以来经过的时间,包括深度睡眠时间,使用Promise异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | 否 | 返回结果是否为纳秒数。 - true:纳秒数。
- false:毫秒数。
| +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------- | ---- | ------------------------------- | +| isNano | boolean | 否 | 返回结果是否为纳秒数。<
- true:表示返回结果为纳秒数(ns)。
- false:表示返回结果为毫秒数(ms)。 | **返回值:** -| 类型 | 说明 | -| --------------------- | ------------------------------------------------------------ | -| Promise<number> | 以Promise形式返回结果,返回自系统启动以来经过的时间,包括深度睡眠时间。 | +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象,返回自系统启动以来经过的时间,包括深度睡眠时间。 | **示例:** - ```js - systemTime.getRealTime().then((data) => { - console.log(`systemTime.getRealTime success data: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.getRealTime because ` + JSON.stringify(error)); - }); - ``` - +```js +systemTime.getRealTime().then((data) => { + console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.setDate setDate(date: Date, callback: AsyncCallback<void>): void -设置系统日期,使用callback形式返回结果。 +设置系统日期,使用callback异步回调。 **需要权限:** ohos.permission.SET_TIME @@ -349,30 +338,29 @@ setDate(date: Date, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | --------------------- | | date | Date | 是 | 目标日期。 | -| callback | AsyncCallback<void> | 是 | 回调函数,可以在回调函数中处理接口返回值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** - ```js - var data = new Date(); - systemTime.setDate(data,(error, data) => { - if (error) { - console.error('failed to systemTime.setDate because ' + JSON.stringify(error)); - return; - } - console.info('systemTime.setDate success data : ' + JSON.stringify(data)); - }); - ``` - +```js +let data = new Date(); +systemTime.setDate(data,(error, data) => { + if (error) { + console.error('Failed to set system date. Cause:' + JSON.stringify(error)); + return; +} + console.info('Succeeded in setting system date. Data:' + JSON.stringify(data)); +}); +``` ## systemTime.setDate setDate(date: Date): Promise<void> -设置系统日期,使用Promise形式返回结果。 +设置系统日期,使用Promise异步回调。 **需要权限:** ohos.permission.SET_TIME @@ -388,52 +376,50 @@ setDate(date: Date): Promise<void> | 类型 | 说明 | | ------------------- | -------------------- | -| Promise<void> | 返回的异步回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** - ```js - var data = new Date(); - systemTime.setDate(data).then((value) => { - console.log(`systemTime.setDate success data : ` + JSON.stringify(value)); - }).catch((error) => { - console.error(`failed to systemTime.setDate because: ` + JSON.stringify(error)); - }); - ``` - +```js +let data = new Date(); +systemTime.setDate(data).then((value) => { + console.log(`Succeeded in setting system date. Data:` + JSON.stringify(value)); +}).catch((error) => { + console.error(`Failed to set system date. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.getDate8+ getDate(callback: AsyncCallback<Date>): void -获取当前系统日期,使用callback形式返回结果。 +获取当前系统日期,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------------------------- | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------- | ---- | --------------------- | | callback | AsyncCallback<Date> | 是 | 回调函数,返回当前系统日期。 | **示例:** - ```js - systemTime.getDate((error, data) => { - if (error) { - console.error(`failed to systemTime.getDate because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getDate success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getDate((error, data) => { + if (error) { + console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getDate8+ getDate(): Promise<Date> -获取当前系统日期,使用Promise形式返回结果。 +获取当前系统日期,使用Promise异步回调。 **系统能力:** SystemCapability.MiscServices.Time @@ -441,24 +427,23 @@ getDate(): Promise<Date> | 类型 | 说明 | | ------------------- | ----------------------------------------- | -| Promise<Date> | 以Promise形式返回结果,返回当前系统日期。 | +| Promise<Date> | Promise对象,返回当前系统日期。 | **示例:** - ```js - systemTime.getDate().then((data) => { - console.log(`systemTime.getDate success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.getDate because ` + JSON.stringify(error)); - }); - ``` - +```js +systemTime.getDate().then((data) => { + console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.setTimezone setTimezone(timezone: string, callback: AsyncCallback<void>): void -设置系统时区。 +设置系统时区,使用callback异步回调。 **需要权限:** ohos.permission.SET_TIME_ZONE @@ -466,29 +451,28 @@ setTimezone(timezone: string, callback: AsyncCallback<void>): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------- | ---- | -------------------------- | | timezone | string | 是 | 系统时区。 | -| callback | AsyncCallback<void> | 是 | 回调函数,可以在回调函数中处理接口返回值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。 | **示例:** - ```js - systemTime.setTimezone('Asia/Shanghai', (error, data) => { - if (error) { - console.error('failed to systemTime.setTimezone because ' + JSON.stringify(error)); - return; - } - console.info('SystemTimePlugin systemTime.setTimezone success data : ' + JSON.stringify(data)); - }); - ``` - +```js +systemTime.setTimezone('Asia/Shanghai', (error, data) => { + if (error) { + console.error('Failed to set system time zone. Cause:' + JSON.stringify(error)); + return; + } + console.info('Succeeded in setting system time zone. Data:' + JSON.stringify(data)); +}); +``` ## systemTime.setTimezone setTimezone(timezone: string): Promise<void> -设置系统时区。 +设置系统时区,使用Promise异步回调。 **需要权限:** ohos.permission.SET_TIME_ZONE @@ -504,51 +488,49 @@ setTimezone(timezone: string): Promise<void> | 类型 | 说明 | | ------------------- | -------------------- | -| Promise<void> | 返回的异步回调函数。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** - ```js - systemTime.setTimezone('Asia/Shanghai').then((data) => { - console.log(`systemTime.setTimezone success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.setTimezone because: ` + JSON.stringify(error)); - }); - ``` - +```js +systemTime.setTimezone('Asia/Shanghai').then((data) => { + console.log(`Succeeded in setting system time zone. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to set system time zone. Cause:` + JSON.stringify(error)); +}); +``` ## systemTime.getTimezone8+ getTimezone(callback: AsyncCallback<string>): void -获取系统时区,使用callback形式返回结果。 +获取系统时区,使用callback异步回调。 **系统能力:** SystemCapability.MiscServices.Time **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------ | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------- | ---- | ------------------------ | | callback | AsyncCallback<string> | 是 | 回调函数,返回系统时区。 | **示例:** - ```js - systemTime.getTimezone((error, data) => { - if (error) { - console.error(`failed to systemTime.getTimezone because ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.getTimezone success data : ` + JSON.stringify(data)); - }); - ``` - +```js +systemTime.getTimezone((error, data) => { + if (error) { + console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); + return; + } + console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); +}); +``` ## systemTime.getTimezone8+ getTimezone(): Promise<string> -获取系统时区,使用Promise形式返回结果。 +获取系统时区,使用Promise异步回调。 **系统能力:** SystemCapability.MiscServices.Time @@ -556,14 +538,14 @@ getTimezone(): Promise<string> | 类型 | 说明 | | --------------------- | ------------------------------------- | -| Promise<string> | 以Promise形式返回结果,返回系统时区。 | +| Promise<string> | Promise对象,返回系统时区。 | **示例:** - ```js - systemTime.getTimezone().then((data) => { - console.log(`systemTime.getTimezone success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.getTimezone because ` + JSON.stringify(error)); - }); - ``` \ No newline at end of file +```js +systemTime.getTimezone().then((data) => { + console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); +}).catch((error) => { + console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); +}); +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-system-timer.md b/zh-cn/application-dev/reference/apis/js-apis-system-timer.md index a8428fefc5956cce3dc06397b5a76f17ae6d0d30..24339605a5fb26ccb92e1be2e363dc27483fa0c1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-system-timer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-system-timer.md @@ -14,7 +14,7 @@ import systemTimer from '@ohos.systemTimer'; ``` -## systemTime.createTimer +## systemTimer.createTimer createTimer(options: TimerOptions, callback: AsyncCallback<number>): void @@ -55,7 +55,7 @@ export default { ``` -## systemTime.createTimer +## systemTimer.createTimer createTimer(options: TimerOptions): Promise<number> @@ -94,7 +94,7 @@ export default { ``` -## systemTime.startTimer +## systemTimer.startTimer startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void @@ -106,7 +106,7 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g | 参数名 | 类型 | 必填 | 说明 | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | 是 | 定时器的ID。 | +| timer | number | 是 | 定时器的ID。 | | triggerTime | number | 是 | 定时器的触发时间,单位:毫秒。 | @@ -114,12 +114,12 @@ startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void&g ```js export default { - systemTimer () { + async systemTimer () { var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime, (error, data) => { @@ -132,8 +132,8 @@ export default { } } ``` - -## systemTime.startTimer + +## systemTimer.startTimer startTimer(timer: number, triggerTime: number): Promise<void> @@ -153,12 +153,12 @@ startTimer(timer: number, triggerTime: number): Promise<void> ```js export default { - systemTimer (){ + async systemTimer (){ var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime).then((data) => { @@ -171,7 +171,7 @@ export default { ``` -## systemTime.stopTimer +## systemTimer.stopTimer stopTimer(timer: number, callback: AsyncCallback<void>): void @@ -189,16 +189,16 @@ stopTimer(timer: number, callback: AsyncCallback<void>): void ```js export default { - systemTimer () { + async systemTimer () { var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) - systemTimer.stoptTimer(timerId, (error, data) => { + systemTimer.stopTimer(timerId, (error, data) => { if (error) { console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); return; @@ -210,7 +210,7 @@ export default { ``` -## systemTime.stopTimer +## systemTimer.stopTimer stopTimer(timer: number): Promise<void> @@ -222,22 +222,22 @@ stopTimer(timer: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------- | ---- | ------------------------------------------------------------ | -| timer | number | 是 | 定时器的ID。 | +| timer | number | 是 | 定时器的ID。 | **示例:** ```js export default { - systemTimer (){ + async systemTimer (){ var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) - systemTimer.stoptTimer(timerId).then((data) => { + systemTimer.stopTimer(timerId).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -247,7 +247,7 @@ export default { ``` -## systemTime.destroyTimer +## systemTimer.destroyTimer destroyTimer(timer: number, callback: AsyncCallback<void>): void @@ -265,12 +265,12 @@ destroyTimer(timer: number, callback: AsyncCallback<void>): void ```js export default { - systemTimer () { + async systemTimer () { var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) @@ -287,7 +287,7 @@ export default { ``` -## systemTime.destroyTimer +## systemTimer.destroyTimer destroyTimer(timer: number): Promise<void> @@ -305,12 +305,12 @@ destroyTimer(timer: number): Promise<void> ```js export default { - systemTimer (){ + async systemTimer (){ var options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) + let timerId = await systemTimer.createTimer(options) let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) @@ -323,7 +323,7 @@ export default { } } ``` - + ## TimerOptions createTimer的初始化选项。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md index 98a499564467113a1fda62564c9f116658db6202..59f8191cdf9522b993ee139a046456ff8dec2f88 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-touchevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-touchevent.md @@ -54,19 +54,19 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | 名称 | 参数类型 | 可读 | 可写 | 描述 | | ----------- | ------ | ---- | ---- | ----------------------------------- | -| id | number | 是 | 否 | 指针标识 | -| pressedTime | number | 是 | 否 | 按下时的时间戳 | +| id | number | 是 | 否 | 触摸事件标识 | +| pressedTime | number | 是 | 否 | 按下时间戳 | | screenX | number | 是 | 否 | 触摸位置所属的屏幕x坐标 | | screenY | number | 是 | 否 | 触摸位置所属的屏幕y坐标 | | windowX | number | 是 | 否 | 触摸位置在窗口中的x坐标 | | windowY | number | 是 | 否 | 触摸位置在窗口中的y坐标 | | pressure | number | 是 | 否 | 压力值,取值范围是[0.0, 1.0], 0.0表示不支持 | -| width | number | 是 | 否 | 按下接触区域的宽度 | -| height | number | 是 | 否 | 按下接触区域的高度 | +| width | number | 是 | 否 | 触摸区域的宽度 | +| height | number | 是 | 否 | 触摸区域的高度 | | tiltX | number | 是 | 否 | 相对YZ平面的角度,取值的范围[-90, 90],其中正值是向右倾斜。 | | tiltY | number | 是 | 否 | 相对XZ平面的角度,值的范围[-90, 90],其中正值是向下倾斜。 | -| toolX | number | 是 | 否 | 工具区域的中心点X | -| toolY | number | 是 | 否 | 工具区域的中心点Y | +| toolX | number | 是 | 否 | 工具区域的中心点x坐标 | +| toolY | number | 是 | 否 | 工具区域的中心点y坐标 | | toolWidth | number | 是 | 否 | 工具区域宽度 | | toolHeight | number | 是 | 否 | 工具区域高度 | | rawX | number | 是 | 否 | 输入设备上的x坐标 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md index 2a9ecdf72e3e38ac84630ca6b447bb1fc6739297..2362b3a1e8b2048c9012f922350c88ced020ba0a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treemap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -94,7 +94,7 @@ isEmpty(): boolean const treeMap = new TreeMap(); let result = treeMap.isEmpty(); try { - treeMap.isEmpty.bind({})(); + treeMap.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -137,7 +137,7 @@ let result = treeMap.hasKey("squirrel"); treeMap.set("squirrel", 123); let result1 = treeMap.hasKey("squirrel"); try { - treeMap.hasKey.bind({}, "squirrel")(); + treeMap.hasKey.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -180,7 +180,7 @@ let result = treeMap.hasValue(123); treeMap.set("squirrel", 123); let result1 = treeMap.hasValue(123); try { - treeMap.hasValue.bind({}, 123)(); + treeMap.hasValue.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -223,7 +223,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); try { - treeMap.get.bind({}, "sparrow")(); + treeMap.get.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -260,7 +260,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); try { - treeMap.getFirstKey.bind({})(); + treeMap.getFirstKey.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -297,7 +297,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); try { - treeMap.getLastKey.bind({})(); + treeMap.getLastKey.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -335,7 +335,7 @@ treeMap.set("sparrow", 356); let map = new TreeMap(); treeMap.setAll(map); try { - treeMap.setAll.bind({}, map)(); + treeMap.setAll.bind({}, map)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -377,7 +377,7 @@ set(key: K, value: V): Object let treeMap = new TreeMap(); treeMap.set("squirrel", 123); try { - treeMap.set.bind({}, "squirrel", 123)(); + treeMap.set.bind({}, "squirrel", 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -420,7 +420,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.remove("sparrow"); try { - treeMap.remove.bind({}, "sparrow")(); + treeMap.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -464,7 +464,7 @@ treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getLowerKey("sparrow"); try { - treeMap.getLowerKey.bind({}, "sparrow")(); + treeMap.getLowerKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -508,7 +508,7 @@ treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getHigherKey("sparrow"); try { - treeMap.getHigherKey.bind({}, "sparrow")(); + treeMap.getHigherKey.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -550,7 +550,7 @@ let treeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); try { - treeMap.replace.bind({}, "sparrow", 357)(); + treeMap.replace.bind({}, "sparrow", 357)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -581,7 +581,7 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); try { - treeMap.clear.bind({})(); + treeMap.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -623,7 +623,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.keys.bind({})(); + treeMap.keys.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -665,7 +665,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.values.bind({})(); + treeMap.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -714,7 +714,7 @@ treeMap.forEach((value, key) => { try { treeMap.forEach.bind({}, (value, key) => { console.log("value:" + value, key); - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -757,7 +757,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap.entries.bind({})(); + treeMap.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -807,7 +807,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeMap[Symbol.iterator].bind({})(); + treeMap[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md index d2f8259399bc69099d1054342445469be05eec46..02102890f016d30d0f3a1712396683e4ebbb65a7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-treeset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -83,7 +83,7 @@ isEmpty(): boolean const treeSet = new TreeSet(); let result = treeSet.isEmpty(); try { - treeSet.isEmpty.bind({})(); + treeSet.isEmpty.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -118,7 +118,7 @@ treeSet.has(123); treeSet.add(123); let result1 = treeSet.has(123); try { - treeSet.has.bind({}, 123)(); + treeSet.has.bind({}, 123)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -147,7 +147,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); try { - treeSet.getFirstValue.bind({})(); + treeSet.getFirstValue.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -176,7 +176,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); try { - treeSet.getLastValue.bind({})(); + treeSet.getLastValue.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -209,7 +209,7 @@ add(value: T): boolean let treeSet = new TreeSet(); let result = treeSet.add("squirrel"); try { - treeSet.add.bind({}, "squirrel")(); + treeSet.add.bind({}, "squirrel")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -244,7 +244,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); try { - treeSet.remove.bind({}, "sparrow")(); + treeSet.remove.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -280,7 +280,7 @@ treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getLowerValue("sparrow"); try { - treeSet.getLowerValue.bind({}, "sparrow")(); + treeSet.getLowerValue.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -316,7 +316,7 @@ treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getHigherValue("sparrow"); try { - treeSet.getHigherValue.bind({}, "sparrow")(); + treeSet.getHigherValue.bind({}, "sparrow")(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -345,7 +345,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); try { - treeSet.popFirst.bind({})(); + treeSet.popFirst.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -374,7 +374,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); try { - treeSet.popLast.bind({})(); + treeSet.popLast.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -397,7 +397,7 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); try { - treeSet.clear.bind({})(); + treeSet.clear.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -431,7 +431,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet.values.bind({})(); + treeSet.values.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -472,7 +472,7 @@ treeSet.forEach((value, key) => { try { treeSet.forEach.bind({}, (value, key) => { console.log("value:" + value, key) - })(); + })(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -507,7 +507,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet.entries.bind({})(); + treeSet.entries.bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } @@ -548,7 +548,7 @@ while(temp != undefined) { temp = iter.next().value; } try { - treeSet[Symbol.iterator].bind({})(); + treeSet[Symbol.iterator].bind({})(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { console.log(`${err.code} - ${err.name} - ${err.message}`); } diff --git a/zh-cn/application-dev/reference/apis/js-apis-uitest.md b/zh-cn/application-dev/reference/apis/js-apis-uitest.md index aa35794cc466b4e592cedeaa16be6400d9caba9c..0876c020eb9f4aa92054c5fe2e78993b68e3f2d6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uitest.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uitest.md @@ -6,11 +6,11 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 - [On9+](#on9):提供控件特征描述能力,用于控件筛选匹配查找。 - [Component9+](#component9):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。 -- [Driver9+](#driver9):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能能力。 -- [UiWindow9+](#uiwindow9):入口类,提供窗口属性获取,窗口拖动、调整窗口大小等能能力。 -- [By](#by):提供控件特征描述能力,用于控件筛选匹配查找。从API version9开始不再维护,建议使用[[On9+](#on9)](#driver9)。 -- [UiComponent](#uicomponent):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。从API version9开始不再维护,建议使用[Component9+](#component9)。 -- [UiDriver](#uidriver):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能能力。从API version9开始不再维护,建议使用[Driver9+](#driver9)。 +- [Driver9+](#driver9):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能力。 +- [UiWindow9+](#uiwindow9):入口类,提供窗口属性获取,窗口拖动、调整窗口大小等能力。 +- [By(deprecated)](#bydeprecated):提供控件特征描述能力,用于控件筛选匹配查找。从API version 9开始不再维护,建议使用[On9+](#on9)。 +- [UiComponent(deprecated)](#uicomponentdeprecated):代表UI界面上的指定控件,提供控件属性获取,控件点击,滑动查找,文本注入等能力。从API version 9开始不再维护,建议使用[Component9+](#component9)。 +- [UiDriver(deprecated)](#uidriverdeprecated):入口类,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等能力。从API version 9开始不再维护,建议使用[Driver9+](#driver9)。 >**说明:** > @@ -20,7 +20,7 @@ UiTest提供模拟UI操作的能力,供开发者在测试场景使用,主要 ## 导入模块 ```js -import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest' +import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest'; ``` ## MatchPattern @@ -118,11 +118,11 @@ import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern ## On9+ -UiTest框架在API9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
+UiTest框架在API 9中,通过On类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
On提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[ON.isBefore](#isbefore)和[ON.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
On类提供的所有API均为同步接口,建议使用者通过静态构造器ON来链式创建On对象。 ```js -ON.text('123').type('button') +ON.text('123').type('button'); ``` ### text9+ @@ -149,7 +149,7 @@ text(txt: string, pattern?: MatchPattern): On **示例:** ```js -let on = ON.text('123') //使用静态构造器ON创建On对象,指定目标控件的text属性。 +let on = ON.text('123'); // 使用静态构造器ON创建On对象,指定目标控件的text属性。 ``` @@ -176,7 +176,7 @@ id(id: string): On **示例:** ```js -let on = ON.id(123) //使用静态构造器ON创建On对象,指定目标控件的id属性。 +let on = ON.id('123'); // 使用静态构造器ON创建On对象,指定目标控件的id属性。 ``` @@ -203,7 +203,7 @@ type(tp: string): On **示例:** ```js -let on = ON.type('button') //使用静态构造器ON创建On对象,指定目标控件的控件类型属性。 +let on = ON.type('button'); // 使用静态构造器ON创建On对象,指定目标控件的控件类型属性。 ``` @@ -230,7 +230,7 @@ clickable(b?: boolean): On **示例:** ```js -let on = ON.clickable(true) //使用静态构造器ON创建On对象,指定目标控件的可点击状态属性。 +let on = ON.clickable(true); // 使用静态构造器ON创建On对象,指定目标控件的可点击状态属性。 ``` ### longClickable9+ @@ -256,7 +256,7 @@ longClickable(b?: boolean): On **示例:** ```js -let on = ON.longClickable(true) //使用静态构造器ON创建On对象,指定目标控件的可长按点击状态属性。 +let on = ON.longClickable(true); // 使用静态构造器ON创建On对象,指定目标控件的可长按点击状态属性。 ``` @@ -283,7 +283,7 @@ scrollable(b?: boolean): On **示例:** ```js -let on = ON.scrollable(true) //使用静态构造器ON创建On对象,指定目标控件的可滑动状态属性。 +let on = ON.scrollable(true); // 使用静态构造器ON创建On对象,指定目标控件的可滑动状态属性。 ``` ### enabled9+ @@ -309,7 +309,7 @@ enabled(b?: boolean): On **示例:** ```js -let on = ON.enabled(true) //使用静态构造器ON创建On对象,指定目标控件的使能状态属性。 +let on = ON.enabled(true); // 使用静态构造器ON创建On对象,指定目标控件的使能状态属性。 ``` ### focused9+ @@ -335,7 +335,7 @@ focused(b?: boolean): On **示例:** ```js -let on = ON.focused(true) //使用静态构造器ON创建On对象,指定目标控件的获焦状态属性。 +let on = ON.focused(true); // 使用静态构造器ON创建On对象,指定目标控件的获焦状态属性。 ``` ### selected9+ @@ -361,7 +361,7 @@ selected(b?: boolean): On **示例:** ```js -let on = ON.selected(true) //使用静态构造器ON创建On对象,指定目标控件的被选中状态属性。 +let on = ON.selected(true); // 使用静态构造器ON创建On对象,指定目标控件的被选中状态属性。 ``` ### checked9+ @@ -387,7 +387,7 @@ checked(b?: boolean): On **示例:** ```js -let on = ON.checked(true) //使用静态构造器ON创建On对象,指定目标控件的被勾选状态属性 +let on = ON.checked(true); // 使用静态构造器ON创建On对象,指定目标控件的被勾选状态属性 ``` ### checkable9+ @@ -413,7 +413,7 @@ checkable(b?: boolean): On **示例:** ```js -let on = ON.checkable(true) //使用静态构造器ON创建On对象,指定目标控件的能否被勾选状态属性。 +let on = ON.checkable(true); // 使用静态构造器ON创建On对象,指定目标控件的能否被勾选状态属性。 ``` ### isBefore9+ @@ -439,7 +439,7 @@ isBefore(on: On): On **示例:** ```js -let on = ON.isBefore(ON.text('123')) //使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之前。 +let on = ON.isBefore(ON.text('123')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之前。 ``` ### isAfter9+ @@ -465,7 +465,7 @@ isAfter(on: On): On **示例:** ```js -let on = ON.isAfter(ON.text('123')) //使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之后。 +let on = ON.isAfter(ON.text('123')); // 使用静态构造器ON创建On对象,指定目标控件位于给出的特征属性控件之后。 ``` ## Component9+ @@ -494,9 +494,9 @@ click(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - await button.click() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.click(); } ``` @@ -521,9 +521,9 @@ doubleClick(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - await button.doubleClick() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.doubleClick(); } ``` @@ -548,9 +548,9 @@ longClick(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - await button.longClick() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.longClick(); } ``` @@ -581,9 +581,9 @@ getId(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let num = await button.getId() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let num = await button.getId(); } ``` @@ -614,9 +614,9 @@ getText(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let text = await button.getText() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let text = await button.getText(); } ``` @@ -647,9 +647,9 @@ getType(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let type = await button.getType() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let type = await button.getType(); } ``` @@ -680,9 +680,9 @@ getBounds(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let rect = await button.getBounds() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let rect = await button.getBounds(); } ``` @@ -713,9 +713,9 @@ getBoundsCenter(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let point = await button.getBoundsCenter() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let point = await button.getBoundsCenter(); } ``` @@ -746,13 +746,12 @@ isClickable(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isClickable()) { - console.info('This button can be Clicked') - } - else{ - console.info('This button can not be Clicked') + console.info('This button can be Clicked'); + } else { + console.info('This button can not be Clicked'); } } ``` @@ -784,13 +783,12 @@ isLongClickable(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isLongClickable()) { - console.info('This button can longClick') - } - else{ - console.info('This button can not longClick') + console.info('This button can longClick'); + } else { + console.info('This button can not longClick'); } } ``` @@ -822,13 +820,12 @@ isChecked(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('Checkbox')) + let driver = Driver.create(); + let checkBox = await driver.findComponent(ON.type('Checkbox')); if(await checkBox.isChecked) { - console.info('This checkBox is checked') - } - else{ - console.info('This checkBox is not checked') + console.info('This checkBox is checked'); + } else { + console.info('This checkBox is not checked'); } } ``` @@ -860,13 +857,12 @@ isCheckable(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('Checkbox')) + let driver = Driver.create(); + let checkBox = await driver.findComponent(ON.type('Checkbox')); if(await checkBox.isCheckable) { - console.info('This checkBox is checkable') - } - else{ - console.info('This checkBox is not checkable') + console.info('This checkBox is checkable'); + } else { + console.info('This checkBox is not checkable'); } } ``` @@ -898,13 +894,12 @@ isScrollable(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.scrollable(true)) + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.scrollable(true)); if(await scrollBar.isScrollable()) { - console.info('This scrollBar can be operated') - } - else{ - console.info('This scrollBar can not be operated') + console.info('This scrollBar can be operated'); + } else { + console.info('This scrollBar can not be operated'); } } ``` @@ -937,13 +932,12 @@ isEnabled(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isEnabled()) { - console.info('This button can be operated') - } - else{ - console.info('This button can not be operated') + console.info('This button can be operated'); + } else { + console.info('This button can not be operated'); } } @@ -976,13 +970,12 @@ isFocused(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isFocused()) { - console.info('This button is focused') - } - else{ - console.info('This button is not focused') + console.info('This button is focused'); + } else { + console.info('This button is not focused'); } } ``` @@ -1014,13 +1007,12 @@ isSelected(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isSelected()) { - console.info('This button is selected') - } - else{ - console.info('This button is not selected') + console.info('This button is selected'); + } else { + console.info('This button is not selected'); } } ``` @@ -1052,9 +1044,9 @@ inputText(text: string): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.text('hello world')) - await text.inputText('123') + let driver = Driver.create(); + let text = await driver.findComponent(ON.text('hello world')); + await text.inputText('123'); } ``` @@ -1077,9 +1069,9 @@ clearText(): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.text('hello world')) - await text.clearText() + let driver = Driver.create(); + let text = await driver.findComponent(ON.text('hello world')); + await text.clearText(); } ``` @@ -1116,9 +1108,9 @@ scrollSearch(on: ON): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('Scroll')) - let button = await scrollBar.scrollSearch(ON.text('next page')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('Scroll')); + let button = await scrollBar.scrollSearch(ON.text('next page')); } ``` @@ -1149,9 +1141,9 @@ scrollToTop(speed?: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('Scroll')) - await scrollBar.scrollToTop() + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.type('Scroll')); + await scrollBar.scrollToTop(); } ``` @@ -1182,9 +1174,9 @@ scrollToBottom(speed?: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('Scroll')) - await scrollBar.scrollToBottom() + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.type('Scroll')); + await scrollBar.scrollToBottom(); } ``` @@ -1215,10 +1207,10 @@ dragTo(target: Component): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('button')) - let text = await driver.findComponent(ON.text('hello world')) - await button.dragTo(text) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let text = await driver.findComponent(ON.text('hello world')); + await button.dragTo(text); } ``` @@ -1249,9 +1241,9 @@ pinchOut(scale: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('image')) - await image.pinchOut(1.5) + let driver = Driver.create(); + let image = await driver.findComponent(ON.type('image')); + await image.pinchOut(1.5); } ``` @@ -1282,9 +1274,9 @@ pinchIn(scale: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.type('image')) - await image.pinchIn(0.5) + let driver = Driver.create(); + let image = await driver.findComponent(ON.type('image')); + await image.pinchIn(0.5); } ``` @@ -1319,7 +1311,7 @@ static create(): Driver ```js async function demo() { - let driver = Driver.create() + let driver = Driver.create(); } ``` @@ -1349,8 +1341,8 @@ Driver对象在给定的时间内延时。 ```js async function demo() { - let driver = Driver.create() - await driver.delayMs(1000) + let driver = Driver.create(); + await driver.delayMs(1000); } ``` @@ -1386,8 +1378,8 @@ findComponent(on: On): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.findComponent(ON.text('next page')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.text('next page')); } ``` @@ -1423,8 +1415,8 @@ findComponents(on: On): Promise\> ```js async function demo() { - let driver = Driver.create() - let buttonList = await driver.findComponents(ON.text('next page')) + let driver = Driver.create(); + let buttonList = await driver.findComponents(ON.text('next page')); } ``` @@ -1460,8 +1452,8 @@ findWindow(filter: WindowFilter): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); } ``` @@ -1498,8 +1490,8 @@ waitForComponent(on: On, time: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let button = await driver.waitForComponent(ON.text('next page'),500) + let driver = Driver.create(); + let button = await driver.waitForComponent(ON.text('next page'),500); } ``` @@ -1530,8 +1522,8 @@ assertComponentExist(on: On): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.assertComponentExist(ON.text('next page')) + let driver = Driver.create(); + await driver.assertComponentExist(ON.text('next page')); } ``` @@ -1555,8 +1547,8 @@ Driver对象进行点击BACK键的操作。 ```js async function demo() { - let driver = Driver.create() - await driver.pressBack() + let driver = Driver.create(); + await driver.pressBack(); } ``` @@ -1586,8 +1578,8 @@ Driver对象采取如下操作:传入key值实现模拟点击对应按键的 ```js async function demo() { - let driver = Driver.create() - await driver.triggerKey(123) + let driver = Driver.create(); + await driver.triggerKey(123); } ``` @@ -1619,8 +1611,8 @@ Driver对象通过给定的key值,找到对应组合键并点击。例如,Ke ```js async function demo() { - let driver = Driver.create() - await driver.triggerCombineKeys(2072, 2047, 2035) + let driver = Driver.create(); + await driver.triggerCombineKeys(2072, 2047, 2035); } ``` @@ -1652,8 +1644,8 @@ Driver对象采取如下操作:在目标坐标点单击。 ```js async function demo() { - let driver = Driver.create() - await driver.click(100,100) + let driver = Driver.create(); + await driver.click(100,100); } ``` @@ -1684,8 +1676,8 @@ Driver对象采取如下操作:在目标坐标点双击。 ```js async function demo() { - let driver = Driver.create() - await driver.doubleClick(100,100) + let driver = Driver.create(); + await driver.doubleClick(100,100); } ``` @@ -1716,8 +1708,8 @@ Driver对象采取如下操作:在目标坐标点长按。 ```js async function demo() { - let driver = Driver.create() - await driver.longClick(100,100) + let driver = Driver.create(); + await driver.longClick(100,100); } ``` @@ -1751,8 +1743,8 @@ Driver对象采取如下操作:从起始坐标点滑向目的坐标点。 ```js async function demo() { - let driver = Driver.create() - await driver.swipe(100,100,200,200,600) + let driver = Driver.create(); + await driver.swipe(100,100,200,200,600); } ``` @@ -1786,8 +1778,8 @@ Driver对象采取如下操作:从起始坐标点拖拽至目的坐标点。 ```js async function demo() { - let driver = Driver.create() - await driver.drag(100,100,200,200,600) + let driver = Driver.create(); + await driver.drag(100,100,200,200,600); } ``` @@ -1823,8 +1815,8 @@ Driver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 ```js async function demo() { - let driver = Driver.create() - await driver.screenCap('/local/tmp/') + let driver = Driver.create(); + await driver.screenCap('/local/tmp/'); } ``` @@ -1854,8 +1846,8 @@ setDisplayRotation(rotation: DisplayRotation): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.setDisplayRotation(DisplayRotation.ROTATION_180) + let driver = Driver.create(); + await driver.setDisplayRotation(DisplayRotation.ROTATION_180); } ``` @@ -1885,8 +1877,8 @@ getDisplayRotation(): Promise\ ```js async function demo() { - let driver = Driver.create() - let rotation = await driver.getDisplayRotation() + let driver = Driver.create(); + let rotation = await driver.getDisplayRotation(); } ``` @@ -1916,8 +1908,8 @@ setDisplayRotationEnabled(enabled: boolean): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.setDisplayRotationEnabled(false) + let driver = Driver.create(); + await driver.setDisplayRotationEnabled(false); } ``` @@ -1947,8 +1939,8 @@ getDisplaySize(): Promise\ ```js async function demo() { - let driver = Driver.create() - let size = await driver.getDisplaySize() + let driver = Driver.create(); + let size = await driver.getDisplaySize(); } ``` @@ -1978,8 +1970,8 @@ getDisplayDensity(): Promise\ ```js async function demo() { - let driver = Driver.create() - let density = await driver.getDisplayDensity() + let driver = Driver.create(); + let density = await driver.getDisplayDensity(); } ``` @@ -2003,8 +1995,8 @@ wakeUpDisplay(): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.wakeUpDisplay() + let driver = Driver.create(); + await driver.wakeUpDisplay(); } ``` @@ -2028,8 +2020,8 @@ pressHome(): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.pressHome() + let driver = Driver.create(); + await driver.pressHome(); } ``` @@ -2066,8 +2058,8 @@ waitForIdle(idleTime: number, timeout: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let idled = await driver.waitForIdle(4000,5000) + let driver = Driver.create(); + let idled = await driver.waitForIdle(4000,5000); } ``` @@ -2100,8 +2092,8 @@ fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ ```js async function demo() { - let driver = Driver.create() - await driver.fling({X: 500, Y: 480},{X: 450, Y: 480},5,600) + let driver = Driver.create(); + await driver.fling({X: 500, Y: 480},{X: 450, Y: 480},5,600); } ``` @@ -2138,14 +2130,15 @@ injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let name = await window.getBundleName() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let name = await window.getBundleName(); } ``` @@ -2277,9 +2270,9 @@ getBounds(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let rect = await window.getBounds() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let rect = await window.getBounds(); } ``` @@ -2310,9 +2303,9 @@ getTitle(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let rect = await window.getTitle() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let rect = await window.getTitle(); } ``` @@ -2343,9 +2336,9 @@ getWindowMode(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let mode = await window.getWindowMode() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let mode = await window.getWindowMode(); } ``` @@ -2376,9 +2369,9 @@ isFocused(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let focused = await window.isFocused() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let focused = await window.isFocused(); } ``` @@ -2409,9 +2402,9 @@ isActived(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - let focused = await window.isActived() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let focused = await window.isActived(); } ``` @@ -2436,9 +2429,9 @@ focus(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.focus() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.focus(); } ``` @@ -2471,9 +2464,9 @@ moveTo(x: number, y: number): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.moveTo(100, 100) + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.moveTo(100, 100); } ``` @@ -2507,9 +2500,9 @@ resize(wide: number, height: number, direction: ResizeDirection): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.resize(100, 100, ResizeDirection.LEFT) + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.resize(100, 100, ResizeDirection.LEFT); } ``` @@ -2535,9 +2528,9 @@ split(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.split() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.split(); } ``` @@ -2563,9 +2556,9 @@ maximize(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.maximize() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.maximize(); } ``` @@ -2591,9 +2584,9 @@ minimize(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.minimize() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.minimize(); } ``` @@ -2619,9 +2612,9 @@ resume(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.resume() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.resume(); } ``` @@ -2647,21 +2640,21 @@ close(): Promise\ ```js async function demo() { - let driver = Driver.create() - let window = await driver.findWindow({actived: true}) - await window.close() + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.close(); } ``` ## By(deprecated) UiTest框架通过By类提供了丰富的控件特征描述API,用于进行控件筛选来匹配/查找出目标控件。
-By提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[By.isBefore](#isbefore)和[By.isAfter](#isafter)等API限定邻近控件特征进行辅助定位。
By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。 +By提供的API能力具有以下几个特点:
1、支持单属性匹配和多属性组合匹配,例如同时指定目标控件text和id。
2、控件属性支持多种匹配模式。
3、支持控件绝对定位,相对定位,可通过[By.isBefore(deprecated)](#isbeforedeprecated)和[By.isAfter(deprecated)](#isafterdeprecated)等API限定邻近控件特征进行辅助定位。
By类提供的所有API均为同步接口,建议使用者通过静态构造器BY来链式创建By对象。 -从API version9开始不再维护,建议使用[On9+](#on9)。 +从API version 9开始不再维护,建议使用[On9+](#on9)。 ```js -BY.text('123').type('button') +BY.text('123').type('button'); ``` ### text(deprecated) @@ -2670,7 +2663,7 @@ text(txt: string, pattern?: MatchPattern): By 指定目标控件文本属性,支持多种匹配模式,返回By对象自身。 -从API version9开始不再维护,建议使用[text9+](#text9)。 +从API version 9开始不再维护,建议使用[text9+](#text9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2683,14 +2676,14 @@ text(txt: string, pattern?: MatchPattern): By **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------- | -| [By](#by) | 返回指定目标控件文本属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件文本属性的By对象。 | **示例:** ```js -let by = BY.text('123') //使用静态构造器BY创建by对象,指定目标控件的text属性。 +let by = BY.text('123'); // 使用静态构造器BY创建by对象,指定目标控件的text属性。 ``` @@ -2700,7 +2693,7 @@ key(key: string): By 指定目标控件key值属性,返回By对象自身。 -从API version9开始不再维护,建议使用[id9+](#id9)。 +从API version 9开始不再维护,建议使用[id9+](#id9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2712,14 +2705,14 @@ key(key: string): By **返回值:** -| 类型 | 说明 | -| --------- | ----------------------------------- | -| [By](#by) | 返回指定目标控件key值属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ----------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件key值属性的By对象。 | **示例:** ```js -let by = BY.key('123') //使用静态构造器BY创建by对象,指定目标控件的key值属性。 +let by = BY.key('123'); // 使用静态构造器BY创建by对象,指定目标控件的key值属性。 ``` @@ -2729,7 +2722,7 @@ id(id: number): By 指定目标控件id属性,返回By对象自身。 -从API version9开始废弃。 +从API version 9开始废弃。 **系统能力**:SystemCapability.Test.UiTest @@ -2741,14 +2734,14 @@ id(id: number): By **返回值:** -| 类型 | 说明 | -| --------- | -------------------------------- | -| [By](#by) | 返回指定目标控件id属性的By对象。 | +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件id属性的By对象。 | **示例:** ```js -let by = BY.id(123) //使用静态构造器BY创建by对象,指定目标控件的id属性。 +let by = BY.id(123); // 使用静态构造器BY创建by对象,指定目标控件的id属性。 ``` @@ -2758,7 +2751,7 @@ type(tp: string): By 指定目标控件的控件类型属性,返回By对象自身。 -从API version9开始不再维护,建议使用[type9+](#type9)。 +从API version 9开始不再维护,建议使用[type9+](#type9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2770,14 +2763,14 @@ type(tp: string): By **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的控件类型属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的控件类型属性的By对象。 | **示例:** ```js -let by = BY.type('button') //使用静态构造器BY创建by对象,指定目标控件的控件类型属性。 +let by = BY.type('button'); // 使用静态构造器BY创建by对象,指定目标控件的控件类型属性。 ``` @@ -2787,7 +2780,7 @@ clickable(b?: boolean): By 指定目标控件的可点击状态属性,返回By对象自身。 -从API version9开始不再维护,建议使用[clickable9+](#clickable9)。 +从API version 9开始不再维护,建议使用[clickable9+](#clickable9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2799,14 +2792,14 @@ clickable(b?: boolean): By **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的可点击状态属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ------------------------------------------ | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的可点击状态属性的By对象。 | **示例:** ```js -let by = BY.clickable(true) //使用静态构造器BY创建by对象,指定目标控件的可点击状态属性。 +let by = BY.clickable(true); // 使用静态构造器BY创建by对象,指定目标控件的可点击状态属性。 ``` @@ -2816,7 +2809,7 @@ scrollable(b?: boolean): By 指定目标控件的可滑动状态属性,返回By对象自身。 -从API version9开始不再维护,建议使用[scrollable9+](#scrollable9)。 +从API version 9开始不再维护,建议使用[scrollable9+](#scrollable9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2828,14 +2821,14 @@ scrollable(b?: boolean): By **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的可滑动状态属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ------------------------------------------ | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的可滑动状态属性的By对象。 | **示例:** ```js -let by = BY.scrollable(true) //使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性。 +let by = BY.scrollable(true); // 使用静态构造器BY创建by对象,指定目标控件的可滑动状态属性。 ``` ### enabled(deprecated) @@ -2844,7 +2837,7 @@ enabled(b?: boolean): By 指定目标控件的使能状态属性,返回By对象自身。 -从API version9开始不再维护,建议使用[enabled9+](#enabled9)。 +从API version 9开始不再维护,建议使用[enabled9+](#enabled9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2856,14 +2849,14 @@ enabled(b?: boolean): By **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的使能状态属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的使能状态属性的By对象。 | **示例:** ```js -let by = BY.enabled(true) //使用静态构造器BY创建by对象,指定目标控件的使能状态属性。 +let by = BY.enabled(true); // 使用静态构造器BY创建by对象,指定目标控件的使能状态属性。 ``` ### focused(deprecated) @@ -2872,7 +2865,7 @@ focused(b?: boolean): By 指定目标控件的获焦状态属性,返回By对象自身。 -从API version9开始不再维护,建议使用[focused9+](#focused9)。 +从API version 9开始不再维护,建议使用[focused9+](#focused9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2884,14 +2877,14 @@ focused(b?: boolean): By **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------- | -| [By](#by) | 返回指定目标控件的获焦状态属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的获焦状态属性的By对象。 | **示例:** ```js -let by = BY.focused(true) //使用静态构造器BY创建by对象,指定目标控件的获焦状态属性。 +let by = BY.focused(true); // 使用静态构造器BY创建by对象,指定目标控件的获焦状态属性。 ``` ### selected(deprecated) @@ -2900,7 +2893,7 @@ selected(b?: boolean): By 指定目标控件的被选中状态属性,返回By对象自身。 -从API version9开始不再维护,建议使用[selected9+](#selected9)。 +从API version 9开始不再维护,建议使用[selected9+](#selected9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2912,14 +2905,14 @@ selected(b?: boolean): By **返回值:** -| 类型 | 说明 | -| --------- | ------------------------------------------ | -| [By](#by) | 返回指定目标控件的被选中状态属性的By对象。 | +| 类型 | 说明 | +| ------------------- | ------------------------------------------ | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件的被选中状态属性的By对象。 | **示例:** ```js -let by = BY.selected(true) //使用静态构造器BY创建by对象,指定目标控件的被选中状态属性。 +let by = BY.selected(true); // 使用静态构造器BY创建by对象,指定目标控件的被选中状态属性。 ``` ### isBefore(deprecated) @@ -2928,26 +2921,26 @@ isBefore(by: By): By 指定目标控件位于给出的特征属性控件之前,返回By对象自身。 -从API version9开始不再维护,建议使用[isBefore9+](#isbefore9)。 +从API version 9开始不再维护,建议使用[isBefore9+](#isbefore9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ---------------- | -| by | [By](#by) | 是 | 特征控件的属性。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | ---------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 特征控件的属性。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------------------- | -| [By](#by) | 返回指定目标控件位于给出的特征属性控件之前的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件位于给出的特征属性控件之前的By对象。 | **示例:** ```js -let by = BY.isBefore(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前。 +let by = BY.isBefore(BY.text('123')); // 使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之前。 ``` ### isAfter(deprecated) @@ -2956,26 +2949,26 @@ isAfter(by: By): By 指定目标控件位于给出的特征属性控件之后,返回By对象自身。 -从API version9开始不再维护,建议使用[isAfter9+](#isafter9)。 +从API version 9开始不再维护,建议使用[isAfter9+](#isafter9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | ---------------- | -| by | [By](#by) | 是 | 特征控件的属性。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | ---------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 特征控件的属性。 | **返回值:** -| 类型 | 说明 | -| --------- | ---------------------------------------------------- | -| [By](#by) | 返回指定目标控件位于给出的特征属性控件之后的By对象。 | +| 类型 | 说明 | +| ------------------- | ---------------------------------------------------- | +| [By(deprecated)](#bydeprecated) | 返回指定目标控件位于给出的特征属性控件之后的By对象。 | **示例:** ```js -let by = BY.isAfter(BY.text('123')) //使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后。 +let by = BY.isAfter(BY.text('123')); // 使用静态构造器BY创建by对象,指定目标控件位于给出的特征属性控件之后。 ``` ## UiComponent(deprecated) @@ -2983,7 +2976,7 @@ let by = BY.isAfter(BY.text('123')) //使用静态构造器BY创建by对象, UiTest中,UiComponent类代表了UI界面上的一个控件,提供控件属性获取,控件点击,滑动查找,文本注入等API。 该类提供的所有方法都使用Promise方式作为异步方法,需使用await调用。 -从API version9开始不再维护,建议使用[Component9+](#component9)。 +从API version 9开始不再维护,建议使用[Component9+](#component9)。 ### click(deprecated) @@ -2991,7 +2984,7 @@ click(): Promise\ 控件对象进行点击操作。 -从API version9开始不再维护,建议使用[click9+](#click9)。 +从API version 9开始不再维护,建议使用[click9+](#click9)。 **系统能力**:SystemCapability.Test.UiTest @@ -2999,9 +2992,9 @@ click(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.click() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.click(); } ``` @@ -3011,7 +3004,7 @@ doubleClick(): Promise\ 控件对象进行双击操作。 -从API version9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 +从API version 9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3019,9 +3012,9 @@ doubleClick(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.doubleClick() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.doubleClick(); } ``` @@ -3031,7 +3024,7 @@ longClick(): Promise\ 控件对象进行长按操作。 -从API version9开始不再维护,建议使用[longClick9+](#longclick9)。 +从API version 9开始不再维护,建议使用[longClick9+](#longclick9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3039,9 +3032,9 @@ longClick(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.longClick() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.longClick(); } ``` @@ -3051,7 +3044,7 @@ getId(): Promise\ 获取控件对象的id值。 -从API version9开始不再维护,被废弃。 +从API version 9开始不再维护,被废弃。 **系统能力**:SystemCapability.Test.UiTest @@ -3065,9 +3058,9 @@ getId(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let num = await button.getId() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let num = await button.getId(); } ``` @@ -3077,7 +3070,7 @@ getKey(): Promise\ 获取控件对象的key值。 -从API version9开始不再维护,建议使用[getId9+](#getid9) +从API version 9开始不再维护,建议使用[getId9+](#getid9) **系统能力**:SystemCapability.Test.UiTest @@ -3091,9 +3084,9 @@ getKey(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let str_key = await button.getKey() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let str_key = await button.getKey(); } ``` @@ -3103,7 +3096,7 @@ getText(): Promise\ 获取控件对象的文本信息。 -从API version9开始不再维护,建议使用[getText9+](#gettext9)。 +从API version 9开始不再维护,建议使用[getText9+](#gettext9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3117,9 +3110,9 @@ getText(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let text = await button.getText() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let text = await button.getText(); } ``` @@ -3129,7 +3122,7 @@ getType(): Promise\ 获取控件对象的控件类型。 -从API version9开始不再维护,建议使用[getType9+](#gettype9)。 +从API version 9开始不再维护,建议使用[getType9+](#gettype9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3143,9 +3136,9 @@ getType(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let type = await button.getType() + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let type = await button.getType(); } ``` @@ -3155,7 +3148,7 @@ isClickable(): Promise\ 获取控件对象可点击状态。 -从API version9开始不再维护,建议使用[isClickable9+](#isclickable9)。 +从API version 9开始不再维护,建议使用[isClickable9+](#isclickable9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3169,13 +3162,12 @@ isClickable(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); if(await button.isClickable()) { - console.info('This button can be Clicked') - } - else{ - console.info('This button can not be Clicked') + console.info('This button can be Clicked'); + } else { + console.info('This button can not be Clicked'); } } ``` @@ -3186,7 +3178,7 @@ isScrollable(): Promise\ 获取控件对象可滑动状态。 -从API version9开始不再维护,建议使用[isScrollable9+](#isscrollable9)。 +从API version 9开始不再维护,建议使用[isScrollable9+](#isscrollable9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3200,13 +3192,12 @@ isScrollable(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let driver = UiDriver.create(); + let scrollBar = await driver.findComponent(BY.scrollable(true)); if(await scrollBar.isScrollable()) { - console.info('This scrollBar can be operated') - } - else{ - console.info('This scrollBar can not be operated') + console.info('This scrollBar can be operated'); + } else { + console.info('This scrollBar can not be operated'); } } ``` @@ -3218,7 +3209,7 @@ isEnabled(): Promise\ 获取控件使能状态。 -从API version9开始不再维护,建议使用[isEnabled9+](#isenabled9)。 +从API version 9开始不再维护,建议使用[isEnabled9+](#isenabled9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3232,13 +3223,12 @@ isEnabled(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); if(await button.isEnabled()) { - console.info('This button can be operated') - } - else{ - console.info('This button can not be operated') + console.info('This button can be operated'); + } else { + console.info('This button can not be operated'); } } @@ -3250,7 +3240,7 @@ isFocused(): Promise\ 判断控件对象是否获焦。 -从API version9开始不再维护,建议使用[isFocused9+](#isfocused9)。 +从API version 9开始不再维护,建议使用[isFocused9+](#isfocused9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3264,13 +3254,12 @@ isFocused(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); if(await button.isFocused()) { - console.info('This button is focused') - } - else{ - console.info('This button is not focused') + console.info('This button is focused'); + } else { + console.info('This button is not focused'); } } ``` @@ -3281,7 +3270,7 @@ isSelected(): Promise\ 获取控件对象被选中状态。 -从API version9开始不再维护,建议使用[isSelected9+](#isselected9)。 +从API version 9开始不再维护,建议使用[isSelected9+](#isselected9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3295,13 +3284,12 @@ isSelected(): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); if(await button.isSelected()) { - console.info('This button is selected') - } - else{ - console.info('This button is not selected') + console.info('This button is selected'); + } else { + console.info('This button is not selected'); } } ``` @@ -3312,7 +3300,7 @@ inputText(text: string): Promise\ 向控件中输入文本(适用于文本框控件)。 -从API version9开始不再维护,建议使用[inputText9+](#inputtext9)。 +从API version 9开始不再维护,建议使用[inputText9+](#inputtext9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3326,9 +3314,9 @@ inputText(text: string): Promise\ ```js async function demo() { - let driver = UiDriver.create() - let text = await driver.findComponent(BY.text('hello world')) - await text.inputText('123') + let driver = UiDriver.create(); + let text = await driver.findComponent(BY.text('hello world')); + await text.inputText('123'); } ``` @@ -3338,29 +3326,29 @@ scrollSearch(by: By): Promise\ 在控件上滑动查找目标控件(适用于List等支持滑动的控件)。 -从API version9开始不再维护,建议使用[scrollSearch9+](#scrollsearch9)。 +从API version 9开始不再维护,建议使用[scrollSearch9+](#scrollsearch9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | ------------------------------------- | -| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的目标控件对象。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | ------------------------------------- | +| Promise\<[UiComponent(deprecated)](#uicomponentdeprecated)> | 以Promise形式返回找到的目标控件对象。 | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) - let button = await scrollBar.scrollSearch(BY.text('next page')) + let driver = UiDriver.create(); + let scrollBar = await driver.findComponent(BY.type('Scroll')); + let button = await scrollBar.scrollSearch(BY.text('next page')); } ``` @@ -3369,7 +3357,7 @@ async function demo() { UiDriver类为uitest测试框架的总入口,提供控件匹配/查找,按键注入,坐标点击/滑动,截图等API。 该类提供的方法除UiDriver.create()以外的所有方法都使用Promise方式作为异步方法,需使用await调用。 -从API version9开始不再维护,建议使用[Driver9+](#driver9)。 +从API version 9开始不再维护,建议使用[Driver9+](#driver9)。 ### create(deprecated) @@ -3377,7 +3365,7 @@ static create(): UiDriver 静态方法,构造一个UiDriver对象,并返回该对象。 -从API version9开始不再维护,建议使用[create9+](#create9)。 +从API version 9开始不再维护,建议使用[create9+](#create9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3391,7 +3379,7 @@ static create(): UiDriver ```js async function demo() { - let driver = UiDriver.create() + let driver = UiDriver.create(); } ``` @@ -3401,7 +3389,7 @@ delayMs(duration: number): Promise\ UiDriver对象在给定的时间内延时。 -从API version9开始不再维护,建议使用[delayMs9+](#delayms9)。 +从API version 9开始不再维护,建议使用[delayMs9+](#delayms9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3415,8 +3403,8 @@ UiDriver对象在给定的时间内延时。 ```js async function demo() { - let driver = UiDriver.create() - await driver.delayMs(1000) + let driver = UiDriver.create(); + await driver.delayMs(1000); } ``` @@ -3426,28 +3414,28 @@ findComponent(by: By): Promise\ 在UiDriver对象中,根据给出的目标控件属性要求查找目标控件。 -从API version9开始不再维护,建议使用[findComponent9+](#findcomponent9)。 +从API version 9开始不再维护,建议使用[findComponent9+](#findcomponent9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------- | --------------------------------- | -| Promise\<[UiComponent](#uicomponent)> | 以Promise形式返回找到的控件对象。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[UiComponent(deprecated)](#uicomponentdeprecated)> | 以Promise形式返回找到的控件对象。 | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.text('next page')) + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.text('next page')); } ``` @@ -3457,28 +3445,28 @@ findComponents(by: By): Promise\> 在UiDriver对象中,根据给出的目标控件属性要求查找出所有匹配控件,以列表保存。 -从API version9开始不再维护,建议使用[findComponents9+](#findcomponents9)。 +从API version 9开始不再维护,建议使用[findComponents9+](#findcomponents9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 目标控件的属性要求。 | **返回值:** -| 类型 | 说明 | -| --------------------------------------------- | --------------------------------------- | -| Promise\> | 以Promise形式返回找到的控件对象的列表。 | +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------------- | +| Promise\(deprecated)
](#uicomponentdeprecated)>> | 以Promise形式返回找到的控件对象的列表。 | **示例:** ```js async function demo() { - let driver = UiDriver.create() - let buttonList = await driver.findComponents(BY.text('next page')) + let driver = UiDriver.create(); + let buttonList = await driver.findComponents(BY.text('next page')); } ``` @@ -3488,22 +3476,22 @@ assertComponentExist(by: By): Promise\ 断言API,用于断言当前界面存在满足给出的目标控件属性的控件; 如果控件不存在,该API将抛出JS异常,使当前测试用例失败。 -从API version9开始不再维护,建议使用[assertComponentExist9+](#assertcomponentexist9)。 +从API version 9开始不再维护,建议使用[assertComponentExist9+](#assertcomponentexist9)。 **系统能力**:SystemCapability.Test.UiTest **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | --------- | ---- | -------------------- | -| by | [By](#by) | 是 | 目标控件的属性要求。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| by | [By(deprecated)](#bydeprecated) | 是 | 目标控件的属性要求。 | **示例:** ```js async function demo() { - let driver = UiDriver.create() - await driver.assertComponentExist(BY.text('next page')) + let driver = UiDriver.create(); + await driver.assertComponentExist(BY.text('next page')); } ``` @@ -3513,7 +3501,7 @@ pressBack(): Promise\ UiDriver对象进行点击BACK键的操作。 -从API version9开始不再维护,建议使用[pressBack9+](#pressback9)。 +从API version 9开始不再维护,建议使用[pressBack9+](#pressback9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3521,8 +3509,8 @@ UiDriver对象进行点击BACK键的操作。 ```js async function demo() { - let driver = UiDriver.create() - await driver.pressBack() + let driver = UiDriver.create(); + await driver.pressBack(); } ``` @@ -3532,7 +3520,7 @@ triggerKey(keyCode: number): Promise\ UiDriver对象采取如下操作:通过key值找到对应键并点击。 -从API version9开始不再维护,建议使用[triggerKey9+](#triggerkey9)。 +从API version 9开始不再维护,建议使用[triggerKey9+](#triggerkey9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3546,8 +3534,8 @@ UiDriver对象采取如下操作:通过key值找到对应键并点击。 ```js async function demo() { - let driver = UiDriver.create() - await driver.triggerKey(123) + let driver = UiDriver.create(); + await driver.triggerKey(123); } ``` @@ -3558,7 +3546,7 @@ click(x: number, y: number): Promise\ UiDriver对象采取如下操作:在目标坐标点单击。 -从API version9开始不再维护,建议使用[click9+](#click9)。 +从API version 9开始不再维护,建议使用[click9+](#click9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3573,8 +3561,8 @@ UiDriver对象采取如下操作:在目标坐标点单击。 ```js async function demo() { - let driver = UiDriver.create() - await driver.click(100,100) + let driver = UiDriver.create(); + await driver.click(100,100); } ``` @@ -3584,7 +3572,7 @@ doubleClick(x: number, y: number): Promise\ UiDriver对象采取如下操作:在目标坐标点双击。 -从API version9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 +从API version 9开始不再维护,建议使用[doubleClick9+](#doubleclick9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3599,8 +3587,8 @@ UiDriver对象采取如下操作:在目标坐标点双击。 ```js async function demo() { - let driver = UiDriver.create() - await driver.doubleClick(100,100) + let driver = UiDriver.create(); + await driver.doubleClick(100,100); } ``` @@ -3610,7 +3598,7 @@ longClick(x: number, y: number): Promise\ UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 -从API version9开始不再维护,建议使用[longClick9+](#longclick9)。 +从API version 9开始不再维护,建议使用[longClick9+](#longclick9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3625,8 +3613,8 @@ UiDriver对象采取如下操作:在目标坐标点长按下鼠标左键。 ```js async function demo() { - let driver = UiDriver.create() - await driver.longClick(100,100) + let driver = UiDriver.create(); + await driver.longClick(100,100); } ``` @@ -3636,7 +3624,7 @@ swipe(startx: number, starty: number, endx: number, endy: number): Promise\9+
](#swipe9)。 +从API version 9开始不再维护,建议使用[swipe9+](#swipe9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3653,8 +3641,8 @@ UiDriver对象采取如下操作:从给出的起始坐标点滑向给出的目 ```js async function demo() { - let driver = UiDriver.create() - await driver.swipe(100,100,200,200) + let driver = UiDriver.create(); + await driver.swipe(100,100,200,200); } ``` @@ -3664,7 +3652,7 @@ screenCap(savePath: string): Promise\ UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的图片至给出的保存路径中。 -从API version9开始不再维护,建议使用[screenCap9+](#screencap9)。 +从API version 9开始不再维护,建议使用[screenCap9+](#screencap9)。 **系统能力**:SystemCapability.Test.UiTest @@ -3684,7 +3672,7 @@ UiDriver对象采取如下操作:捕获当前屏幕,并保存为PNG格式的 ```js async function demo() { - let driver = UiDriver.create() - await driver.screenCap('/local/tmp/') + let driver = UiDriver.create(); + await driver.screenCap('/local/tmp/1.png'); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-update.md b/zh-cn/application-dev/reference/apis/js-apis-update.md index f6b29aa4c3a4b51193c7fcc15abcef1829e44d1f..1053f4629197be91c60382da5239cc8eeb6c08b5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-update.md +++ b/zh-cn/application-dev/reference/apis/js-apis-update.md @@ -102,7 +102,7 @@ try { let localUpdater = update.getLocalUpdater(); } catch(error) { console.error(`Fail to get localUpdater error: ${error}`); -} +}; ``` ## Updater @@ -844,7 +844,7 @@ const versionDigestInfo = { }; // 清除选项 -lconstet clearOptions = { +const clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, }; updater.clearError(versionDigestInfo, clearOptions).then(() => { @@ -1248,7 +1248,7 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\(deprecated)
+> **说明:**
+> 从API version 9开始废弃,建议使用[equalsTo9+](#equalsto9)替代。 equals(other: URI): boolean @@ -103,6 +105,33 @@ const uriInstance = new uri.URI('http://username:password@host:8080/directory/fi const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); uriInstance.equals(uriInstance1); ``` +### equalsTo9+ + +equalsTo(other: URI): boolean + +判断此URI是否与其他URI对象相等。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| other | [URI](#uri) | 是 | 需要比较的URI对象。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 返回true表示相等,否则返回false。 | + +**示例:** + +```js +const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +uriInstance.equalsTo(uriInstance1); +``` ### checkIsAbsolute diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index 44b873ad803829f77a47b79878496e9eaab5e92f..4a7cd31c53c0068fe76bd3f73177a9a98fc0c9b9 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -3,17 +3,374 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 - ## 导入模块 ``` import Url from '@ohos.url' ``` +## URLParams9+ -## URLSearchParams +### constructor9+ -### constructor +constructor(init?: string[][] | Record<string, string> | string | URLParams) + +URLParams的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| init | string[][] \| Record<string, string> \| string \| URLParams | 否 | 入参对象。
- string[][]:字符串二维数组
- Record<string, string>:对象列表
- string:字符串
- URLParams:对象 | + +**示例:** + +```js +let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); +let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'}); +let objectParams2 = new Url.URLParams('?fod=1&bard=2'); +let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let params = new Url.URLParams(urlObject.search); +``` + + +### append9+ + +append(name: string, value: string): void + +将新的键值对插入到查询字符串。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 需要插入搜索参数的键名。 | +| value | string | 是 | 需要插入搜索参数的值。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.append('fod', '3'); +``` + + +### delete9+ + +delete(name: string): void + +删除指定名称的键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 需要删除的键值名称。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsobject = new Url.URLParams(urlObject.search.slice(1)); +paramsobject.delete('fod'); +``` + + +### getAll9+ + +getAll(name: string): string[] + +获取指定名称的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 指定的键值名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string[] | 返回指定名称的所有键值对。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let params = new Url.URLParams(urlObject.search.slice(1)); +params.append('fod', '3'); // Add a second value for the fod parameter. +console.log(params.getAll('fod').toString()) // Output ["1","3"]. +``` + + +### entries9+ + +entries(): IterableIterator<[string, string]> + +返回一个ES6的迭代器,迭代器的每一项都是一个 JavaScript Array。Array的第一项是name,Array的第二项是value。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<[string, string]> | 返回一个ES6的迭代器。 | + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2"); +for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs + console.log(pair[0]+ ', '+ pair[1]); +} +``` + + +### forEach9+ + +forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void + +通过回调函数来遍历URLSearchParams实例对象上的键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callbackfn | function | 是 | 回调函数。 | +| thisArg | Object | 否 | callbackfn被调用时用作this值 | + +**表1** callbackfn的参数说明 + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| value | string | 是 | 当前遍历到的键值。 | +| key | string | 是 | 当前遍历到的键名。 | +| searchParams | Object | 是 | 当前调用forEach方法的实例对象。 | + +**示例:** + +```js +const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +myURLObject.URLParams.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.searchParams === searchParams); +}); +``` + + +### get9+ + +get(name: string): string | null + +获取指定名称对应的第一个值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 指定键值对的名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回第一个值。 | +| null | 如果没找到,返回 null。 | + +**示例:** + +```js +let paramsObject = new Url.URLParams('name=Jonathan&age=18'); +let name = paramsObject.get("name"); // is the string "Jonathan" +let age = parseInt(paramsObject.get("age"), 10); // is the number 18 +``` + + +### has9+ + +has(name: string): boolean + +判断一个指定的键名对应的值是否存在。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 要查找的参数的键名。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 是否存在相对应的key值,存在返回true,否则返回false。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.has('bard') === true; +``` + + +### set9+ + +set(name: string, value: string): void + +将与name关联的URLSearchParams对象中的值设置为value。如果存在名称为name的键值对,请将第一个键值对的值设置为value并删除所有其他值。如果不是,则将键值对附加到查询字符串。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 将要设置的参数的键值名。 | +| value | string | 是 | 所要设置的参数值。 | + +**示例:** + +```js +let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.set('baz', '3'); // Add a third parameter. +``` + + +### sort9+ + +sort(): void + +对包含在此对象中的所有键值对进行排序,并返回undefined。排序顺序是根据键的Unicode代码点。该方法使用稳定的排序算法 (即,将保留具有相等键的键值对之间的相对顺序)。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object +searchParamsObject.sort(); // Sort the key/value pairs +console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 +``` + + +### keys9+ + +keys(): IterableIterator<string> + +返回一个所有键值对的name的ES6迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<string> | 返回一个所有键值对的name的ES6迭代器。 | + +**示例:** + +```js +let searchParamsObject = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +for (var key of searchParamsObject .keys()) { // Output key-value pairs + console.log(key); +} +``` + + +### values9+ + +values(): IterableIterator<string> + +返回一个所有键值对的value的ES6迭代器。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<string> | 返回一个所有键值对的value的ES6迭代器。 | + +**示例:** + +```js +let searchParams = new Url.URLParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +for (var value of searchParams.values()) { + console.log(value); +} +``` + + +### [Symbol.iterator]9+ + +[Symbol.iterator]\(): IterableIterator<[string, string]> + +返回一个ES6的迭代器,迭代器的每一项都是一个 JavaScript Array。Array的第一项是name,Array的第二项是value。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| IterableIterator<[string, string]> | 返回一个ES6的迭代器。 | + +**示例:** + +```js +const paramsObject = new Url.URLParams('fod=bay&edg=bap'); +for (const [name, value] of paramsObject) { + console.log(name, value); +} +``` + + +### tostring9+ + +toString(): string + +返回序列化为字符串的搜索参数,必要时对字符进行百分比编码。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回序列化为字符串的搜索参数,必要时对字符进行百分比编码。 | + +**示例:** + +```js +let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let params = new Url.URLParams(url.search.slice(1)); +params.append('fod', '3'); +console.log(params.toString()); +``` + +## URLSearchParams(deprecated) + +### constructor(deprecated) + +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+](#constructor9+)替代。 constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) @@ -37,8 +394,10 @@ let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); let params = new Url.URLSearchParams(urlObject.search); ``` +### append(deprecated) -### append +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.append9+](#append9)替代。 append(name: string, value: string): void @@ -61,8 +420,10 @@ let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsObject.append('fod', '3'); ``` +### delete(deprecated) -### delete +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.delete9+](#delete9)替代。 delete(name: string): void @@ -84,8 +445,10 @@ let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1)); paramsobject.delete('fod'); ``` +### getAll(deprecated) -### getAll +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.getAll9+](#getall9)替代。 getAll(name: string): string[] @@ -114,8 +477,10 @@ params.append('fod', '3'); // Add a second value for the fod parameter. console.log(params.getAll('fod').toString()) // Output ["1","3"]. ``` +### entries(deprecated) -### entries +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.entries9+](#entries9)替代。 entries(): IterableIterator<[string, string]> @@ -139,7 +504,9 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ``` -### forEach +### forEach(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.forEach9+](#foreach9)替代。 forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void @@ -172,7 +539,9 @@ myURLObject.searchParams.forEach((value, name, searchParams) => { ``` -### get +### get(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.get9+](#get9)替代。 get(name: string): string | null @@ -202,7 +571,9 @@ let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ``` -### has +### has(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.has9+](#has9)替代。 has(name: string): boolean @@ -231,7 +602,9 @@ paramsObject.has('bard') === true; ``` -### set +### set(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.set9+](#set9)替代。 set(name: string, value: string): void @@ -255,7 +628,9 @@ paramsObject.set('baz', '3'); // Add a third parameter. ``` -### sort +### sort(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.sort9+](#sort9)替代。 sort(): void @@ -272,7 +647,9 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ``` -### keys +### keys(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.keys9+](#keys9)替代。 keys(): IterableIterator<string> @@ -296,7 +673,9 @@ for (var key of searchParamsObject .keys()) { // Output key-value pairs ``` -### values +### values(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.values9+](#values9)替代。 values(): IterableIterator<string> @@ -320,7 +699,9 @@ for (var value of searchParams.values()) { ``` -### [Symbol.iterator] +### [Symbol.iterator](deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.[Symbol.iterator]9+](#symbol.iterator9)替代。 [Symbol.iterator]\(): IterableIterator<[string, string]> @@ -343,8 +724,9 @@ for (const [name, value] of paramsObject) { } ``` - -### tostring +### tostring(deprecated) +> **说明:**
+> 从API version 9开始废弃,建议使用[URLParams9+.tostring9+](#tostring9)替代。 toString(): string @@ -367,7 +749,6 @@ params.append('fod', '3'); console.log(params.toString()); ``` - ## URL ### 属性 @@ -387,12 +768,13 @@ console.log(params.toString()); | protocol | string | 是 | 是 | 获取和设置URL的协议部分。 | | search | string | 是 | 是 | 获取和设置URL的序列化查询部分。 | | searchParams | URLsearchParams | 是 | 否 | 获取URLSearchParams表示URL查询参数的对象。 | +| URLParams | URLParams | 是 | 否 | 获取URLParams表示URL查询参数的对象。 | | username | string | 是 | 是 | 获取和设置URL的用户名部分。 | ### constructor -constructor(url: string, base?: string | URL) +constructor(url?: string, base?: string | URL) URL的构造函数。 @@ -422,6 +804,27 @@ new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ ``` +### parseURL9+ + +static parseURL(inputUrl : string, inputBase ?: string | URL) + +URL静态成员函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| inputUrl | string | 是 | 入参对象。 | +| inputBase | string \| URL | 否 | 入参字符串或者对象。
- string:字符串
- URL:字符串或对象 | + +**示例:** + +```js +let mm = 'http://username:password@host:8080'; +Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; +``` ### tostring @@ -464,3 +867,4 @@ toJSON(): string const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); url.toJSON(); ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb.md b/zh-cn/application-dev/reference/apis/js-apis-usb.md index ffa8e471f0e279279714c637cc16ecdd0f4a96f7..2780155db9df46c9eaeabed1696644f4c01128a2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usb.md @@ -107,7 +107,7 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> **错误码:** -以下错误码的详细介绍参见[USB错误码](../errorcodes/errcode-usb.md)。 +以下错误码的详细介绍参见[USB错误码](../errorcodes/errorcode-usb.md)。 | 错误码ID | 错误信息 | | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md similarity index 90% rename from zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md rename to zh-cn/application-dev/reference/apis/js-apis-userFileManager.md index ac164b3b6b8a98d7deb7ea3459009a68be9d43b8..5922f80b2d90d9ee2384292c82529fef8d671474 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @@ -3,8 +3,8 @@ 该模块提供用户数据管理能力,包括访问、修改用户等用户公共媒体数据信息等常用功能。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -> 本模块下的接口均为系统接口 +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块接口为系统接口。 ## 导入模块 @@ -26,7 +26,7 @@ getUserFileMgr(context: Context): UserFileManager | 参数名 | 类型 | 必填 | 说明 | | ------- | ------- | ---- | -------------------------- | -| context | [Context](#../apis/js-apis-Context.md) | 是 | 传入Ability实例的Context。 | +| context | [Context](js-apis-Context.md) | 是 | 传入Ability实例的Context。 | **返回值:** @@ -38,7 +38,7 @@ getUserFileMgr(context: Context): UserFileManager ```ts const context = getContext(this); -let mgr = userfilemanager.getUserFileMgr(context); +let mgr = userFileManager.getUserFileMgr(context); ``` ## userFileManager.getUserFileMgr @@ -62,7 +62,7 @@ getUserFileMgr(): UserFileManager **示例:** ```ts -let mgr = userfilemanager.getUserFileMgr(); +let mgr = userFileManager.getUserFileMgr(); ``` ## UserFileManager @@ -90,6 +90,8 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPhotoAssets'); let predicates = new dataSharePredicates.DataSharePredicates(); @@ -138,6 +140,8 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPhotoAssets'); let predicates = new dataSharePredicates.DataSharePredicates(); @@ -180,6 +184,8 @@ createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback& **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('createPhotoAssetDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -188,7 +194,7 @@ async function example() { }; let albums = await mgr.getPhotoAlbums(fetchOptions) let album = await albums.getFirstObject() - mgr.createPhotoAsset('testFile.txt', album.albumUri, (err, fileAsset) => { + mgr.createPhotoAsset('testFile.jpg', album.albumUri, (err, fileAsset) => { if (fileAsset != undefined) { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -221,7 +227,7 @@ createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): ```ts async function example() { console.info('createPhotoAssetDemo') - mgr.createPhotoAsset('testFile.txt', (err, fileAsset) => { + mgr.createPhotoAsset('testFile.jpg', (err, fileAsset) => { if (fileAsset != undefined) { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -261,7 +267,7 @@ createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset async function example() { console.info('createPhotoAssetDemo') try { - let fileAsset = await mgr.createPhotoAsset('testFile.txt') + let fileAsset = await mgr.createPhotoAsset('testFile.jpg') console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); } catch (err) { @@ -291,6 +297,8 @@ getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResul **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPhotoAlbumsDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -308,8 +316,9 @@ async function example() { console.info('album is undefined, err = ', err); } }) + } else { + console.info('getPhotoAlbums fail, message = ', err); } - console.info('getPhotoAlbums fail, message = ', err); }) } ``` @@ -339,6 +348,8 @@ getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>& **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPhotoAlbumsDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -449,6 +460,8 @@ getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getAudioAssets'); let predicates = new dataSharePredicates.DataSharePredicates(); @@ -457,7 +470,7 @@ async function example() { predicates: predicates }; - mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => { if (fetchResult != undefined) { console.info('fetchFileResult success'); let fileAsset = await fetchResult.getFirstObject(); @@ -497,6 +510,8 @@ getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getAudioAssets'); let predicates = new dataSharePredicates.DataSharePredicates(); @@ -505,7 +520,7 @@ async function example() { predicates: predicates }; try { - var fetchResult = await mgr.getPhotoAssets(fetchOptions) + var fetchResult = await mgr.getAudioAssets(fetchOptions) } catch (err) { console.info('getAudioAssets failed, message = ', err); } @@ -523,7 +538,7 @@ async function example() { delete(uri: string, callback: AsyncCallback<void>): void; -删除媒体文件。 +删除媒体文件,删除的文件进入到回收站。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -539,6 +554,8 @@ delete(uri: string, callback: AsyncCallback<void>): void; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('deleteAssetDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -570,7 +587,7 @@ async function example() { delete(uri: string): Promise<void>; -删除媒体文件。 +删除媒体文件,删除的文件进入到回收站。 **需要权限**:ohos.permission.READ_IMAGEVIDEO 和 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 和 ohos.permission.WRITE_AUDIO @@ -591,6 +608,8 @@ delete(uri: string): Promise<void>; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('deleteDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -637,10 +656,29 @@ on(type: ChangeEvent, callback: Callback<void>): void ```ts async function example() { - console.info('onDemo') - userFileMgr.on('imageChange', () => { - // image file had changed, do something - }); + console.info('onDemo') + let count = 0; + mgr.on('imageChange', () => { + count++; + // image file had changed, do something + }); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count > 0) { + console.info("onDemo success"); + } else { + console.info("onDemo fail"); + } + mgr.off('imageChange', () => { + // stop listening success + }); } ``` @@ -663,10 +701,31 @@ off(type: ChangeEvent, callback?: Callback<void>): void ```ts async function example() { - console.info('offDemo') - userFileMgr.off('imageChange', () => { - // stop listening success - }); + console.info('offDemo') + let count = 0; + mgr.on('imageChange', () => { + count++; + // image file had changed, do something + }); + + mgr.off('imageChange', () => { + // stop listening success + }); + + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count == 0) { + console.info("offDemo success"); + } else { + console.info("offDemo fail"); + } } ``` @@ -893,7 +952,10 @@ get(member: string): MemberType; | member | string | 是 | 成员参数名称例如:ImageVideoKey.URI | **示例:** + ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('fileAssetGetDemo') try { @@ -929,7 +991,10 @@ set(member: string, value: string): void; | value | string | 是 | 设置成员参数名称,只能修改ImageVideoKey.TITLE的值 | **示例:** + ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('fileAssetSetDemo') try { @@ -967,6 +1032,8 @@ commitModify(callback: AsyncCallback<void>): void **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('commitModifyDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1010,6 +1077,8 @@ commitModify(): Promise<void> **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('commitModifyDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1132,6 +1201,8 @@ close(fd: number, callback: AsyncCallback<void>): void **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('closeDemo') try { @@ -1180,6 +1251,8 @@ close(fd: number): Promise<void> **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('closeDemo') try { @@ -1214,11 +1287,13 @@ getThumbnail(callback: AsyncCallback<image.PixelMap>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getThumbnailDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1254,11 +1329,13 @@ getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------- | ---- | ---------------- | | size | Size | 是 | 缩略图尺寸 | -| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | 是 | 回调返回缩略图的PixelMap | **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getThumbnailDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1300,11 +1377,13 @@ getThumbnail(size?: Size): Promise<image.PixelMap> | 类型 | 说明 | | ----------------------------- | --------------------- | -| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise返回缩略图的PixelMap | **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getThumbnailDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1344,6 +1423,8 @@ favorite(isFavorite: boolean, callback: AsyncCallback<void>): void **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('favoriteDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1388,6 +1469,8 @@ favorite(isFavorite: boolean): Promise<void> **示例:** ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('favoriteDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1426,6 +1509,8 @@ getCount(): number **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getCountDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1456,6 +1541,8 @@ isAfterLast(): boolean **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { let predicates = new dataSharePredicates.DataSharePredicates(); let fetchOption = { @@ -1485,6 +1572,8 @@ close(): void **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('fetchResultCloseDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1515,6 +1604,8 @@ getFirstObject(callback: AsyncCallback<T>): void **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getFirstObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1550,6 +1641,8 @@ getFirstObject(): Promise<T> **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getFirstObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1580,6 +1673,8 @@ async function example() { **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getNextObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1618,6 +1713,8 @@ async function example() { **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getNextObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1651,6 +1748,8 @@ getLastObject(callback: AsyncCallback<T>): void **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getLastObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1686,6 +1785,8 @@ getLastObject(): Promise<T> **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getLastObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1717,6 +1818,8 @@ getPositionObject(index: number, callback: AsyncCallback<T>): void **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPositionObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1758,6 +1861,8 @@ getPositionObject(index: number): Promise<T> **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('getPositionObjectDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1807,6 +1912,8 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('albumGetFileAssetsDemoCallback') @@ -1849,6 +1956,8 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('albumGetFileAssetsDemoPromise') @@ -1889,6 +1998,8 @@ commitModify(callback: AsyncCallback<void>): void; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('albumCommitModifyDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1927,6 +2038,8 @@ commitModify(): Promise<void>; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('albumCommitModifyDemo') let predicates = new dataSharePredicates.DataSharePredicates(); @@ -1983,6 +2096,8 @@ getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult< **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumGetFileAssetsDemoCallback') let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2028,6 +2143,8 @@ getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>&g **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumGetFileAssetsDemoPromise') let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2062,6 +2179,8 @@ delete(uri: string, callback: AsyncCallback<void>): void; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumDeleteCallback'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2108,6 +2227,8 @@ delete(uri: string): Promise<void>; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumDeleteDemoPromise') let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2148,6 +2269,8 @@ recover(uri: string, callback: AsyncCallback<void>): void; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumRecoverDemoCallback'); let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2194,6 +2317,8 @@ recover(uri: string): Promise<void>; **示例**: ```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + async function example() { console.info('privateAlbumRecoverDemoPromise') let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); @@ -2342,7 +2467,7 @@ async function example() { | 名称 | 类型 | 必填 | 说明 | | ---------------------- | ------------------- | ---- |------------------------------------------------ | | fetchColumns | Array<string> | 是 | 检索条件,指定列名查询,如果该参数为空时默认查询uri、name、fileType。示例:
fetchColumns: "uri"| -| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | ## AlbumFetchOptions @@ -2352,5 +2477,5 @@ async function example() { | 名称 | 类型 | 必填 | 说明 | | ---------------------- | ------------------- | ---- |------------------------------------------------ | -| predicates | [dataSharePredicates.DataSharePredicates](#../js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | 是 | 谓词查询,显示过滤条件 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md b/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md index a22163a78c646bedab2ff1ec36df7797f7562b42..c0383e0497ec0e53e0e02da382adeac1405e8f9b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -70,13 +70,3 @@ setSurfaceId(surfaceId: string): void; console.error("set surface id failed, error = " + e); } ``` - -## ResultCode - - 表示执行结果的枚举。 - - **系统能力:** SystemCapability.UserIAM.UserAuth.FaceAuth - -| 名称 | 默认值 | 描述 | -| ----------------------- | ------ | -------------------- | -| FAIL | 12700001 | 执行失败。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md index 78824946b90c2e74190506e9273551d68e580145..5eb839a2e10eb986132ad007bb9afdffef298de0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -903,7 +903,6 @@ onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void | TYPE_NOT_SUPPORT | 5 | 不支持的认证类型。 | | TRUST_LEVEL_NOT_SUPPORT | 6 | 不支持的认证等级。 | | BUSY | 7 | 忙碌状态。 | -| INVALID_PARAMETERS | 8 | 无效参数。 | | LOCKED | 9 | 认证器已锁定。 | | NOT_ENROLLED | 10 | 用户未录入认证信息。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index f6da5fb4ba68285030323fca83358f37d28de624..5cd067c6b35ba8ad40797c1156e16c9f73cbbdf0 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -14,7 +14,38 @@ import util from '@ohos.util'; ``` -## util.printf +## util.format9+ + +format(format: string, ...args: Object[]): string + +通过式样化字符串对输入的内容按特定格式输出。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------- | ---- | -------------- | +| format | string | 是 | 式样化字符串。 | +| ...args | Object[] | 否 | 待式样化数据。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| string | 按特定格式式样化后的字符串。 | + +**示例:** + + ```js +let res = util.format("%s", "hello world!"); +console.log(res); + ``` + +## util.printf(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.format9+](#utilformat9)替代。 printf(format: string, ...args: Object[]): string @@ -27,7 +58,7 @@ printf(format: string, ...args: Object[]): string | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | format | string | 是 | 式样化字符串。 | -| ...args | Object[] | 否 | 待式样化数据。 | +| ...args | Object[] | 否 | 替换式样化字符串通配符的数据。 | **返回值:** @@ -41,8 +72,38 @@ printf(format: string, ...args: Object[]): string console.log(res); ``` +## util.errnoToString9+ + +errnoToString(errno: number): string + +获取系统错误码对应的详细信息。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------------------- | +| errno | number | 是 | 系统发生错误产生的错误码。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------- | +| string | 错误码对应的详细信息。 | + +**示例:** + + ```js +let errnum = 10; // 10 : a system error number +let result = util.errnoToString(errnum); +console.log("result = " + result); + ``` + +## util.getErrorString(deprecated) -## util.getErrorString +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.errnoToString9+](#utilerrnotostring9)替代。 getErrorString(errno: number): string @@ -69,7 +130,6 @@ getErrorString(errno: number): string console.log("result = " + result); ``` - ## util.callbackWrapper callbackWrapper(original: Function): (err: Object, value: Object )=>void @@ -103,30 +163,6 @@ callbackWrapper(original: Function): (err: Object, value: Object )=>void }, err) ``` - -## util.promiseWrapper(deprecated) - -promiseWrapper(original: (err: Object, value: Object) => void): Object - -> **说明:**
-> 从API Version 9开始废弃,建议使用[util.promisify9+](#utilpromisify9)替代。 - -对异步函数处理并返回一个promise的版本。 - -**系统能力:** SystemCapability.Utils.Lang - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| original | Function | 是 | 异步函数。 | - -**返回值:** - -| 类型 | 说明 | -| -------- | -------- | -| Function | 采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | - ## util.promisify9+ promisify(original: (err: Object, value: Object) => void): Function @@ -162,6 +198,29 @@ promisify(original: (err: Object, value: Object) => void): Function }) ``` +## util.promiseWrapper(deprecated) + +promiseWrapper(original: (err: Object, value: Object) => void): Object + +> **说明:**
+> 从API Version 9开始废弃,建议使用[util.promisify9+](#utilpromisify9)替代。 + +对异步函数处理并返回一个promise的版本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| original | Function | 是 | 异步函数。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Function | 采用遵循常见的错误优先的回调风格的函数(也就是将 (err, value) => ... 回调作为最后一个参数),并返回一个返回 promise 的版本。 | + ## util.randomUUID9+ randomUUID(entropyCache?: boolean): string @@ -244,7 +303,7 @@ parseUUID(uuid: string): Uint8Array console.log(JSON.stringify(uuid)); // 输出: // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 - ``` + ``` ## TextDecoder @@ -258,8 +317,45 @@ parseUUID(uuid: string): Uint8Array | fatal | boolean | 是 | 否 | 是否显示致命错误。 | | ignoreBOM | boolean | 是 | 否 | 是否忽略BOM(byte order marker)标记,默认值为false ,表示解码结果包含BOM标记。 | +### constructor9+ -### constructor +constructor() + +TextDecoder的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +### create9+ + +create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): TextDecoder; + +替代有参构造功能。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------ | +| encoding | string | 否 | 编码格式。 | +| options | Object | 否 | 编码相关选项参数,存在两个属性fatal和ignoreBOM。 | + + **表1.1**options + +| 名称 | 参数类型 | 必填 | 说明 | +| --------- | -------- | ---- | ------------------ | +| fatal | boolean | 否 | 是否显示致命错误。 | +| ignoreBOM | boolean | 否 | 是否忽略BOM标记。 | + +**示例:** + + ```js +let textDecoder = new util.TextDecoder() +textDecoder.create('utf-8', { ignoreBOM : true }); + ``` + +### constructor(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) @@ -286,7 +382,6 @@ TextDecoder的构造函数。 let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` - ### decode decode(input: Uint8Array, options?: { stream?: false }): string @@ -397,8 +492,39 @@ TextEncoder的构造函数。 let textEncoder = new util.TextEncoder(); ``` +### encodeInto9+ + +encodeInto(input?: string): Uint8Array + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| input | string | 是 | 需要编码的字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ------------------ | +| Uint8Array | 返回编码后的文本。 | + +**示例:** + + ```js +let textEncoder = new util.TextEncoder(); +let buffer = new ArrayBuffer(20); +let result = new Uint8Array(buffer); +result = textEncoder.encodeInto("\uD800¥¥"); + ``` + +### encode(deprecated) -### encode +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeInto9+](#encodeinto9)替代。 encode(input?: string): Uint8Array @@ -426,8 +552,41 @@ encode(input?: string): Uint8Array result = textEncoder.encode("\uD800¥¥"); ``` +### encodeIntoUint8Array9+ + +encodeIntoUint8Array(input: string, dest: Uint8Array, ): { read: number; written: number } + +放置生成的UTF-8编码文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------------------------------------------- | +| input | string | 是 | 需要编码的字符串。 | +| dest | Uint8Array | 是 | Uint8Array对象实例,用于将生成的UTF-8编码文本放入其中。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ------------------ | +| Uint8Array | 返回编码后的文本。 | + +**示例:** + + ```js +let that = new util.TextEncoder() +let buffer = new ArrayBuffer(4) +let dest = new Uint8Array(buffer) +let result = new Object() +result = that.encodeInto('abcd', dest) + ``` + +### encodeInto(deprecated) -### encodeInto +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeIntoUint8Array9+](#encodeintouint8array9)替代。 encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } @@ -459,8 +618,46 @@ encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } ## RationalNumber8+ +### constructor9+ -### constructor8+ +constructor() + +RationalNumber的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(); + ``` + +### parseRationalNumber9+ + +parseRationalNumber(numerator: number,denominator: number) + +替代原有参构造的参数处理。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------------- | +| numerator | number | 是 | 分子,整数类型。 | +| denominator | number | 是 | 分母,整数类型。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(); +rationalNumber.parseRationalNumber(1,2) + ``` + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(numerator: number,denominator: number) @@ -476,11 +673,11 @@ RationalNumber的构造函数。 | denominator | number | 是 | 分母,整数类型。 | **示例:** + ```js let rationalNumber = new util.RationalNumber(1,2); ``` - ### createRationalFromString8+ static createRationalFromString​(rationalString: string): RationalNumber​ @@ -507,8 +704,38 @@ static createRationalFromString​(rationalString: string): RationalNumber​ let rational = util.RationalNumber.createRationalFromString("3/4"); ``` +### compare9+ + +compare​(another: RationalNumber): number​ + +将当前的RationalNumber对象与给定的对象进行比较。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------- | ---- | ------------------ | +| another | RationalNumber | 是 | 其他的有理数对象。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------------------------------------ | +| number | 如果两个对象相等,则返回0;如果给定对象小于当前对象,则返回1;如果给定对象大于当前对象,则返回-1。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compare(rational); + ``` + +### compareTo8+(deprecated) -### compareTo8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[compare9+](#compare9)替代。 compareTo​(another: RationalNumber): number​ @@ -535,7 +762,6 @@ compareTo​(another: RationalNumber): number​ let result = rationalNumber.compareTo(rational); ``` - ### valueOf8+ valueOf(): number @@ -556,7 +782,6 @@ valueOf(): number let result = rationalNumber.valueOf(); ``` - ### equals8+ equals​(obj: Object): boolean @@ -584,8 +809,37 @@ equals​(obj: Object): boolean let result = rationalNumber.equals(rational); ``` +### getCommonFactor9+ + +getCommonFactor(number1: number,number2: number): number + +获取两个指定整数的最大公约数。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ---------- | +| number1 | number | 是 | 整数类型。 | +| number2 | number | 是 | 整数类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------ | +| number | 返回两个给定数字的最大公约数。 | + +**示例:** + + ```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonFactor(4,6); + ``` -### getCommonDivisor8+ +### getCommonDivisor8+(deprecated) +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCommonFactor9+](#getcommonfactor9)替代。 static getCommonDivisor​(number1: number,number2: number): number @@ -612,7 +866,6 @@ static getCommonDivisor​(number1: number,number2: number): number let result = util.RationalNumber.getCommonDivisor(4,6); ``` - ### getNumerator8+ getNumerator​(): number @@ -633,7 +886,6 @@ getNumerator​(): number let result = rationalNumber.getNumerator(); ``` - ### getDenominator8+ getDenominator​(): number @@ -654,7 +906,6 @@ getDenominator​(): number let result = rationalNumber.getDenominator(); ``` - ### isZero8+ isZero​():boolean @@ -675,7 +926,6 @@ isZero​():boolean let result = rationalNumber.isZero(); ``` - ### isNaN8+ isNaN​(): boolean @@ -696,7 +946,6 @@ isNaN​(): boolean let result = rationalNumber.isNaN(); ``` - ### isFinite8+ isFinite​():boolean @@ -717,7 +966,6 @@ isFinite​():boolean let result = rationalNumber.isFinite(); ``` - ### toString8+ toString​(): string @@ -738,26 +986,27 @@ toString​(): string let result = rationalNumber.toString(); ``` -## LruBuffer8+ + +## LRUCache9+ ### 属性 **系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 -| 名称 | 类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| length | number | 是 | 否 | 当前缓冲区中值的总数。 | +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------ | ------ | ---- | ---- | ---------------------- | +| length | number | 是 | 否 | 当前缓冲区中值的总数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(1,8); - let result = pro.length; +let pro = new util.LRUCache(); +pro.put(2,10); +pro.put(1,8); +let result = pro.length; ``` - -### constructor8+ +### constructor9+ constructor(capacity?: number) @@ -767,17 +1016,18 @@ constructor(capacity?: number) **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ---------------------------- | +| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | **示例:** + ```js - let lrubuffer= new util.LruBuffer(); +let lrubuffer= new util.LRUCache(); ``` -### updateCapacity8+ +### updateCapacity9+ updateCapacity(newCapacity: number): void @@ -787,18 +1037,19 @@ updateCapacity(newCapacity: number): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ---------------------------- | +| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.updateCapacity(100); +let pro = new util.LRUCache(); +let result = pro.updateCapacity(100); ``` -### toString8+ +### toString9+ toString(): string @@ -808,21 +1059,22 @@ toString(): string **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | string | 返回对象的字符串表示形式。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - pro.remove(20); - let result = pro.toString(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +pro.remove(20); +let result = pro.toString(); ``` -### getCapacity8+ +### getCapacity9+ getCapacity(): number @@ -832,18 +1084,19 @@ getCapacity(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ---------------------- | | number | 返回当前缓冲区的容量。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.getCapacity(); +let pro = new util.LRUCache(); +let result = pro.getCapacity(); ``` -### clear8+ +### clear9+ clear(): void @@ -852,15 +1105,16 @@ clear(): void **系统能力:** SystemCapability.Utils.Lang **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.length; - pro.clear(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.length; +pro.clear(); ``` -### getCreateCount8+ +### getCreateCount9+ getCreateCount(): number @@ -870,19 +1124,20 @@ getCreateCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | --------------------------------- | | number | 返回createDefault()返回值的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(1,8); - let result = pro.getCreateCount(); +let pro = new util.LRUCache(); +pro.put(1,8); +let result = pro.getCreateCount(); ``` -### getMissCount8+ +### getMissCount9+ getMissCount(): number @@ -892,20 +1147,21 @@ getMissCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ------------------------ | | number | 返回查询值不匹配的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMissCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +let result = pro.getMissCount(); ``` -### getRemovalCount8+ +### getRemovalCount9+ getRemovalCount(): number @@ -915,21 +1171,22 @@ getRemovalCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | number | 返回从缓冲区中驱逐的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.updateCapacity(2); - pro.put(50,22); - let result = pro.getRemovalCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.updateCapacity(2); +pro.put(50,22); +let result = pro.getRemovalCount(); ``` -### getMatchCount8+ +### getMatchCount9+ getMatchCount(): number @@ -939,20 +1196,21 @@ getMatchCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | -------------------------- | | number | 返回查询值匹配成功的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMatchCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.get(2); +let result = pro.getMatchCount(); ``` -### getPutCount8+ +### getPutCount9+ getPutCount(): number @@ -962,19 +1220,20 @@ getPutCount(): number **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------ | ---------------------------- | | number | 返回将值添加到缓冲区的次数。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.getPutCount(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.getPutCount(); ``` -### isEmpty8+ +### isEmpty9+ isEmpty(): boolean @@ -984,19 +1243,20 @@ isEmpty(): boolean **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------- | ---------------------------------------- | | boolean | 如果当前缓冲区不包含任何值,则返回true。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.isEmpty(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.isEmpty(); ``` -### get8+ +### get9+ get(key: K): V | undefined @@ -1006,25 +1266,26 @@ get(key: K): V | undefined **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要查询的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ------------ | +| key | K | 是 | 要查询的键。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | | V \| undefined | 如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.get(2); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.get(2); ``` -### put8+ +### put9+ put(key: K,value: V): V @@ -1034,24 +1295,25 @@ put(key: K,value: V): V **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要添加的密钥。 | -| value | V | 是 | 指示与要添加的键关联的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------------------- | +| key | K | 是 | 要添加的密钥。 | +| value | V | 是 | 指示与要添加的键关联的值。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | +| 类型 | 说明 | +| ---- | ------------------------------------------------------------ | +| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.put(2,10); +let pro = new util.LRUCache(); +let result = pro.put(2,10); ``` -### values8+ +### values9+ values(): V[] @@ -1061,21 +1323,22 @@ values(): V[] **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------- | ------------------------------------------------------------ | | V [] | 按从最近访问到最近最少访问的顺序返回当前缓冲区中所有值的列表。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(2,"anhu"); - pro.put("afaf","grfb"); - let result = pro.values(); +let pro = new util.LRUCache(); +pro.put(2,10); +pro.put(2,"anhu"); +pro.put("afaf","grfb"); +let result = pro.values(); ``` -### keys8+ +### keys9+ keys(): K[] @@ -1085,19 +1348,20 @@ keys(): K[] **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| --------- | ------------------------------------------------------------ | | K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.keys(); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.keys(); ``` -### remove8+ +### remove9+ remove(key: K): V | undefined @@ -1107,25 +1371,26 @@ remove(key: K): V | undefined **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 要删除的密钥。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| key | K | 是 | 要删除的密钥。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | | V \| undefined | 返回一个包含已删除键值对的Optional对象;如果key不存在,则返回一个空的Optional对象,如果key为null,则抛出异常。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.remove(20); +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.remove(20); ``` -### afterRemoval8+ +### afterRemoval9+ afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void @@ -1135,36 +1400,37 @@ afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | -| key | K | 是 | 表示删除的键。 | -| value | V | 是 | 表示删除的值。 | -| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ------------------------------------------------------------ | +| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | +| key | K | 是 | 表示删除的键。 | +| value | V | 是 | 表示删除的值。 | +| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | **示例:** + ```js - let arr = []; - class ChildLruBuffer extends util.LruBuffer - { - constructor() - { - super(); - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } - } - let lru = new ChildLruBuffer(); - lru.afterRemoval(false,10,30,null); +let arr = []; +class ChildLruBuffer extends util.LRUCache +{ + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } +} +let lru = new ChildLruBuffer(); +lru.afterRemoval(false,10,30,null); ``` -### contains8+ +### contains9+ contains(key: K): boolean @@ -1174,136 +1440,1067 @@ contains(key: K): boolean **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 表示要检查的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | ---------------- | +| key | K | 是 | 表示要检查的键。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------ | +| boolean | 如果缓冲区包含指定的键,则返回 true。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.contains(20); + ``` + + +### createDefault9+ + +createDefault(key: K): V + +如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---- | ---- | -------------- | +| key | K | 是 | 表示丢失的键。 | + +**返回值:** + +| 类型 | 说明 | +| ---- | ------------------ | +| V | 返回与键关联的值。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +let result = pro.createDefault(50); + ``` + + +### entries9+ + +entries(): IterableIterator<[K,V]> + +允许迭代包含在这个对象中的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ----------- | -------------------- | +| [K, V] | 返回一个可迭代数组。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro.entries(); + ``` + +### [Symbol.iterator]9+ + +[Symbol.iterator]\(): IterableIterator<[K, V]> + +返回一个键值对形式的二维数组。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------------------------ | +| [K, V] | 返回一个键值对形式的二维数组。 | + +**示例:** + + ```js +let pro = new util.LRUCache(); +pro.put(2,10); +let result = pro[Symbol.iterator](); + ``` + +## LruBuffer8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[LRUCache9+](#lrucache9)替代。 + +### 属性 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | 当前缓冲区中值的总数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(1,8); + let result = pro.length; + ``` + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 + +constructor(capacity?: number) + +默认构造函数用于创建一个新的LruBuffer实例,默认容量为64。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| capacity | number | 否 | 指示要为缓冲区自定义的容量。 | + +**示例:** + ```js + let lrubuffer= new util.LruBuffer(); + ``` + +### updateCapacity8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[updateCapacity9+](#updatecapacity9)替代。 + +updateCapacity(newCapacity: number): void + +将缓冲区容量更新为指定容量,如果newCapacity小于或等于0,则抛出异常。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| newCapacity | number | 是 | 指示要为缓冲区自定义的容量。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); + ``` + +### toString8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[toString9+](#tostring9)替代。 + +toString(): string + +返回对象的字符串表示形式。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| string | 返回对象的字符串表示形式。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + pro.remove(20); + let result = pro.toString(); + ``` + +### getCapacity8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCapacity9+](#getcapacity9)替代。 + +getCapacity(): number + +获取当前缓冲区的容量。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回当前缓冲区的容量。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); + ``` + +### clear8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[clear9+](#clear9)替代。 + +clear(): void + +从当前缓冲区清除键值对。后续会调用afterRemoval()方法执行后续操作。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.length; + pro.clear(); + ``` + +### getCreateCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getCreateCount9+](#getcreatecount9)替代。 + +getCreateCount(): number + +获取createDefault()返回值的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回createDefault()返回值的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(1,8); + let result = pro.getCreateCount(); + ``` + +### getMissCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getMissCount9+](#getmisscount9)替代。 + +getMissCount(): number + +获取查询值不匹配的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回查询值不匹配的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMissCount(); + ``` + +### getRemovalCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getRemovalCount9+](#getremovalcount9)替代。 + +getRemovalCount(): number + +获取从缓冲区中逐出值的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回从缓冲区中驱逐的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.updateCapacity(2); + pro.put(50,22); + let result = pro.getRemovalCount(); + ``` + +### getMatchCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getMatchCount9+](#getmatchcount9)替代。 + +getMatchCount(): number + +获取查询值匹配成功的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回查询值匹配成功的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMatchCount(); + ``` + +### getPutCount8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[getPutCount9+](#getputcount9)替代。 + +getPutCount(): number + +获取将值添加到缓冲区的次数。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 返回将值添加到缓冲区的次数。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.getPutCount(); + ``` + +### isEmpty8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[isEmpty9+](#isempty9)替代。 + +isEmpty(): boolean + +检查当前缓冲区是否为空。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 如果当前缓冲区不包含任何值,则返回true。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.isEmpty(); + ``` + +### get8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[get9+](#get9)替代。 + +get(key: K): V | undefined + +表示要查询的键。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要查询的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V \| undefined | 如果指定的键存在于缓冲区中,则返回与键关联的值;否则返回undefined。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.get(2); + ``` + +### put8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[put9+](#put9)替代。 + +put(key: K,value: V): V + +将键值对添加到缓冲区。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要添加的密钥。 | +| value | V | 是 | 指示与要添加的键关联的值。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V | 返回与添加的键关联的值;如果要添加的键已经存在,则返回原始值,如果键或值为空,则抛出此异常。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.put(2,10); + ``` + +### values8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[values9+](#values9)替代。 + +values(): V[] + +获取当前缓冲区中所有值从最近访问到最近最少访问的顺序列表 。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V [] | 按从最近访问到最近最少访问的顺序返回当前缓冲区中所有值的列表。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(2,"anhu"); + pro.put("afaf","grfb"); + let result = pro.values(); + ``` + +### keys8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[keys9+](#keys9)替代。 + +keys(): K[] + +获取当前缓冲区中所有键从最近访问到最近最少访问的升序列表。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| K [] | 按升序返回当前缓冲区中所有键的列表,从最近访问到最近最少访问。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.keys(); + ``` + +### remove8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[remove9+](#remove9)替代。 + +remove(key: K): V | undefined + +从当前缓冲区中删除指定的键及其关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 要删除的密钥。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V \| undefined | 返回一个包含已删除键值对的Optional对象;如果key不存在,则返回一个空的Optional对象,如果key为null,则抛出异常。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.remove(20); + ``` + +### afterRemoval8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[afterRemoval9+](#afterremoval9)替代。 + +afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void + +删除值后执行后续操作。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| isEvict | boolean | 否 | 因容量不足而调用该方法时,参数值为true,其他情况为false。 | +| key | K | 是 | 表示删除的键。 | +| value | V | 是 | 表示删除的值。 | +| newValue | V | 否 | 如果已调用put方法并且要添加的键已经存在,则参数值是关联的新值。其他情况下参数值为空。 | + +**示例:** + ```js + let arr = []; + class ChildLruBuffer extends util.LruBuffer + { + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } + } + let lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); + ``` + +### contains8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 + +contains(key: K): boolean + +检查当前缓冲区是否包含指定的键。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 表示要检查的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 如果缓冲区包含指定的键,则返回 true。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.contains(20); + ``` + +### createDefault8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[createDefault9+](#createdefault9)替代。 + +createDefault(key: K): V + +如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| key | K | 是 | 表示丢失的键。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| V | 返回与键关联的值。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); + ``` + +### entries8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[entries9+](#entries9)替代。 + +entries(): IterableIterator<[K,V]> + +允许迭代包含在这个对象中的所有键值对。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| [K, V] | 返回一个可迭代数组。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.entries(); + ``` + +### [Symbol.iterator]8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[Symbol.iterator9+](#symboliterator9)替代。 + +[Symbol.iterator]\(): IterableIterator<[K, V]> + +返回一个键值对形式的二维数组。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| [K, V] | 返回一个键值对形式的二维数组。 | + +**示例:** + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro[Symbol.iterator](); + ``` + +### ScopeType8+ + +用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 + +ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 +```js +interface ScopeComparable{ + compareTo(other: ScopeComparable): boolean; +} +type ScopeType = ScopeComparable | number; +``` + + +构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 + + +示例: +```js +class Temperature{ + constructor(value){ + // 当使用ts语言开发时,需要补充以下代码: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` + +## ScopeHelper9+ + +### constructor9+ + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +用于创建指定下限和上限的作用域实例的构造函数,返回一个ScopeHelper对象。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 指定作用域实例的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 指定作用域实例的上限。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); + ``` + + +### toString9+ + +toString(): string + +该字符串化方法返回一个包含当前范围的字符串表示形式。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------------------- | +| string | 返回包含当前范围对象的字符串表示形式。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.toString(); + ``` + + +### intersect9+ + +intersect(range: ScopeHelper): ScopeHelper + +获取给定范围和当前范围的交集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ------------------------------ | +| [ScopeHelper9+](#scopehelper9) | 返回给定范围和当前范围的交集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +range.intersect(rangeFir ); + ``` + + +### intersect9+ + +intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper + +获取当前范围与给定下限和上限范围的交集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 给定范围的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 给定范围的上限。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ---------------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回当前范围与给定下限和上限范围的交集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.intersect(tempMiDF, tempMidS); + ``` + + +### getUpper9+ + +getUpper(): ScopeType + +获取当前范围的上限。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | 返回当前范围的上限值。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getUpper(); + ``` + + +### getLower9+ + +getLower(): ScopeType + +获取当前范围的下限。 + +**系统能力:** SystemCapability.Utils.Lang + +**返回值:** + +| 类型 | 说明 | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | 返回当前范围的下限值。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getLower(); + ``` + + +### expand9+ + +expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper + +创建并返回包括当前范围和给定下限和上限的并集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | 是 | 给定范围的下限。 | +| upperObj | [ScopeType](#scopetype8) | 是 | 给定范围的上限。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | ------------------------------------ | +| [ScopeHelper9+](#scopehelper9) | 返回当前范围和给定下限和上限的并集。 | + +**示例:** + + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF, tempMidS); + ``` + + +### expand9+ + +expand(range: ScopeHelper): ScopeHelper + +创建并返回包括当前范围和给定范围的并集。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| boolean | 如果缓冲区包含指定的键,则返回 true。 | +| 类型 | 说明 | +| ------------------------------ | ---------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回包括当前范围和给定范围的并集。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.contains(20); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +let result = range.expand(rangeFir); ``` -### createDefault8+ +### expand9+ -createDefault(key: K): V +expand(value: ScopeType): ScopeHelper -如果未计算特定键的值,则执行后续操作,参数表示丢失的键,返回与键关联的值。 +创建并返回包括当前范围和给定值的并集。 **系统能力:** SystemCapability.Utils.Lang **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| key | K | 是 | 表示丢失的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入一个给定值。 | **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| V | 返回与键关联的值。 | +| 类型 | 说明 | +| ------------------------------ | -------------------------------- | +| [ScopeHelper9+](#scopehelper9) | 返回包括当前范围和给定值的并集。 | **示例:** + ```js - let pro = new util.LruBuffer(); - let result = pro.createDefault(50); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF); ``` -### entries8+ +### contains9+ -entries(): IterableIterator<[K,V]> +contains(value: ScopeType): boolean -允许迭代包含在这个对象中的所有键值对。 +检查给定value是否包含在当前范围内。 **系统能力:** SystemCapability.Utils.Lang +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入一个给定值。 | + **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| [K, V] | 返回一个可迭代数组。 | +| 类型 | 说明 | +| ------- | --------------------------------------------------- | +| boolean | 如果给定值包含在当前范围内返回true,否则返回false。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.entries(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +range.contains(tempMiDF); ``` -### [Symbol.iterator]8+ +### contains9+ -[Symbol.iterator]\(): IterableIterator<[K, V]> +contains(range: ScopeHelper): boolean -返回一个键值对形式的二维数组。 +检查给定range是否在当前范围内。 **系统能力:** SystemCapability.Utils.Lang +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ------------------ | +| range | [ScopeHelper9+](#scopehelper9) | 是 | 传入一个给定范围。 | + **返回值:** -| 类型 | 说明 | -| -------- | -------- | -| [K, V] | 返回一个键值对形式的二维数组。 | +| 类型 | 说明 | +| ------- | ----------------------------------------------------- | +| boolean | 如果给定范围包含在当前范围内返回true,否则返回false。 | **示例:** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro[Symbol.iterator](); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempLess = new Temperature(20); +let tempMore = new Temperature(45); +let rangeSec = new util.ScopeHelper(tempLess, tempMore); +let result = range.contains(rangeSec); ``` -## Scope8+ +### clamp9+ +clamp(value: ScopeType): ScopeType -### ScopeType8+ +将给定值限定到当前范围内。 -用于表示范围中的值的类型。该类型的值,类型可以为ScopeComparable或number。 +**系统能力:** SystemCapability.Utils.Lang -ScopeComparable类型的值需要实现compareTo方法,确保传入的数据具有可比性。 -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` +**参数:** +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------ | ---- | -------------- | +| value | [ScopeType](#scopetype8) | 是 | 传入的给定值。 | -构造新类,实现compareTo方法。后续示例代码中,均通过Temperature,获取[ScopeType](#scopetype8)的实例化对象。 +**返回值:** +| 类型 | 说明 | +| ------------------------ | ------------------------------------------------------------ | +| [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | -示例: -```js -class Temperature{ - constructor(value){ - // 当使用ts语言开发时,需要补充以下代码: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` +**示例:** + ```js +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.clamp(tempMiDF); + ``` -### constructor8+ +## Scope8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[ScopeHelper9+](#scopehelper9)替代。 + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor(lowerObj: ScopeType, upperObj: ScopeType) @@ -1325,8 +2522,10 @@ constructor(lowerObj: ScopeType, upperObj: ScopeType) let range = new util.Scope(tempLower, tempUpper); ``` +### toString8+(deprecated) -### toString8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[toString9+](#tostring9)替代。 toString(): string @@ -1348,8 +2547,10 @@ toString(): string let result = range.toString(); ``` +### intersect8+(deprecated) -### intersect8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 intersect(range: Scope): Scope @@ -1370,6 +2571,7 @@ intersect(range: Scope): Scope | [Scope](#scope8) | 返回给定范围和当前范围的交集。 | **示例:** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -1380,8 +2582,10 @@ intersect(range: Scope): Scope range.intersect(rangeFir ); ``` +### intersect8+(deprecated) -### intersect8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[intersect9+](#intersect9)替代。 intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope @@ -1412,8 +2616,10 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope let result = range.intersect(tempMiDF, tempMidS); ``` +### getUpper8+(deprecated) -### getUpper8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[getUpper9+](#getupper9)替代。 getUpper(): ScopeType @@ -1435,8 +2641,10 @@ getUpper(): ScopeType let result = range.getUpper(); ``` +### getLower8+(deprecated) -### getLower8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[getLower9+](#getlower9)替代。 getLower(): ScopeType @@ -1458,8 +2666,10 @@ getLower(): ScopeType let result = range.getLower(); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(lowerObj: ScopeType,upperObj: ScopeType): Scope @@ -1491,8 +2701,10 @@ expand(lowerObj: ScopeType,upperObj: ScopeType): Scope let result = range.expand(tempMiDF, tempMidS); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(range: Scope): Scope @@ -1523,8 +2735,10 @@ expand(range: Scope): Scope let result = range.expand(rangeFir); ``` +### expand8+(deprecated) -### expand8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[expand9+](#expand9)替代。 expand(value: ScopeType): Scope @@ -1553,8 +2767,10 @@ expand(value: ScopeType): Scope let result = range.expand(tempMiDF); ``` +### contains8+(deprecated) -### contains8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 contains(value: ScopeType): boolean @@ -1583,8 +2799,10 @@ contains(value: ScopeType): boolean range.contains(tempMiDF); ``` +### contains8+(deprecated) -### contains8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[contains9+](#contains9)替代。 contains(range: Scope): boolean @@ -1605,6 +2823,7 @@ contains(range: Scope): boolean | boolean | 如果给定范围包含在当前范围内返回true,否则返回false。 | **示例:** + ```js let tempLower = new Temperature(30); let tempUpper = new Temperature(40); @@ -1615,8 +2834,10 @@ contains(range: Scope): boolean let result = range.contains(rangeSec); ``` +### clamp8+(deprecated) -### clamp8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[clamp9+](#clamp9)替代。 clamp(value: ScopeType): ScopeType @@ -1645,11 +2866,217 @@ clamp(value: ScopeType): ScopeType let result = range.clamp(tempMiDF); ``` +## Base64Helper9+ -## Base648+ +### constructor9+ +constructor() -### constructor8+ +Base64Helper的构造函数。 + +**系统能力:** SystemCapability.Utils.Lang + +**示例:** + + ```js +let base64 = new util.Base64Helper(); + ``` + +### encodeSync9+ + +encodeSync(src: Uint8Array): Uint8Array + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | 是 | 编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ----------------------------- | +| Uint8Array | 返回编码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeSync(array); + ``` + + +### encodeToStringSync9+ + +encodeToStringSync(src: Uint8Array): string + +通过输入参数编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | 是 | 编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------- | +| string | 返回编码后的字符串。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeToStringSync(array); + ``` + + +### decodeSync9+ + +decodeSync(src: Uint8Array | string): Uint8Array + +通过输入参数解码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ----------------------------- | +| src | Uint8Array \| string | 是 | 解码输入Uint8数组或者字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | ----------------------------- | +| Uint8Array | 返回解码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let buff = 'czEz'; +let result = that.decodeSync(buff); + ``` + + +### encode9+ + +encode(src: Uint8Array): Promise<Uint8Array> + +通过输入参数异步编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | 是 | 异步编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | 返回异步编码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let rarray = new Uint8Array([99,122,69,122]); +that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) + ``` + + +### encodeToString9+ + +encodeToString(src: Uint8Array): Promise<string> + +通过输入参数异步编码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | 是 | 异步编码输入Uint8数组。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------ | +| Promise<string> | 返回异步编码后的字符串。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +that.encodeToString(array).then(val=>{ + console.log(val) +}) + ``` + + +### decode9+ + +decode(src: Uint8Array | string): Promise<Uint8Array> + +通过输入参数异步解码后输出对应文本。 + +**系统能力:** SystemCapability.Utils.Lang + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | --------------------------------- | +| src | Uint8Array \| string | 是 | 异步解码输入Uint8数组或者字符串。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | 返回异步解码后新分配的Uint8数组。 | + +**示例:** + + ```js +let that = new util.Base64Helper(); +let array = new Uint8Array([99,122,69,122]); +let rarray = new Uint8Array([115,49,51]); +that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) + ``` + + +## Base648+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[Base64Helper9+](#base64helper9)替代。 + +### constructor8+(deprecated) + +> **说明:**
+> 从API Version 9开始废弃,建议使用[constructor9+](#constructor9)替代。 constructor() @@ -1662,8 +3089,10 @@ Base64的构造函数。 let base64 = new util.Base64(); ``` +### encodeSync8+(deprecated) -### encodeSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeSync9+](#encodesync9)替代。 encodeSync(src: Uint8Array): Uint8Array @@ -1684,14 +3113,17 @@ encodeSync(src: Uint8Array): Uint8Array | Uint8Array | 返回编码后新分配的Uint8数组。 | **示例:** + ```js let that = new util.Base64(); let array = new Uint8Array([115,49,51]); let result = that.encodeSync(array); ``` +### encodeToStringSync8+(deprecated) -### encodeToStringSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeToStringSync9+](#encodetostringsync9)替代。 encodeToStringSync(src: Uint8Array): string @@ -1718,8 +3150,10 @@ encodeToStringSync(src: Uint8Array): string let result = that.encodeToStringSync(array); ``` +### decodeSync8+(deprecated) -### decodeSync8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[decodeSync9+](#decodesync9)替代。 decodeSync(src: Uint8Array | string): Uint8Array @@ -1746,8 +3180,10 @@ decodeSync(src: Uint8Array | string): Uint8Array let result = that.decodeSync(buff); ``` +### encode8+(deprecated) -### encode8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encode9+](#encode9)替代。 encode(src: Uint8Array): Promise<Uint8Array> @@ -1779,8 +3215,10 @@ encode(src: Uint8Array): Promise<Uint8Array> }) ``` +### encodeToString8+(deprecated) -### encodeToString8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[encodeToString9+](#encodetostring9)替代。 encodeToString(src: Uint8Array): Promise<string> @@ -1809,8 +3247,10 @@ encodeToString(src: Uint8Array): Promise<string> }) ``` +### decode8+(deprecated) -### decode8+ +> **说明:**
+> 从API Version 9开始废弃,建议使用[decode9+](#decode9)替代。 decode(src: Uint8Array | string): Promise<Uint8Array> @@ -1842,7 +3282,6 @@ decode(src: Uint8Array | string): Promise<Uint8Array> }) ``` - ## types8+ @@ -2926,4 +4365,5 @@ isSharedArrayBuffer(value: Object): boolean ```js let that = new util.types(); let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); - ``` \ No newline at end of file + ``` + \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md index 921c82b5ebd90b46ab78b469c1ad0326026bf651..164f69a071584ae837c07a4ee960e0a553bbd3c7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -72,7 +72,7 @@ let vector = new Vector(); let result = vector.add("a"); let result1 = vector.add(1); let b = [1, 2, 3]; -vector.add(b); +let result2 = vector.add(b); let c = {name : "Dylon", age : "13"}; let result3 = vector.add(c); ``` @@ -285,8 +285,6 @@ vector.add(4); vector.add(5); vector.add(4); vector.removeByRange(2,4); -vector.removeByRange(4,3); -vector.removeByRange(2,6); ``` ### replaceAllElements @@ -430,9 +428,10 @@ vector.add(2); vector.add(4); vector.add(5); vector.add(4); -let result = vector.subVector(2,4); -let result1 = vector.subVector(4,3); -let result2 = vector.subVector(2,6); +vector.add(6); +vector.add(8); +let result = vector.subVector(0,4); +let result1 = vector.subVector(2,4); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index 5f4b865d34a2b425b4764373d9ba8b00002fd874..1daff5659e271364deb8a39ba7d67af97b997ba0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md @@ -1,6 +1,6 @@ # 振动 -vibrator模块提供控制马达振动的能力,如通过接口控制马达启动马达振动,停止马达振动等。 +vibrator模块提供控制马达振动启、停的能力。 > **说明:** > @@ -17,7 +17,7 @@ import vibrator from '@ohos.vibrator'; startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void -按照指定振动效果和振动属性触发马达振动。 +根据指定振动效果和振动属性触发马达振动。 **需要权限**:ohos.permission.VIBRATE @@ -29,7 +29,7 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: Asy | --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | | effect | [VibrateEffect](#vibrateeffect9) | 是 | 马达振动效果。 | | attribute | [VibrateAttribute](#vibrateattribute9) | 是 | 马达振动属性。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当马达振动成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,当马达振动成功,err为undefined,否则为错误对象。 | **错误码**: @@ -44,20 +44,20 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: Asy ```js try { vibrator.startVibration({ - type:'time', - duration:1000, - },{ - id:0, + type: 'time', + duration: 1000, + }, { + id: 0, usage: 'alarm' - }, (error)=>{ - if(error){ - console.log('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - }else{ - console.log('Callback returned to indicate a successful vibration.'); + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; } + console.log('Callback returned to indicate a successful vibration.'); }); -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -65,7 +65,7 @@ try { startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> -按照指定振动效果和振动属性触发马达振动。 +根据指定振动效果和振动属性触发马达振动。 **需要权限**:ohos.permission.VIBRATE @@ -82,7 +82,7 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<v | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **错误码**: @@ -97,18 +97,18 @@ startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<v ```js try { vibrator.startVibration({ - type: 'time', - duration: 1000 + type: 'time', + duration: 1000 }, { id: 0, usage: 'alarm' - }).then(()=>{ + }).then(() => { console.log('Promise returned to indicate a successful vibration'); - }).catch((error)=>{ - console.log('error.code' + error.code + 'error.message' + error.message); - }) -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + }, (error) => { + console.error('error.code' + error.code + 'error.message' + error.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -116,7 +116,7 @@ try { stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void -按照要停止指定的振动模式来停止马达的振动。如果要停止的振动模式与触发马达振动时的模式不相同,则调用本接口会失败。 +按照指定模式停止马达的振动。 **需要权限**:ohos.permission.VIBRATE @@ -126,22 +126,42 @@ stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| stopMode | [VibratorStopMode](#vibratorstopmode) | 是 | 马达停止指定的振动模式。 | +| stopMode | [VibratorStopMode](#vibratorstopmode) | 是 | 指定的停止振动模式。 | | callback | AsyncCallback<void> | 是 | 回调函数。当马达停止振动成功,err为undefined,否则为错误对象。 | **示例:** ```js try { - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; + } + console.log('Callback returned to indicate a successful vibration.'); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); +} + +try { + // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ - console.log('Callback returned to indicate successful.'); + return; } + console.log('Callback returned to indicate successful.'); }) -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -149,7 +169,7 @@ try { stopVibration(stopMode: VibratorStopMode): Promise<void> -按照要停止指定的振动模式来停止马达的振动。如果要停止的振动模式与触发马达振动时的模式不相同,则调用本接口会失败。 +按照指定模式停止马达的振动。 **需要权限**:ohos.permission.VIBRATE @@ -165,43 +185,61 @@ stopVibration(stopMode: VibratorStopMode): Promise<void> | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **示例:** ```js try { - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ - console.log('Promise returned to indicate a successful vibration.'); - }, (error)=>{ + // 按照固定时长振动 + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.log('Promise returned to indicate a successful vibration'); + }, (error) => { + console.error('error.code' + error.code + 'error.message' + error.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); +} + +try { + // 按照VIBRATOR_STOP_MODE_TIME模式停止振动 + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { + console.log('Promise returned to indicate a successful vibration.'); + }, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` ## EffectId -马达振动效果的字符串。 +预置的振动效果。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.MiscDevice -| 名称 | 默认值 | 说明 | -| ------------------ | -------------------- | ------------------ | -| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | 预置的振动效果ID。 | +| 名称 | 值 | 说明 | +| ------------------ | -------------------- | -------------------------------- | +| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | 描述用户调整计时器时的振动效果。 | ## VibratorStopMode -马达要停止指定的振动模式。 +停止的振动模式。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.MiscDevice -| 名称 | 默认值 | 说明 | -| ------------------------- | -------- | ------------------------------------------------------------ | -| VIBRATOR_STOP_MODE_TIME | "time" | 停止模式为duration模式的振动。即触发振动时参数类型为number,参数本身为振动持续时间的触发方式。 | -| VIBRATOR_STOP_MODE_PRESET | "preset" | 停止模式为预置EffectId的振动。即触发振动时参数类型为EffectId,参数本身为马达振动效果的字符串的触发方式。 | +| 名称 | 值 | 说明 | +| ------------------------- | -------- | ------------------------------ | +| VIBRATOR_STOP_MODE_TIME | "time" | 停止模式为duration模式的振动。 | +| VIBRATOR_STOP_MODE_PRESET | "preset" | 停止模式为预置EffectId的振动。 | ## VibrateEffect9+ @@ -220,10 +258,10 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.MiscDevice -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | -------- | ------ | ------------------------------ | | type | "time" | 按照指定持续时间触发马达振动。 | -| duration | - | 马达振动时长, 单位ms。 | +| duration | - | 马达持续振动时长, 单位ms。 | ## VibratePreset9+ @@ -231,7 +269,7 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.MiscDevice -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | -------- | -------- | ------------------------------ | | type | "preset" | 按照预置振动效果触发马达振动。 | | effectId | - | 预置的振动效果ID。 | @@ -243,10 +281,10 @@ try { **系统能力**:以下各项对应的系统能力均为SystemCapability.Sensors.MiscDevice -| 名称 | 默认值 | 说明 | +| 名称 | 值 | 说明 | | ----- | ------ | -------------- | | id | 0 | 振动器id。 | -| usage | - | 马达振动场景。 | +| usage | - | 马达振动的使用场景。 | ## Usage9+ @@ -257,14 +295,14 @@ try { | 名称 | 类型 | 说明 | | ---------------- | ------ | ------------------------------ | | unknown | string | 没有明确使用场景,最低优先级。 | -| alarm | string | 用于警报振动的场景。 | -| ring | string | 用于铃声振动的场景。 | -| notification | string | 用于通知振动的场景。 | -| communication | string | 用于通信振动的场景。 | -| touch | string | 用于触摸振动的场景。 | -| media | string | 用于多媒体振动的场景。 | -| physicalFeedback | string | 用于物理反馈振动的场景。 | -| simulateReality | string | 用于模拟现实振动的场景。 | +| alarm | string | 用于警报场景。 | +| ring | string | 用于铃声场景。 | +| notification | string | 用于通知场景。 | +| communication | string | 用于通信场景。 | +| touch | string | 用于触摸场景。 | +| media | string | 用于多媒体场景。 | +| physicalFeedback | string | 用于物理反馈场景。 | +| simulateReality | string | 用于模拟现实场景。 | ## vibrator.vibrate(deprecated) @@ -288,14 +326,14 @@ vibrate(duration: number): Promise<void> | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **示例:** ```js -vibrator.vibrate(1000).then(()=>{ +vibrator.vibrate(1000).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -322,10 +360,10 @@ vibrate(duration: number, callback?: AsyncCallback<void>): void **示例:** ```js -vibrator.vibrate(1000,function(error){ - if(error){ +vibrator.vibrate(1000, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate a successful vibration.'); } }) @@ -354,14 +392,14 @@ vibrate(effectId: EffectId): Promise<void> | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **示例:** ```js -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -389,10 +427,10 @@ vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void **示例:** ```js -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ - if(error){ +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate a successful vibration.'); } }) @@ -402,7 +440,7 @@ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ stop(stopMode: VibratorStopMode): Promise<void> -按照要停止指定的振动模式来停止马达的振动。如果要停止的振动模式与触发马达振动时的模式不相同,则调用本接口会失败。 +按照指定模式停止马达的振动。 从API version 9 开始不再维护,建议使用 [vibrator.stopVibration](#vibratorstopvibration9-1) 代替。 @@ -420,14 +458,23 @@ stop(stopMode: VibratorStopMode): Promise<void> | 类型 | 说明 | | ------------------- | -------------------------------------- | -| Promise<void> | Promise对象。无返回结果的Promise对象。 | +| Promise<void> | Promise对象。 | **示例:** ```js -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ +// 按照effectId类型启动振动 +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + } else { + console.log('Callback returned to indicate a successful vibration.'); + } +}) +// 使用VIBRATOR_STOP_MODE_PRESET模式停止振动 +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -437,7 +484,7 @@ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void -按照要停止指定的振动模式来停止马达的振动。如果要停止的振动模式与触发马达振动时的模式不相同,则调用本接口会失败。 +按照指定模式停止马达的振动。 从API version 9 开始不再维护,建议使用 [vibrator.stopVibration](#vibratorstopvibration9) 代替。 @@ -455,10 +502,19 @@ stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void **示例:** ```js -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ +// 按照effectId类型启动振动 +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + } else { + console.log('Callback returned to indicate a successful vibration.'); + } +}) +// 使用VIBRATOR_STOP_MODE_PRESET模式停止振动 +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate successful.'); } }) diff --git a/zh-cn/application-dev/reference/apis/js-apis-webview.md b/zh-cn/application-dev/reference/apis/js-apis-webview.md index ddd17eeb6f5f8e044d0a7082df0fe8336c386a94..a31ccc4a1efba63bc781319c0873dfbaa4948a52 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-webview.md +++ b/zh-cn/application-dev/reference/apis/js-apis-webview.md @@ -46,7 +46,11 @@ struct WebComponent { Column() { Button('close') .onClick(() => { - this.msgPort[1].close(); + if (this.msgPort && this.msgPort[1]) { + this.msgPort[1].close(); + } else { + console.error("msgPort is null, Please initialize first"); + } }) Web({ src: 'www.example.com', controller: this.controller }) } @@ -166,7 +170,20 @@ struct WebComponent { ### 创建对象 ```ts -controller: web_webview.WebviewController = new web_webview.WebviewController(); +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} ``` ### loadUrl @@ -192,7 +209,7 @@ loadUrl(url: string | Resource, headers?: Array\): void | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | -| 17100003 | Invalid resource. | +| 17100003 | Invalid resource path or file type. | **示例:** @@ -1001,7 +1018,7 @@ zoom(factor: number): void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web compoent. | -| 17100004 | Cannot delete JavaScriptProxy. | +| 17100004 | Function not enable. | **示例:** @@ -1383,7 +1400,11 @@ struct WebComponent { Button('SendDataToHTML') .onClick(() => { try { - this.ports[1].postMessageEvent("post message from ets to HTML"); + if (this.ports && this.ports[1]) { + this.ports[1].postMessageEvent("post message from ets to HTML"); + } else { + console.error(`ports is null, Please initialize first`); + } } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } @@ -1434,7 +1455,11 @@ window.addEventListener('message', function (event) { // 3. 使用h5Port往ets侧发送消息. function PostMsgToEts(data) { - h5Port.postMessage(data); + if (h5Port) { + h5Port.postMessage(data); + } else { + console.error("h5Port is null, Please initialize first"); + } } ``` @@ -2573,7 +2598,7 @@ static deleteOrigin(origin : string): void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2625,7 +2650,7 @@ static getOrigins(callback: AsyncCallback\>) : void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2686,7 +2711,7 @@ static getOrigins() : Promise\> | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100012 | Invalid web storage origin. | **示例:** @@ -2748,7 +2773,7 @@ static getOriginQuota(origin : string, callback : AsyncCallback\) : void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2812,7 +2837,7 @@ static getOriginQuota(origin : string) : Promise\ | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2871,7 +2896,7 @@ static getOriginUsage(origin : string, callback : AsyncCallback\) : void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -2935,7 +2960,7 @@ static getOriginUsage(origin : string) : Promise\ | 错误码ID | 错误信息 | | -------- | ----------------------------------------------------- | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3213,7 +3238,7 @@ static allowGeolocation(origin: string): void 以下错误码的详细介绍请参见 [webview错误码](../errorcodes/errorcode-webview.md) | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3263,7 +3288,7 @@ static deleteGeolocation(origin: string): void | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** @@ -3314,7 +3339,7 @@ static getAccessibleGeolocation(origin: string, callback: AsyncCallback\ | 错误码ID | 错误信息 | | -------- | ------------------------------------------------------ | -| 17100011 | Invalid permission origin. | +| 17100011 | Invalid origin. | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index 35bfb2ce17c34a439c404a78200f9b8a19a0a441..a0a82cbf7ff47911534159971440dd6df3823450 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -339,7 +339,7 @@ try { }); } catch (exception) { console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.createWindow9+ @@ -386,7 +386,7 @@ try { }); } catch (exception) { console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.findWindow9+ @@ -412,11 +412,12 @@ findWindow(name: string): Window **示例:** ```js +let windowClass = null; try { - let windowClass = window.findWindow('alertWindow'); + windowClass = window.findWindow('alertWindow'); } catch (exception) { console.error('Failed to find the Window. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.getLastWindow9+ @@ -458,7 +459,7 @@ try { }); } catch (exception) { console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.getLastWindow9+ @@ -504,7 +505,7 @@ try { }); } catch (exception) { console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.minimizeAll9+ @@ -535,26 +536,25 @@ minimizeAll(id: number, callback: AsyncCallback<void>): void ```js import display from '@ohos.display' -import window from '@ohos.window' +let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); -} catch (exception) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); - return; -}; -try { - window.minimizeAll(displayClass.id, (err) => { - if(err.code) { - console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in minimizing all windows.'); - }); + try { + window.minimizeAll(displayClass.id, (err) => { + if(err.code) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in minimizing all windows.'); + }); + } catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); + } } catch (exception) { - console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); -}; + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +} ``` ## window.minimizeAll9+ @@ -590,26 +590,24 @@ minimizeAll(id: number): Promise<void> ```js import display from '@ohos.display' -import window from '@ohos.window' let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); -} catch (exception) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); - return; -}; -try { - let promise = window.minimizeAll(displayClass.id); - promise.then(()=> { - console.info('Succeeded in minimizing all windows.'); - }).catch((err)=>{ - console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); - }); + try { + let promise = window.minimizeAll(displayClass.id); + promise.then(()=> { + console.info('Succeeded in minimizing all windows.'); + }).catch((err)=>{ + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); + } } catch (exception) { - console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); -}; + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +} ``` ## window.toggleShownStateForAllAppWindows9+ @@ -644,7 +642,7 @@ window.toggleShownStateForAllAppWindows((err) => { return; } console.info('Succeeded in toggling shown state for all app windows.'); -}) +}); ``` ## window.toggleShownStateForAllAppWindows9+ @@ -678,7 +676,7 @@ promise.then(()=> { console.info('Succeeded in toggling shown state for all app windows.'); }).catch((err)=>{ console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); -}) +}); ``` ## window.setWindowLayoutMode9+ @@ -718,7 +716,7 @@ try { }); } catch (exception) { console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.setWindowLayoutMode9+ @@ -762,7 +760,7 @@ try { }); } catch (exception) { console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.on('systemBarTintChange')8+ @@ -791,7 +789,7 @@ try { }); } catch (exception) { console.error('Failed to enable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.off('systemBarTintChange')8+ @@ -818,7 +816,7 @@ try { window.off('systemBarTintChange'); } catch (exception) { console.error('Failed to disable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ## window.create(deprecated) @@ -1110,7 +1108,7 @@ promise.then((data)=> { console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ## window.getTopWindow(deprecated) @@ -1180,7 +1178,7 @@ promise.then((data)=> { console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ## Window @@ -1221,8 +1219,8 @@ windowClass.hide((err) => { console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); -}) + console.info('Succeeded in hiding the window.'); +}); ``` ### hide7+ @@ -1257,7 +1255,7 @@ promise.then(()=> { console.info('Succeeded in hiding the window.'); }).catch((err)=>{ console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### hideWithAnimation9+ @@ -1295,7 +1293,7 @@ windowClass.hideWithAnimation((err) => { return; } console.info('Succeeded in hiding the window with animation.'); -}) +}); ``` ### hideWithAnimation9+ @@ -1329,10 +1327,10 @@ hideWithAnimation(): Promise<void> ```js let promise = windowClass.hideWithAnimation(); promise.then(()=> { - console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window with animation.'); }).catch((err)=>{ console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### showWindow9+ @@ -1437,7 +1435,7 @@ windowClass.showWithAnimation((err) => { return; } console.info('Succeeded in showing the window with animation.'); -}) +}); ``` ### showWithAnimation9+ @@ -1474,7 +1472,7 @@ promise.then(()=> { console.info('Succeeded in showing the window with animation.'); }).catch((err)=>{ console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### destroyWindow9+ @@ -1509,7 +1507,7 @@ windowClass.destroyWindow((err) => { return; } console.info('Succeeded in destroying the window.'); -}) +}); ``` ### destroyWindow9+ @@ -1543,7 +1541,7 @@ promise.then(()=> { console.info('Succeeded in destroying the window.'); }).catch((err)=>{ console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### moveWindowTo9+ @@ -1584,7 +1582,7 @@ try { }); } catch (exception) { console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); -}; +} ``` ### moveWindowTo9+ @@ -1629,7 +1627,7 @@ try { }); } catch (exception) { console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); -}; +} ``` ### resize9+ @@ -1676,7 +1674,7 @@ try { }); } catch (exception) { console.error('Failed to change the window size. Cause:' + JSON.stringify(exception)); -}; +} ``` ### resize9+ @@ -1727,7 +1725,7 @@ try { }); } catch (exception) { console.error('Failed to change the window size. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowMode9+ @@ -1770,7 +1768,7 @@ try { }); } catch (exception) { console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowMode9+ @@ -1809,7 +1807,7 @@ setWindowMode(mode: WindowMode): Promise<void> ```js let mode = window.WindowMode.FULLSCREEN; try { - let promise = windowClass.setWindowMode(type); + let promise = windowClass.setWindowMode(mode); promise.then(()=> { console.info('Succeeded in setting the window mode.'); }).catch((err)=>{ @@ -1817,7 +1815,7 @@ try { }); } catch (exception) { console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### getWindowProperties9+ @@ -1849,14 +1847,14 @@ try { let properties = windowClass.getWindowProperties(); } catch (exception) { console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### getWindowAvoidArea9+ getWindowAvoidArea(type: AvoidAreaType): AvoidArea -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -1888,7 +1886,7 @@ try { let avoidArea = windowClass.getWindowAvoidArea(type); } catch (exception) { console.error('Failed to obtain the area. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowLayoutFullScreen9+ @@ -1929,7 +1927,7 @@ try { }); } catch (exception) { console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowLayoutFullScreen9+ @@ -1974,7 +1972,7 @@ try { }); } catch (exception) { console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowSystemBarEnable9+ @@ -2016,7 +2014,7 @@ try { }); } catch (exception) { console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowSystemBarEnable9+ @@ -2062,7 +2060,7 @@ try { }); } catch (exception) { console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowSystemBarProperties9+ @@ -2092,7 +2090,7 @@ setWindowSystemBarProperties(systemBarProperties: SystemBarProperties, callback: **示例:** ```js -let SystemBarProperties={ +let SystemBarProperties = { statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', //以下两个属性从API Version8开始支持 @@ -2109,7 +2107,7 @@ try { }); } catch (exception) { console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowSystemBarProperties9+ @@ -2144,7 +2142,7 @@ setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise& **示例:** ```js -let SystemBarProperties={ +let SystemBarProperties = { statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', //以下两个属性从API Version8开始支持 @@ -2160,7 +2158,7 @@ try { }); } catch (exception) { console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setPreferredOrientation9+ @@ -2200,7 +2198,7 @@ try { }); } catch (exception) { console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setPreferredOrientation9+ @@ -2244,7 +2242,7 @@ try { }); } catch (exception) { console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setUIContent9+ @@ -2284,7 +2282,7 @@ try { }); } catch (exception) { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setUIContent9+ @@ -2328,7 +2326,7 @@ try { }); } catch (exception) { console.error('Failed to load the content. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### loadContent9+ @@ -2374,7 +2372,7 @@ try { }); } catch (exception) { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); -}; +} ``` ### loadContent9+ @@ -2424,7 +2422,7 @@ try { }); } catch (exception) { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); -}; +} ``` ### isWindowShowing9+ @@ -2457,7 +2455,7 @@ try { console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); } catch (exception) { console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('windowSizeChange')7+ @@ -2484,7 +2482,7 @@ try { }); } catch (exception) { console.error('Failed to enable the listener for window size changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('windowSizeChange')7+ @@ -2509,7 +2507,7 @@ try { windowClass.off('windowSizeChange'); } catch (exception) { console.error('Failed to disable the listener for window size changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('avoidAreaChange')9+ @@ -2537,7 +2535,7 @@ try { }); } catch (exception) { console.error('Failed to enable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('avoidAreaChange')9+ @@ -2562,7 +2560,7 @@ try { windowClass.off('avoidAreaChange'); } catch (exception) { console.error('Failed to disable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('keyboardHeightChange')7+ @@ -2589,7 +2587,7 @@ try { }); } catch (exception) { console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('keyboardHeightChange')7+ @@ -2614,7 +2612,7 @@ try { windowClass.off('keyboardHeightChange'); } catch (exception) { console.error('Failed to disable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('touchOutside')9+ @@ -2643,7 +2641,7 @@ try { }); } catch (exception) { console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('touchOutside')9+ @@ -2670,7 +2668,7 @@ try { windowClass.off('touchOutside'); } catch (exception) { console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('screenshot')9+ @@ -2697,7 +2695,7 @@ try { }); } catch (exception) { console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('screenshot')9+ @@ -2718,21 +2716,21 @@ off(type: 'screenshot', callback?: Callback<void>): void **示例:** ```js -let callback = ()=>{ +let callback = () => { console.info('screenshot happened'); }; try { windowClass.on('screenshot', callback); } catch (exception) { console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); -}; +} try { windowClass.off('screenshot', callback); // 如果通过on开启多个callback进行监听,同时关闭所有监听: windowClass.off('screenshot'); } catch (exception) { console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### on('dialogTargetTouch')9+ @@ -2759,7 +2757,7 @@ try { }); } catch (exception) { console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### off('dialogTargetTouch')9+ @@ -2784,7 +2782,7 @@ try { windowClass.off('dialogTargetTouch'); } catch (exception) { console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### bindDialogTarget9+ @@ -2817,6 +2815,8 @@ bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>, c **示例:** ```js +import rpc from '@ohos.rpc'; + class MyDeathRecipient { onRemoteDied() { console.log('server died'); @@ -2836,6 +2836,7 @@ class TestRemoteObject extends rpc.RemoteObject { return false; } } + let token = new TestRemoteObject('testObject'); try { windowClass.bindDialogTarget(token, () => { @@ -2849,7 +2850,7 @@ try { }); } catch (exception) { console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); -}; +} ``` ### bindDialogTarget9+ @@ -2887,6 +2888,8 @@ bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>): **示例:** ```js +import rpc from '@ohos.rpc'; + class MyDeathRecipient { onRemoteDied() { console.log('server died'); @@ -2906,6 +2909,7 @@ class TestRemoteObject extends rpc.RemoteObject { return false; } } + let token = new TestRemoteObject('testObject'); try { let promise = windowClass.bindDialogTarget(token, () => { @@ -2918,7 +2922,7 @@ try { }); } catch (exception) { console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); -}; +} ``` ### isWindowSupportWideGamut9+ @@ -3024,7 +3028,7 @@ try { }); } catch (exception) { console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowColorSpace9+ @@ -3067,7 +3071,7 @@ try { }); } catch (exception) { console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); -}; +} ``` ### getWindowColorSpace9+ @@ -3128,7 +3132,7 @@ try { windowClass.setWindowBackgroundColor(color); } catch (exception) { console.error('Failed to set the background color. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowBrightness9+ @@ -3169,7 +3173,7 @@ try { }); } catch (exception) { console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowBrightness9+ @@ -3214,7 +3218,7 @@ try { }); } catch (exception) { console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowFocusable9+ @@ -3244,7 +3248,7 @@ setWindowFocusable(isFocusable: boolean, callback: AsyncCallback<void>): v **示例:** ```js -let isFocusable= true; +let isFocusable = true; try { windowClass.setWindowFocusable(isFocusable, (err) => { if (err.code) { @@ -3255,7 +3259,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowFocusable9+ @@ -3290,7 +3294,7 @@ setWindowFocusable(isFocusable: boolean): Promise<void> **示例:** ```js -let isFocusable= true; +let isFocusable = true; try { let promise = windowClass.setWindowFocusable(isFocusable); promise.then(()=> { @@ -3300,7 +3304,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowKeepScreenOn9+ @@ -3341,7 +3345,7 @@ try { }); } catch (exception) { console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowKeepScreenOn9+ @@ -3386,7 +3390,7 @@ try { }); } catch (exception) { console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWakeUpScreen()9+ @@ -3422,7 +3426,7 @@ try { windowClass.setWakeUpScreen(wakeUp); } catch (exception) { console.error('Failed to wake up the screen. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setWindowPrivacyMode9+ @@ -3464,7 +3468,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowPrivacyMode9+ @@ -3510,7 +3514,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setSnapshotSkip9+ @@ -3583,7 +3587,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setWindowTouchable9+ @@ -3628,7 +3632,7 @@ try { }); } catch (exception) { console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setForbidSplitMove9+ @@ -3671,7 +3675,7 @@ try { }); } catch (exception) { console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### setForbidSplitMove9+ @@ -3718,7 +3722,7 @@ try { }); } catch (exception) { console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); -}; +} ``` ### snapshot9+ @@ -3822,7 +3826,7 @@ try { windowClass.opacity(0.5); } catch (exception) { console.error('Failed to opacity. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### scale9+ @@ -3863,7 +3867,7 @@ try { windowClass.scale(obj); } catch (exception) { console.error('Failed to scale. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### rotate9+ @@ -3905,7 +3909,7 @@ try { windowClass.rotate(obj); } catch (exception) { console.error('Failed to rotate. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### translate9+ @@ -3945,7 +3949,7 @@ try { windowClass.translate(obj); } catch (exception) { console.error('Failed to translate. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### getTransitionController9+ @@ -3998,16 +4002,16 @@ controller.animationForHidden = (context : window.TransitionContext) => { toWindow.translate(obj); // 设置动画过程中的属性转换 console.info('toWindow translate end'); } - ) + ); console.info('complete transition end'); -} +}; windowClass.hideWithAnimation((err, data) => { if (err.code) { console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); return; } console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); -}) +}); ``` ### setBlur9+ @@ -4042,7 +4046,7 @@ try { windowClass.setBlur(4.0); } catch (exception) { console.error('Failed to set blur. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setBackdropBlur9+ @@ -4077,7 +4081,7 @@ try { windowClass.setBackdropBlur(4.0); } catch (exception) { console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setBackdropBlurStyle9+ @@ -4112,7 +4116,7 @@ try { windowClass.setBackdropBlurStyle(window.BlurStyle.THIN); } catch (exception) { console.error('Failed to set backdrop blur style. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setShadow9+ @@ -4150,7 +4154,7 @@ try { windowClass.setShadow(4.0, '#FF00FF00', 2, 3); } catch (exception) { console.error('Failed to set shadow. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### setCornerRadius9+ @@ -4185,7 +4189,7 @@ try { windowClass.setCornerRadius(4.0); } catch (exception) { console.error('Failed to set corner radius. Cause: ' + JSON.stringify(exception)); -}; +} ``` ### show(deprecated) @@ -4215,7 +4219,7 @@ windowClass.show((err) => { return; } console.info('Succeeded in showing the window.'); -}) +}); ``` ### show(deprecated) @@ -4244,7 +4248,7 @@ promise.then(()=> { console.info('Succeeded in showing the window.'); }).catch((err)=>{ console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### destroy(deprecated) @@ -4274,7 +4278,7 @@ windowClass.destroy((err) => { return; } console.info('Succeeded in destroying the window.'); -}) +}); ``` ### destroy(deprecated) @@ -4303,7 +4307,7 @@ promise.then(()=> { console.info('Succeeded in destroying the window.'); }).catch((err)=>{ console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### moveTo(deprecated) @@ -4335,7 +4339,6 @@ windowClass.moveTo(300, 300, (err)=>{ return; } console.info('Succeeded in moving the window.'); - }); ``` @@ -4372,7 +4375,7 @@ promise.then(()=> { console.info('Succeeded in moving the window.'); }).catch((err)=>{ console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); -}) +}); ``` ### resetSize(deprecated) @@ -4590,7 +4593,7 @@ promise.then((data)=> { getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** > @@ -4622,11 +4625,11 @@ windowClass.getAvoidArea(type, (err, data) => { getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** > -> 从 API version 7开始支持,从API version 9开始废弃,推荐使用[getWindowProperties()](#getwindowavoidarea9)。 +> 从 API version 7开始支持,从API version 9开始废弃,推荐使用[getWindowAvoidArea()](#getwindowavoidarea9)。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -5144,7 +5147,7 @@ windowClass.isSupportWideGamut((err, data) => { return; } console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); -}) +}); ``` ### isSupportWideGamut(deprecated) @@ -5204,7 +5207,7 @@ windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => { return; } console.info('Succeeded in setting window colorspace.'); -}) +}); ``` ### setColorSpace(deprecated) @@ -5269,7 +5272,7 @@ windowClass.getColorSpace((err, data) => { return; } console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); -}) +}); ``` ### getColorSpace(deprecated) @@ -5667,7 +5670,7 @@ windowClass.setOutsideTouchable(true, (err) => { return; } console.info('Succeeded in setting the area to be touchable.'); -}) +}); ``` ### setOutsideTouchable(deprecated) @@ -5734,7 +5737,6 @@ windowClass.setPrivacyMode(isPrivacyMode, (err) => { return; } console.info('Succeeded in setting the window to privacy mode.'); - }); ``` @@ -5803,7 +5805,6 @@ windowClass.setTouchable(isTouchable, (err) => { return; } console.info('Succeeded in setting the window to be touchable.'); - }); ``` @@ -5853,10 +5854,10 @@ WindowStage生命周期。 | 名称 | 默认值 | 说明 | | ---------- | ------ | ---------- | -| FOREGROUND | 1 | 切到前台。 | +| SHOWN | 1 | 切到前台。 | | ACTIVE | 2 | 获焦状态。 | | INACTIVE | 3 | 失焦状态。 | -| BACKGROUND | 4 | 切到后台。 | +| HIDDEN | 4 | 切到后台。 | ## WindowStage9+ @@ -5893,6 +5894,7 @@ getMainWindow(callback: AsyncCallback<Window>): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -5906,7 +5908,7 @@ class myAbility extends Ability { console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); }); } -} +}; ``` ### getMainWindow9+ @@ -5938,19 +5940,20 @@ getMainWindow(): Promise<Window> ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; let promise = windowStage.getMainWindow(); - promise.then((data)=> { + promise.then((data) => { windowClass = data; console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ + }).catch((err) => { console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err)); }); } -} +}; ``` ### getMainWindowSync9+ @@ -5982,6 +5985,7 @@ getMainWindowSync(): Window ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -5991,7 +5995,7 @@ class myAbility extends Ability { console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(exception)); }; } -} +}; ``` ### createSubWindow9+ @@ -6024,6 +6028,7 @@ createSubWindow(name: string, callback: AsyncCallback<Window>): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6042,7 +6047,7 @@ class myAbility extends Ability { console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); }; } -} +}; ``` ### createSubWindow9+ @@ -6079,23 +6084,24 @@ createSubWindow(name: string): Promise<Window> ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; try { let promise = windowStage.createSubWindow('mySubWindow'); - promise.then((data)=> { + promise.then((data) => { windowClass = data; console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ + }).catch((err) => { console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); }); } catch (exception) { console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); }; } -} +}; ``` ### getSubWindow9+ @@ -6126,6 +6132,7 @@ getSubWindow(callback: AsyncCallback<Array<Window>>): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6139,7 +6146,7 @@ class myAbility extends Ability { console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); }); } -} +}; ``` ### getSubWindow9+ @@ -6169,19 +6176,20 @@ getSubWindow(): Promise<Array<Window>> ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; let promise = windowStage.getSubWindow(); - promise.then((data)=> { + promise.then((data) => { windowClass = data; console.info('Succeeded in obtaining the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ + }).catch((err) => { console.error('Failed to obtain the subwindow. Cause: ' + JSON.stringify(err)); }) } -} +}; ``` ### loadContent9+ @@ -6214,6 +6222,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { @@ -6232,7 +6241,7 @@ class myAbility extends Ability { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); }; } -} +}; ``` ### loadContent9+ @@ -6271,6 +6280,7 @@ loadContent(path: string, storage?: LocalStorage): Promise<void> ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { @@ -6279,16 +6289,16 @@ class myAbility extends Ability { console.log('onWindowStageCreate'); try { let promise = windowStage.loadContent('pages/page2',this.storage); - promise.then(()=> { + promise.then(() => { console.info('Succeeded in loading the content.'); - }).catch((err)=>{ + }).catch((err) => { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); }); } catch (exception) { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); }; } -} +}; ``` ### loadContent9+ @@ -6321,6 +6331,7 @@ loadContent(path: string, callback: AsyncCallback<void>): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6336,7 +6347,7 @@ class myAbility extends Ability { console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); }; } -} +}; ``` ### on('windowStageEvent')9+ @@ -6369,6 +6380,7 @@ on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType> ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6382,7 +6394,7 @@ class myAbility extends Ability { JSON.stringify(exception)); }; } -} +}; ``` ### off('windowStageEvent')9+ @@ -6415,6 +6427,7 @@ off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType&g ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6425,7 +6438,7 @@ class myAbility extends Ability { JSON.stringify(exception)); }; } -} +}; ``` ### disableWindowDecor()9+ @@ -6453,12 +6466,13 @@ disableWindowDecor(): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('disableWindowDecor'); windowStage.disableWindowDecor(); } -} +}; ``` ### setShowOnLockScreen()9+ @@ -6492,6 +6506,7 @@ setShowOnLockScreen(showOnLockScreen: boolean): void ```ts import Ability from '@ohos.application.Ability'; + class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); @@ -6501,7 +6516,7 @@ class myAbility extends Ability { console.error('Failed to show on lockscreen. Cause:' + JSON.stringify(exception)); }; } -} +}; ``` ## TransitionContext9+ @@ -6555,7 +6570,7 @@ controller.animationForShown = (context : window.TransitionContext) => { toWindow.translate(obj); console.info('toWindow translate end'); } - ) + ); try { context.completeTransition(true) } catch (exception) { @@ -6610,9 +6625,9 @@ controller.animationForShown = (context : window.TransitionContext) => { toWindow.translate(obj); console.info('toWindow translate end'); } - ) + ); console.info('complete transition end'); -} +}; ``` ### animationForHidden9+ @@ -6658,5 +6673,5 @@ controller.animationForHidden = (context : window.TransitionContext) => { } ) console.info('complete transition end'); -} +}; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md b/zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md index 4f7dfd2cadeb9d48ed10bb06d56675692192321a..cb6128d2e14a590c3c244e9e31983640fe22465f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -61,7 +61,7 @@ let controller = { console.log('onScreenUnlock called'); finishCallback.onAnimationFinish(); }, - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void { console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); } @@ -83,7 +83,7 @@ minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget, callback: Async | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | windowTarget | [WindowAnimationTarget](#windowanimationtarget) | 是 | 动画目标窗口。| -| callback | AsyncCallback<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | 是 | 动画完成后的回调。| +| callback | AsyncCallback<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | 是 | 回调函数。当最小化动画目标窗口成功,err为undefined,data为获取到的WindowAnimationFinishedCallback;否则返回err.code为-1,data为undefined。| **示例:** @@ -92,52 +92,59 @@ let target: WindowAnimationTarget = undefined; let controller = { onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); + target = startingWindowTarget; finishCallback.onAnimationFinish(); }, onStartAppFromRecent(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onStartAppFromRecent, the startingWindowTarget is: ' + startingWindowTarget); + target = startingWindowTarget; finishCallback.onAnimationFinish(); }, onStartAppFromOther(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onStartAppFromOther, the startingWindowTarget is: ' + startingWindowTarget); + target = startingWindowTarget; finishCallback.onAnimationFinish(); }, onAppTransition(fromWindowTarget: windowAnimationManager.WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onAppTransition, the fromWindowTarget is: ' + fromWindowTarget); console.log('onAppTransition, the toWindowTarget is: ' + toWindowTarget); + target = toWindowTarget; finishCallback.onAnimationFinish(); }, onMinimizeWindow(minimizingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onMinimizeWindow, the minimizingWindowTarget is: ' + minimizingWindowTarget); + target = minimizingWindowTarget; finishCallback.onAnimationFinish(); }, onCloseWindow(closingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onCloseWindow, the closingWindowTarget is: ' + closingWindowTarget); + target = closingWindowTarget; finishCallback.onAnimationFinish(); }, onScreenUnlock(finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { console.log('onScreenUnlock called'); finishCallback.onAnimationFinish(); }, - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void { console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); + target = fullScreenWindowTarget; } } windowAnimationManager.setController(controller) -let finishedCallback = null; +let finishedCallback: windowAnimationManager.WindowAnimationFinishedCallback = undefined; windowAnimationManager.minimizeWindowWithAnimation(target, (err, data) => { - if (err.code) { + if (err) { console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); return; } - finishedCallback = data; -}); -finishedCallback.onAnimationFinish(); + // 在收到回调后,需要开始进行窗口动画,在窗口动画结束后,调用onAnimationFinish回调 + finishedCallback.onAnimationFinish(); +}); ``` ## windowAnimationManager.minimizeWindowWithAnimation @@ -195,7 +202,7 @@ let controller = { console.log('onScreenUnlock called'); finishCallback.onAnimationFinish(); }, - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void { console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); } @@ -348,7 +355,7 @@ onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, fl | 参数名 | 类型 | 必填 | 说明 | | -------------------- | ------------------------------- | ---- | ---------------- | | fullScreenWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | 是 | 全屏状态的动画目标窗口。| -| floatingWindowTargets| Array<[WindowAnimationTarget](#windowanimationtarget)> | 是 | 悬浮状态的动画目标窗口 | +| floatingWindowTargets| Array<[WindowAnimationTarget](#windowanimationtarget)> | 是 | 悬浮状态的动画目标窗口。 | **示例:** @@ -379,7 +386,7 @@ onAnimationFinish():void | bundleName | string | 动画目标窗口所对应的包名。 | | abilityName | string | 动画目标窗口所对应的Ability名称。 | | windowBounds | [RRect](#rrect) | 动画目标窗口所对应的实际大小。 | -| missionId | number | 任务ID。| +| missionId | number | 任务ID,多任务中用于与ability进行匹配。| ## RRect 圆角矩形。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 483a26e968c80663a800b432589434dd0e4440c9..b7daa69d0787b677544129f7117517f77fe83a14 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -1495,7 +1495,7 @@ workerInstance.onexit = function() { } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 @@ -1508,7 +1508,7 @@ const parentPort = worker.workerPort parentPort.onmessage = function(e) { // data:主线程发送的信息 let data = e.data; - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); // worker线程向主线程发送信息 parentPort.postMessage("123") @@ -1516,7 +1516,7 @@ parentPort.onmessage = function(e) { // worker线程发生error的回调 parentPort.onerror= function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` build-profile.json5 配置 : @@ -1557,7 +1557,7 @@ workerInstance.onexit = function() { } ``` ```js -// worker.js +// worker.ts import worker from '@ohos.worker'; // 创建worker线程中与主线程通信的对象 @@ -1567,7 +1567,7 @@ const parentPort = worker.workerPort parentPort.onmessage = function(e) { // data:主线程发送的信息 let data = e.data; - console.log("worker.js onmessage"); + console.log("worker.ts onmessage"); // worker线程向主线程发送信息 parentPort.postMessage("123") @@ -1575,7 +1575,7 @@ parentPort.onmessage = function(e) { // worker线程发生error的回调 parentPort.onerror= function(e) { - console.log("worker.js onerror"); + console.log("worker.ts onerror"); } ``` build-profile.json5 配置: diff --git a/zh-cn/application-dev/reference/apis/js-apis-xml.md b/zh-cn/application-dev/reference/apis/js-apis-xml.md index a9b0b31194d67d5adea06869f9f342079035a209..e137f45c98981154d20a0e2e876ded514bb2f369 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-xml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-xml.md @@ -58,7 +58,9 @@ setAttributes(name: string, value: string): void let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setAttributes("importance", "high"); +thatSer.startElement("note"); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-zlib.md b/zh-cn/application-dev/reference/apis/js-apis-zlib.md index 8138283e12eac6f85872a718f035bf00670afb64..84b3499495eba387eea6c99683c21506144be1d8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-zlib.md +++ b/zh-cn/application-dev/reference/apis/js-apis-zlib.md @@ -13,7 +13,7 @@ import zlib from '@ohos.zlib'; ``` ## zlib.zipFile(deprecated) - zipFile(inFile:string, outFile:string, options: Options): Promise<void> +zipFile(inFile: string, outFile: string, options: Options): Promise<void> 压缩接口(Promise形式)。 @@ -26,7 +26,7 @@ import zlib from '@ohos.zlib'; | 参数名 | 类型 | 必填 | 描述 | | ------- | ------------------- | ---- | ------------------------------------------------------------ | | inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[Stage模型](js-apis-application-context.md) | -| outFile | string | 是 | 指定的压缩结果的文件路径(文件的扩展名zip) | +| outFile | string | 是 | 指定压缩结果的文件路径(文件的扩展名zip) | | options | [Options](#options) | 否 | 压缩的可选参数 | **返回值:** @@ -37,43 +37,41 @@ import zlib from '@ohos.zlib'; **示例1:** -```javascript - +```typescript //【压缩文件 例子1】 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile, outFile, options).then((data) => { - console.log("zipFile result:" + data); -}).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('zipFile result is ' + JSON.Stringify(data)); +}).catch((err) => { + console.log('error is ' + JSON.Stringify(err)); }); - ``` **示例2:** -``` +```typescript // 【压缩文件夹 例子2】 -import zlib from '@ohos.zlib' -var inFile = "/xxx/xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.zipFile(inFile , outFile, options).then((data) => { - console.log("zipFile result:" + data); + console.log('zipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }); ``` @@ -103,11 +101,11 @@ unzipFile(inFile:string, outFile:string, options: Options): Promise<void> **示例:** -```javascript -// 【解压例子1】 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; +```typescript +// 【解压缩 例子1】 +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, @@ -115,16 +113,15 @@ let options = { strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; zlib.unzipFile(inFile, outFile, options).then((data) => { - console.log("unzipFile result:" + data); + console.log('unzipFile result is ' + JSON.Stringify(data)); }).catch((err)=>{ - console.log("catch((err)=>" + err); + console.log('error is ' + JSON.Stringify(err)); }) - ``` ## zlib.compressFile9+ -**function** compressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; +compressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; 压缩文件,压缩的结果通过callback返回。成功时返回null,失败时返回错误码。 @@ -149,13 +146,13 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { **示例** -```javascript -// 【压缩例子1】 +```typescript +// 【压缩文件 例子1】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY @@ -163,16 +160,16 @@ var options = { try { zlib.compressFile(inFile, outFile, options, (errData) => { - if (erData != null) { - console.log("errData is " + errData.errCode + " " + errData.message) + if (errData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` -**function** compressFile(inFile:**string**, outFile:**string**, options: Options): Promise<**void**>; +compressFile(inFile: string, outFile: string, options: Options): Promise\; 压缩文件,压缩的结果通过promise返回,成功时返回null,失败时返回错误码。 @@ -180,12 +177,11 @@ try { **参数:** -| 参数名 | 类型 | 必填 | 描述 | -| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | -| outFile | string | 是 | 指定的解压文件路径 | -| options | [Options](#options) | 是 | 压缩的配置参数 | -| AsyncCallback<**void**> | callback | 否 | 压缩时的回调函数 | +| 参数名 | 类型 | 必填 | 描述 | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,对应的路径参考[FA模型](js-apis-Context.md),[stage模型](js-apis-application-context.md) | +| outFile | string | 是 | 指定的解压文件路径 | +| options | [Options](#options) | 是 | 压缩的配置参数 | **相关错误码** @@ -195,37 +191,39 @@ try { | 900001 | The Input source file is invalid. | | 900002 | The Input destination file is invalid. | -```javascript -// 【压缩例子2】 +```typescript +// 【压缩文件 例子2】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xxx/filename.xxx"; -var outFile = "/xxx/xxx.zip"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xxx/filename.xxx'; +let outFile = '/xxx/xxx.zip'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; try { - zlib.compressFile(inFile, outFile, options).then(data => { - console.info("compressFile success") - }).catch(errData => { - console.info("catch err " + errData.errCode + " " + errData.message) + zlib.compressFile(inFile, outFile, options).then((data) => { + console.info('compressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` ## zlib.decompressFile9+ -**function** decompressFile(inFile: **string**, outFile: **string**, options: Options, callback: AsyncCallback<**void**>): **void**; +decompressFile(inFile: string, outFile: string, options: Options, callback: AsyncCallback\): void; 解压文件,解压的结果通过callback返回,成功时返回null,失败时返回错误码。 +**系统能力:** SystemCapability.BundleManager.Zlib + **参数:** | 参数名 | 类型 | 必填 | 描述 | @@ -245,32 +243,35 @@ try { **示例** -```javascript -// 【解压缩例子1】 +```typescript +// 【解压缩 例子1】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; + try { zlib.decompressFile(inFile, outFile, options, (errData) => { - if (erData != null) { - console.log("errData is " + errData.errCode + " " + errData.message) + if (errData !== null) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` -**function** decompressFile(inFile: **string**, outFile: **string**, options: Options): Promise<**void**>; +decompressFile(inFile: string, outFile: string, options: Options): Promise\; 解压文件,解压的结果通过promise返回,成功时返回null,失败时返回错误码。 +**系统能力:** SystemCapability.BundleManager.Zlib + **参数:** | 参数名 | 类型 | 必填 | 描述 | @@ -287,26 +288,27 @@ try { | 900001 | The Input source file is invalid. | | 900002 | The Input destination file is invalid. | -```javascript -// 【解压缩例子2】 +```typescript +// 【解压缩 例子2】 // 代码中使用的路径需为应用的沙箱路径,如/data/storage/el2/base/haps,也可以通过context获取 -import zlib from '@ohos.zlib' -var inFile = "/xx/xxx.zip"; -var outFile = "/xxx"; -var options = { +import zlib from '@ohos.zlib'; +let inFile = '/xx/xxx.zip'; +let outFile = '/xxx'; +let options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY }; + try { - zlib.compressFile(inFile, outFile, options).then(data => { - console.info("compressFile success") - }).catch(errData => { - console.info("catch err " + errData.errCode + " " + errData.message) + zlib.decompressFile(inFile, outFile, options).then((data) => { + console.info('decompressFile success'); + }).catch((errData) => { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); }) -} catch(errData => { - console.log("catch err " + errData.errCode + " " + errData.message) -}) +} catch(errData) { + console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); +} ``` ## Options @@ -319,16 +321,6 @@ try { | memLevel | MemLevel | 否 | 参考[zip.MemLevel枚举定义](#zipmemlevel) | | strategy | CompressStrategy | 否 | 参考[zip.CompressStrategy枚举定义](#zipcompressstrategy) | -## zip.MemLevel - -**系统能力:** SystemCapability.BundleManager.Zlib - -| 名称 | 值 | 说明 | -| ----------------- | ---- | -------------------------------- | -| MEM_LEVEL_MIN | 1 | zip 接口在压缩过程中最小使用内存 | -| MEM_LEVEL_MAX | 9 | zip 接口在压缩过程中最大使用内存 | -| MEM_LEVEL_DEFAULT | 8 | zip 接口在压缩过程中默认使用内存 | - ## zip.CompressLevel **系统能力:** SystemCapability.BundleManager.Zlib @@ -340,6 +332,16 @@ try { | COMPRESS_LEVEL_BEST_COMPRESSION | 9 | 最佳压缩等级 | | COMPRESS_LEVEL_DEFAULT_COMPRESSION | -1 | 默认压缩等级 | +## zip.MemLevel + +**系统能力:** SystemCapability.BundleManager.Zlib + +| 名称 | 值 | 说明 | +| ----------------- | ---- | -------------------------------- | +| MEM_LEVEL_MIN | 1 | zip 接口在压缩过程中最小使用内存 | +| MEM_LEVEL_MAX | 9 | zip 接口在压缩过程中最大使用内存 | +| MEM_LEVEL_DEFAULT | 8 | zip 接口在压缩过程中默认使用内存 | + ## zip.CompressStrategy **系统能力:** SystemCapability.BundleManager.Zlib diff --git a/zh-cn/application-dev/reference/arkui-js/Readme-CN.md b/zh-cn/application-dev/reference/arkui-js/Readme-CN.md index c67743da8b03297fba24172d508281d34d56e64a..d8146c1f6c803a9eccfd039f8ef002db0705db5d 100644 --- a/zh-cn/application-dev/reference/arkui-js/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-js/Readme-CN.md @@ -96,10 +96,9 @@ - 自定义组件 - [基本用法](js-components-custom-basic-usage.md) + - [数据传递与处理](js-components-custom-props.md) - [继承样式](js-components-custom-style.md) - - [自定义事件](js-components-custom-events.md) - - [Props](js-components-custom-props.md) - - [事件参数](js-components-custom-event-parameter.md) - [slot插槽](js-components-custom-slot.md) - [生命周期定义](js-components-custom-lifecycle.md) +- [动态创建组件](js-components-create-elements.md) - [数据类型说明](js-appendix-types.md) diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif deleted file mode 100644 index 6168a14aa67c866abf6185ba3a3c2ae9f595153c..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001127284934.gif and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001152610806.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001152610806.png index b3a47a84d8086ca0806bc958f745f29821c47cc2..30ab31575654579e9a00a64d3d67f7420662f203 100644 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001152610806.png and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001152610806.png differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif new file mode 100644 index 0000000000000000000000000000000000000000..16e7ff213bd5caf5a9802001d3ced2996c66e0bc Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001176075554.gif differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214619417.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214619417.png index 5da42e3e14d601745274cb62d914c6600620bb25..4f6c19892155444ecf63dab3ca80575a8046cc1b 100644 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214619417.png and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214619417.png differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214704759.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214704759.png index 6afdd1b39e4bcb3664c7664a55b47b8537f4aeaa..0b4837fc44abc0e1005de3d1259ed924f2969806 100644 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214704759.png and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214704759.png differ diff --git a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214811029.png b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214811029.png index 1d71cee4618f1f2822cea1031c9b0e5d602e0a9b..447e5b819bdddc57b98ccf7629d612eb499aec8b 100644 Binary files a/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214811029.png and b/zh-cn/application-dev/reference/arkui-js/figures/zh-cn_image_0000001214811029.png differ diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-image.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-image.md index 346f5798c77b29c22172b9f6fe82ab60322168c4..db240326e125d4d08f92811c025d00ab87320ac3 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-image.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-image.md @@ -54,6 +54,8 @@ > 1. 如果image组件本身的长宽小于svg中的长宽,svg会被裁切,仅显示左上角部分; > > 2. 如果image组件本身的长宽大于svg中的长宽,svg会被放置在image组件的左上角,image组件其他部分显示空白。 +> +> - 图片设置svg图源时,支持的标签范围有限,目前支持的svg标签包括svg、rect、circle、ellipse、path、line、polyline、polygon、animate、animateMotion、animateTransform。 ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-input.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-input.md index 73d0d355a411f3cf549ace6f870427b80fc357cc..4921a3c4eb0446567ae16b27aaa994820fd55542 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-input.md @@ -101,26 +101,28 @@ headericon="/common/search.svg" placeholder="Please input text" onchange="change" onenterkeyclick="enterkeyClick"> - + ``` ```css /* xxx.css */ .content { - width: 60%; + width: 100%; flex-direction: column; align-items: center; } .input { + width: 60%; placeholder-color: gray; } .button { + width: 60%; background-color: gray; margin-top: 20px; - } + } ``` - + ```js // xxx.js import prompt from '@system.prompt' @@ -142,9 +144,10 @@ error: 'error text' }); }, - } + } ``` + ![zh-cn_image_0000001252835901](figures/zh-cn_image_0000001252835901.png) 2. type为button diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-label.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-label.md index ae7bebf6bbbbe32d419bd75df5587279c3a29553..d134e5bf1090eeddf3c664eee8f8d584eb9050ea 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-label.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-label.md @@ -82,7 +82,7 @@ /*xxx.css */ .container { flex-direction: column; - align-items: center; + margin-left: 20px; } .row { flex-direction: row; diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md index 1bf885a86bb1120ccb2819a402aadac3c7b01ec5..8e8894ff6e0c33cbd3681f8ee9b174bcc1f5f943 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-marquee.md @@ -64,74 +64,77 @@ ```html -
- {{marqueeCustomData}} -
- - +
+
+ + Life is a journey, not the destination. + +
+
+ +
``` ```css /* xxx.css */ -.container { +.tutorial-page { + width: 750px; + height: 100%; flex-direction: column; - justify-content: center; align-items: center; - background-color: #ffffff; + justify-content: center; } -.customMarquee { - width: 100%; - height: 80px; - padding: 10px; - margin: 20px; - border: 4px solid #ff8888; - border-radius: 20px; - font-size: 40px; - color: #ff8888; - font-weight: bolder; - font-family: serif; - background-color: #ffdddd; +.marqueetext { + font-size: 37px; } -.content { - flex-direction: row; +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #dc0f27; + border-radius: 15px; + align-items: center; } -.controlButton { - flex-grow: 1; - background-color: #F2F2F2; - text-color: #0D81F2; +button{ + width: 200px; + height: 80px; + margin-top: 100px; } ``` ```js // xxx.js export default { - data: { - scrollAmount: 30, - loop: 3, - marqueeDir: 'left', - marqueeCustomData: 'Custom marquee', - }, - onMarqueeBounce: function() { - console.log("onMarqueeBounce"); + private: { + loopval: 1, + scroll: 8, + color1: 'red' }, - onMarqueeStart: function() { - console.log("onMarqueeStart"); + onInit(){ }, - onMarqueeFinish: function() { - console.log("onMarqueeFinish"); + setfinish(e) { + this.loopval= this.loopval + 1, + this.r = Math.floor(Math.random()*255), + this.g = Math.floor(Math.random()*255), + this.b = Math.floor(Math.random()*255), + this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)', + this.$element('testmarquee').start(), + this.loopval= this.loopval - 1 }, - onStartClick (evt) { - this.$element('customMarquee').start(); + makestart(e) { + this.$element('testmarquee').start() }, - onStopClick (evt) { - this.$element('customMarquee').stop(); + makestop(e) { + this.$element('testmarquee').stop() } } ``` -![zh-cn_image_0000001127284934](figures/zh-cn_image_0000001127284934.gif) +![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif) diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md index 3c38f3db2dc824e700b7488b53373b5a83bc7ae1..ae142ab4eef9c42886d9cf1d52b2f12571376f8a 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -165,52 +165,59 @@ ```html
- - - - - - - - - - - + + + + + + + + + +
``` ```css /* xxx.css */ -.container { - flex-direction: column; - justify-content: center; - align-items: center; +.container { + flex-direction: column; + justify-content: center; + align-items: center; } - picker{ - width:60%; - height:80px; - border-radius:20px; - text-color:white; - font-size:15px; - background-color:#4747e3; - margin-left:20%; + +picker { + width: 60%; + height: 80px; + border-radius: 20px; + text-color: white; + font-size: 15px; + background-color: #4747e3; + margin-left: 20%; } - select{ - background-color: #efecec; - height: 50px; - width: 60%; - margin-left: 20%; - margin-top: 300px; - margin-bottom: 50px; - font-size: 22px; + +select { + background-color: #efecec; + height: 50px; + width: 60%; + margin-left: 20%; + margin-top: 300px; + margin-bottom: 50px; + font-size: 22px; } ``` @@ -218,72 +225,96 @@ // xxx.js import router from '@system.router'; import prompt from '@system.prompt'; + export default { - data: { - selectList:["text","data","time","datetime","multitext"], - rangetext:['15', "20", "25"], - multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]], - textvalue:'default textvalue', - datevalue:'default datevalue', - timevalue:'default timevalue', - datetimevalue:'default datetimevalue', - multitextvalue:'default multitextvalue', - containsecond:true, - multitextselect:[1,2,0], - datetimeselect:'2012-5-6-11-25', - timeselect:'11:22:30', - dateselect:'2021-3-2', - textselect:'2' - }, - selectChange(e){ - for(let i = 0;i - Value - 123 Type Color diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvas.md b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvas.md index 6715bc42fc91491db5d363173a0962962603faec..637be8eba85b2792272b3d59cdd07e4940cb6313 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvas.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvas.md @@ -37,7 +37,7 @@ ### getContext -getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext +getContext(type: '2d', options?: ContextAttrOptions): CanvasRenderingContext2D 获取canvas绘图上下文。不支持在onInit和onReady中进行调用。 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 6f6a7992c56adb2b92150507c88dceefc647f313..807122809834e844ae1f2ded1c70f49141b7514a 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -25,19 +25,21 @@ addColorStop(offset: number, color: string): void
-
``` ```js // xxx.js export default { - handleClick() { + onShow() { const el =this.$refs.canvas; - const ctx =el.getContext('2d'); - const gradient = ctx.createLinearGradient(0,0,100,0); - gradient.addColorStop(0,'#00ffff'); - gradient.addColorStop(1,'#ffff00'); + const ctx = el.getContext('2d'); + const gradient = ctx.createLinearGradient(50,0,300,100); + gradient.addColorStop(0.0, 'red') + gradient.addColorStop(0.5, 'white') + gradient.addColorStop(1.0, 'green') + ctx.fillStyle = gradient + ctx.fillRect(0, 0, 300, 300) } } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index fa2d921d02097ffda89f80b016ab3b7f5661b0bc..ecae9a9fba09726ebf36874ae86605c0c9eea964 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -584,7 +584,7 @@ fillRect(x: number, y: number, width:number, height: number): void ```html
- +
``` @@ -620,7 +620,7 @@ clearRect(x: number, y: number, width:number, height: number): void ```html
- +
``` @@ -983,7 +983,7 @@ createPattern(image: Image, repetition: string): Object ```html
- +
``` @@ -997,7 +997,7 @@ createPattern(image: Image, repetition: string): Object img.src = 'common/images/example.jpg'; var pat = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pat; - ctx.fillRect(0, 0, 20, 20); + ctx.fillRect(0, 0, 500, 500); } } ``` @@ -1573,7 +1573,7 @@ drawImage(image: Image | PixelMap, sx: number, sy: number, sWidth: number, sHeig ```html
- +
``` @@ -1581,11 +1581,11 @@ drawImage(image: Image | PixelMap, sx: number, sy: number, sWidth: number, sHeig //xxx.js export default { onShow() { - var test = this.$element('drawImage'); + var test = this.$refs.canvas; var ctx = test.getContext('2d'); var img = new Image(); img.src = 'common/image/test.jpg'; - ctx.drawImage(img, 50, 80, 80, 80); + ctx.drawImage(img, 0, 0, 200, 200, 10, 10, 200, 200); } } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-path2d.md b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-path2d.md index e09ea90de9b7d96609d7ea9430c64dfbbcecb2f1..9e1edeb0c09f9f23b7f078b2bd0aa5e7dcc5fe44 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-canvas-path2d.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-canvas-path2d.md @@ -65,7 +65,7 @@ setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, trans ```html
- +
``` @@ -96,7 +96,7 @@ closePath(): void ```html
- +
``` @@ -224,7 +224,7 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ```html
- +
``` @@ -265,7 +265,7 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ```html
- +
``` @@ -308,7 +308,7 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, ```html
- +
``` @@ -349,7 +349,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ```html
- +
``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-common-transition.md b/zh-cn/application-dev/reference/arkui-js/js-components-common-transition.md index 67e55748dcf4baf58b5df617cc9bd0300baab7a0..7785dfd52b5e5c8a026ecc5882d2c6751e28abb3 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-common-transition.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-common-transition.md @@ -319,7 +319,7 @@ Page1有一个不透明盒子,点击盒子会跳转到Page2,当点击Page2
transition
-
``` ```js diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md index 396137bfec9a550a7d5e615c397cdfd1470cbae2..d5ca0fc58411acef62562fb9d23aec49b3921d14 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-list.md @@ -62,16 +62,16 @@ 除支持[通用事件](../arkui-js/js-components-common-events.md)外,还支持如下事件: -| 名称 | 参数 | 描述 | -| -------------------------- | ---------------------------------------- | ---------------------------------------- | -| indexerchange5+ | { local: booleanValue } | 多语言索引条切换事件,仅当indexer属性为true,indexermulti为true时生效。booleanValue可能值为true或者false:
- true: 当前展示本地索引。
- false: 当前展示字母索引。 | +| 名称 | 参数 | 描述 | +| -------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| indexerchange5+ | { local: booleanValue } | 多语言索引条切换事件,仅当indexer属性为true,indexermulti为true时生效。booleanValue可能值为true或者false:
- true: 当前展示本地索引。
- false: 当前展示字母索引。 | | scroll | { scrollX: scrollXValue, scrollY: scrollYValue, scrollState: stateValue } | 列表滑动的偏移量和状态回调。
stateValue: 0表示列表滑动已经停止。
stateValue: 1表示列表正在用户触摸状态下滑动。
stateValue: 2表示列表正在用户松手状态下滑动。 | -| scrollbottom | - | 当前列表已滑动到底部位置。 | -| scrolltop | - | 当前列表已滑动到顶部位置。 | -| scrollend | - | 列表滑动已经结束。 | -| scrolltouchup | - | 手指已经抬起且列表仍在惯性滑动。 | -| requestitem | - | 请求创建新的list-item。
长列表延迟加载时,可视区域外缓存的list-item数量少于cachedcount时,会触发该事件。 | -| rotate7+ | { rotateValue: number } | 返回表冠旋转角度增量值,仅智能穿戴支持。 | +| scrollbottom | - | 当前列表已滑动到底部位置。 | +| scrolltop | - | 当前列表已滑动到顶部位置。 | +| scrollend | - | 列表滑动已经结束。 | +| scrolltouchup | - | 手指已经抬起且列表仍在惯性滑动。 | +| requestitem | - | 请求创建新的list-item。
长列表延迟加载时,可视区域外缓存的list-item数量少于cachedcount时,会触发该事件。 | +| rotation7+ | { rotateValue: number } | 返回表冠旋转角度增量值,仅智能穿戴支持。 | ## 方法 @@ -118,10 +118,10 @@ export default { data: { todolist: [{ title: '刷题', - date: '2021-12-31 10:00:00', + date: '2021-12-31 10:00:00' }, { title: '看电影', - date: '2021-12-31 20:00:00', + date: '2021-12-31 20:00:00' }], }, } diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md index 2b91d44ae98b9d706c0cf8c6c64631f827406159..fad69559050a21e56ed32a0004645d6459722c55 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-panel.md @@ -85,58 +85,63 @@ ```html
-
- -
- -
-
- Simple panel in {{modeFlag}} mode -
-
- -
+
+
- + +
+
+ Simple panel in {{ modeFlag }} mode +
+
+ +
+
+
``` ```css /* xxx.css */ .doc-page { - flex-direction: column; - justify-content: center; - align-items: center; + flex-direction: column; + justify-content: center; + align-items: center; } + .btn-div { - width: 100%; - height: 200px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 200px; + flex-direction: column; + align-items: center; + justify-content: center; } + .txt { - color: #000000; - font-weight: bold; - font-size: 39px; + color: #000000; + font-weight: bold; + font-size: 39px; } + .panel-div { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .inner-txt { - width: 100%; - height: 160px; - flex-direction: column; - align-items: center; - justify-content: center; + width: 100%; + height: 160px; + flex-direction: column; + align-items: center; + justify-content: center; } + .inner-btn { - width: 100%; - height: 120px; - justify-content: center; - align-items: center; + width: 100%; + height: 120px; + justify-content: center; + align-items: center; } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md index b6681a3a43402e11518ee088d097236faf4a0deb..47cfbf39da7cbadfc63acc8b9fe5b131e06303b3 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-popup.md @@ -115,7 +115,7 @@ export default { visibilitychange(e) { prompt.showToast({ message: 'visibility change visibility: ' + e.visibility, - duration: 3000, + duration: 3000 }); }, showpopup() { @@ -123,7 +123,7 @@ export default { }, hidepopup() { this.$element("popup").hide(); - }, + } } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md index a62cc034ebbc4af29821b30aaf386be70afe5b15..a026e81bd9e1646cb37f4f6fdbbebe8104e99ebb 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-stepper.md @@ -62,93 +62,97 @@ ```html -
- - -
- First screen -
- -
- -
- Second screen -
- -
- -
- Third screen -
- -
-
+
+ + +
+ First screen +
+ +
+ +
+ Second screen +
+ +
+ +
+ Third screen +
+ +
+
``` ```css /* xxx.css */ .container { - margin-top: 20px; - flex-direction: column; - align-items: center; - height: 300px; + margin-top: 20px; + flex-direction: column; + align-items: center; + height: 300px; } + .stepperItem { - width: 100%; - flex-direction: column; - align-items: center; + width: 100%; + flex-direction: column; + align-items: center; } + .stepperItemContent { - color: #0000ff; - font-size: 50px; - justify-content: center; + font-size: 50px; + justify-content: center; } + .button { - width: 60%; - margin-top: 30px; - justify-content: center; + width: 60%; + margin-top: 30px; + justify-content: center; } ``` ```js // xxx.js export default { - data: { - label_1: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_2: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - label_3: - { - prevLabel: 'BACK', - nextLabel: 'NEXT', - status: 'normal' - }, - }, - setRightButton(e) { - this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'}); - }, - nextclick(e) { - var index = { - pendingIndex: e.pendingIndex - } - return index; - }, - backclick(e) { - var index = { - pendingIndex: e.pendingIndex + data: { + label_1: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_2: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + }, + label_3: + { + prevLabel: 'BACK', + nextLabel: 'NEXT', + status: 'normal' + } + }, + setRightButton(e) { + this.$element('mystepper').setNextButtonStatus({ + status: 'skip', label: 'SKIP' + }); + }, + nextclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; + }, + backclick(e) { + var index = { + pendingIndex: e.pendingIndex + } + return index; } - return index; - }, } ``` diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md b/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md index 71823ace1f55c72bab674028c058be15050a906c..57b9e1b4212ff391a200353282c426ad1200e0c8 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-container-tabs.md @@ -12,8 +12,7 @@ tab页签容器。 ## 子组件 -仅支持最多一个<[tab-bar](../arkui-js/js-components-container-tab-bar.md)>和最多一个<[tab-content](../arkui-js/js-components-container-tab-content.md)>。 - +仅支持<[tab-bar](../arkui-js/js-components-container-tab-bar.md)>和<[tab-content](../arkui-js/js-components-container-tab-content.md)>。 ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md b/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md new file mode 100644 index 0000000000000000000000000000000000000000..5c86727d5b714f5be38752746d48e91e8a855954 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-js/js-components-create-elements.md @@ -0,0 +1,145 @@ +# 动态创建组件 + +提供在页面中动态添加组件,并为动态添加的组件设置属性与样式的能力。 + +> **说明:** +> +> - 从API version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## createElement + +createElement(tag: string): Element + +创建一个组件对象。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| tag | string | 是 | 组件名称。 | + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------- | +| Element | 对应tag名称的组件对象。 | + +```js +let newImage = dom.createElement('image') +``` + + +## setAttribute + +setAttribute(name: string, value: string): void + +动态设置组件的属性。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| name | string | 是 | 属性名称。 | +| value | string | 是 | 属性值。 | + +```js +newImage.setAttribute('src', 'common/testImage.jpg') +``` + + +## setStyle + +setStyle(name: string, value: string): boolean + +动态设置组件的样式。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| name | string | 是 | 样式名称。 | +| value | string | 是 | 样式值。 | + +**返回值:** + +| 类型 | 说明 | +| ----------- | ------------- | +| boolean | 设置成功时返回true,失败时返回false。 | + +```js +newImage.setStyle('width', '120px') +``` + + +## addChild + +addChild(child: Element): void + +将动态创建的组件添加到父组件当中。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------ | ---- | ------- | +| child | Element | 是 | 组件对象。 | + +```js +newDiv.addChild(newImage) +``` + + +## 示例 + +```html + +
+
+ + +
+``` + +```css +/* xxx.css */ +.container { + flex-direction: column; + align-items: center; + width: 100%; +} + +.parent { + flex-direction: column; +} + +.btn { + width: 70%; + height: 60px; + margin: 15px; +} +``` + +```js +// xxx.js +let newDiv = null +let newImage = null + +export default { + appendDiv() { + let parent = this.$element('parentDiv') + newDiv = dom.createElement('div') + newDiv.setStyle('width', '150px') + newDiv.setStyle('height', '150px') + newDiv.setStyle('backgroundColor', '#AEEEEE') + newDiv.setStyle('marginTop', '15px') + parent.addChild(newDiv) + }, + appendImage() { + newImage = dom.createElement('image') + newImage.setAttribute('src', 'common/testImage.jpg') + newImage.setStyle('width', '120px') + newImage.setStyle('height', '120px') + newDiv.addChild(newImage) + } +} +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md index 4cfab1d92123f922b591eae1b5f70a4433f446fb..bbd00b8c1bf389bc026f2f3617fc3cc70e93cdd4 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-basic-usage.md @@ -1,6 +1,7 @@ -# 基本用法 +# 自定义组件的基本用法 自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,从而提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法如下: + ```html
@@ -8,8 +9,8 @@
``` +结合if-else使用自定义组件的示例,showComp1为true时显示自定义组件comp1,否则显示comp2: -结合if-else使用自定义组件的示例: ```html @@ -19,17 +20,142 @@
``` +自定义组件的name属性指自定义组件名称(非必填),组件名称对大小写不敏感,默认使用小写。src属性指自定义组件hml文件路径(必填),若没有设置name属性,则默认使用hml文件名作为组件名。 + + +## 自定义事件 + +父组件中绑定自定义子组件的事件使用(on|@)event-name="bindParentVmMethod"语法,子组件中通过this.$emit('eventName', { params: '传递参数' })触发事件并向上传递参数,父组件执行bindParentVmMethod方法并接收子组件传递的参数。 + +> **说明:** +> +> 子组件中使用驼峰命名法命名的事件,在父组件中绑定时需要使用短横线分隔命名形式,例如:\@children-event表示绑定子组件的childrenEvent事件。 + +**示例1:无参数传递** + +子组件comp定义如下: + +```html + +
+ 点击这里查看隐藏文本 + hello world +
+``` + +```css +/* comp.css */ +.item { + width: 700px; + flex-direction: column; + height: 300px; + align-items: center; + margin-top: 100px; +} +.text-style { + font-weight: 500; + font-family: Courier; + font-size: 40px; +} +``` + +```js +// comp.js +export default { + data: { + showObj: false, + }, + childClicked () { + this.$emit('eventType1'); + this.showObj = !this.showObj; + }, +} +``` + +引入子组件comp的父组件示例如下: + +```html + + +
+ +
+``` + +```css +/* xxx.css */ +.container { + background-color: #f8f8ff; + flex: 1; + flex-direction: column; + align-content: center; +} +``` + +```js +// xxx.js +export default { + textClicked () {} +} +``` + +**示例2:有参数传递** + +子组件comp定义如下: + +```html + +
+ 点击这里查看隐藏文本 + hello world +
+``` + +```js +// comp.js +export default { + childClicked () { + this.$emit('eventType1', { text: '收到子组件参数' }); + this.showObj = !this.showObj; + }, +} +``` + +子组件向上传递参数text,父组件接收时通过e.detail来获取该参数: + +```html + + +
+ 父组件:{{text}} + +
+``` + +```js +// xxx.js +export default { + data: { + text: '开始', + }, + textClicked (e) { + this.text = e.detail.text; + }, +} +``` + +![EventParameters](figures/EventParameters.gif) + + +## 自定义组件数据 -- name属性指自定义组件名称(非必填),组件名称对大小写不敏感,默认使用小写。src属性指自定义组件hml文件路径(必填),若没有设置name属性,则默认使用hml文件名作为组件名。 -- 事件绑定:自定义组件中绑定子组件事件使用(on|@)child1语法,子组件中通过this.$emit('child1', { params: '传递参数' })触发事件并进行传值,父组件执行bindParentVmMethod方法并接收子组件传递的参数。 - > **说明:** - > 子组件中使用驼峰命名法命名的事件,在父组件中绑定时需要使用短横线分隔命名形式,例如:\@children-event表示绑定子组件的childrenEvent事件,如 \@children-event="bindParentVmMethod"。 +自定义组件的js文件中可以通过声明data、props、computed等字段完成数据的定义、传递与处理,其中props与computed的具体使用请参考[数据传递与处理](js-components-custom-props.md)章节。 -**表1** 对象 +**表1** 自定义组件数据 -| 属性 | 类型 | 描述 | +| 名称 | 类型 | 描述 | | -------- | --------------- | ---------------------------------------- | -| data | Object/Function | 页面的数据模型,类型是对象或者函数,如果类型是函数,返回值必须是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。
data与private和public不能重合使用。(Rich) | -| props | Array/Object | props用于组件之间的通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。 | -| computed | Object | 计算属性,用于在读取或设置时,进行预先处理,其结果会被缓存。计算属性名不能以$或_开头,不要使用保留字。 | +| data | Object \| Function | 页面的数据模型,类型是对象或者函数,如果类型是函数,返回值必须是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。
data与private和public不能重合使用。 | +| props | Array \| Object | props用于组件之间的数据通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。 | +| computed | Object | 计算属性,用于在读取或设置参数时,进行预先处理,其结果会被缓存。计算属性名不能以$或_开头,不要使用保留字。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-event-parameter.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-event-parameter.md deleted file mode 100644 index f134127293bc49786845f7a2d42cd46a39072426..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-event-parameter.md +++ /dev/null @@ -1,51 +0,0 @@ -# 事件参数 - -子组件也可以通过绑定的事件向上传递参数,在自定义事件上添加传递参数的示例如下: - - -```html - -
- 点击这里查看隐藏文本 - hello world -
-``` - - -```js -// comp.js -export default { - childClicked () { - this.$emit('eventType1', {text: '收到子组件参数'}); - this.showObj = !this.showObj; - }, -} -``` - - -子组件向上传递参数text,父组件接收时通过e.detail来获取参数: - - -```html - - -
- 父组件:{{text}} - -
-``` - - -```js -// xxx.js -export default { - data: { - text: '开始', - }, - textClicked (e) { - this.text = e.detail.text; - }, -} -``` - -![EventParameters](figures/EventParameters.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-events.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-events.md deleted file mode 100644 index 33718f75e5350b02d3c5307093b7519111d71077..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-events.md +++ /dev/null @@ -1,76 +0,0 @@ -# 自定义事件 - -子组件comp定义如下: - - -```html - -
- 点击这里查看隐藏文本 - hello world -
-``` - - -```css -/* comp.css */ -.item { - width: 700px; - flex-direction: column; - height: 300px; - align-items: center; - margin-top: 100px; -} -.text-style { - font-weight: 500; - font-family: Courier; - font-size: 40px; -} -``` - - -```js -// comp.js -export default { - data: { - showObj: false, - }, - childClicked () { - this.$emit('eventType1'); - this.showObj = !this.showObj; - }, -} -``` - - -引入子组件的示例如下: - - -```html - - -
- -
-``` - - -```css -/* xxx.css */ -.container { - background-color: #f8f8ff; - flex: 1; - flex-direction: column; - align-content: center; -} -``` - - -```js -// xxx.js -export default { - textClicked () {}, -} -``` - -其他相关说明详见:[基本用法](./js-components-custom-basic-usage.md)。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-lifecycle.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-lifecycle.md index 40d466372f5fa8a8a9147dbd8d739479a2d6776d..2838eae60518a05eda6e5077893106735b5778cc 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-lifecycle.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-lifecycle.md @@ -1,6 +1,7 @@ # 生命周期定义 > **说明:** +> > 从API Version 5 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 @@ -12,7 +13,7 @@ | onInit | Function | 初始化自定义组件 | 自定义组件初始化生命周期回调,当自定义组件创建时,触发该回调,主要用于自定义组件中必须使用的数据初始化,该回调只会触发一次调用。 | | onAttached | Function | 自定义组件装载 | 自定义组件被创建后,加入到Page组件树时,触发该回调,该回调触发时,表示组件将被进行显示,该生命周期可用于初始化显示相关数据,通常用于加载图片资源、开始执行动画等场景。 | | onLayoutReady | Function | 自定义组件布局完成 | 自定义组件插入Page组件树后,将会对自定义组件进行布局计算,调整其内容元素尺寸与位置,当布局计算结束后触发该回调。 | -| onDetached | Function | 自定义组件摘除 | 自定义组件摘除时,触发该回调,常用于停止动画或异步逻辑停止执行的场景。 | +| onDetached | Function | 自定义组件卸载 | 自定义组件卸载时,触发该回调,常用于停止动画或异步逻辑停止执行的场景。 | | onDestroy | Function | 自定义组件销毁 | 自定义组件销毁时,触发该回调,常用于资源释放。 | | onShow | Function | 自定义组件Page显示 | 自定义组件所在Page显示后,触发该回调。 | | onHide | Function | 自定义组件Page隐藏 | 自定义组件所在Page隐藏后,触发该回调。 | @@ -23,7 +24,7 @@ ```html
- {{value}} + {{ value }}
``` @@ -40,7 +41,7 @@ export default { this.value = "组件挂载" }, onDetached() { - this.value = "" + this.value = "组件卸载" }, onShow() { console.log("Page显示") diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md index 4570de1995858244da4762a31b414eb87789b8ab..a384d0cce0f98cbb715089815d29acc5285db440 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-props.md @@ -1,7 +1,9 @@ -# Props +# 数据传递与处理 -自定义组件可以通过props声明属性,父组件通过设置属性向子组件传递参数,props支持类型包括:String,Number,Boolean,Array,Object,Function。camelCase (驼峰命名法) 的 prop 名,在外部父组件传递参数时需要使用 kebab-case (短横线分隔命名) 形式,即当属性compProp在父组件引用时需要转换为comp-prop。给自定义组件添加props,通过父组件向下传递参数的示例如下: +## Props + +自定义组件可以通过props声明属性,父组件通过设置属性向子组件传递参数,props支持类型包括:String,Number,Boolean,Array,Object,Function。camelCase (驼峰命名法) 的 prop 名,在外部父组件传递参数时需要使用 kebab-case (短横线分隔命名) 形式,即当属性compProp在父组件引用时需要转换为comp-prop。给自定义组件添加props,通过父组件向下传递参数的示例如下: ```html @@ -10,7 +12,6 @@
``` - ```js // comp.js export default { @@ -18,7 +19,6 @@ export default { } ``` - ```html @@ -27,12 +27,11 @@ export default {
``` - > **说明:** +> > 自定义属性命名时禁止以on、@、on:、grab: 等保留关键字为开头。 - -## 添加默认值 +### 添加默认值 子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: @@ -64,8 +63,7 @@ export default {
``` - -## 数据单向性 +### 数据单向性 父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 @@ -84,8 +82,7 @@ export default { } ``` - -## $watch 感知数据改变 +### $watch 感知数据改变 如果需要观察组件中属性变化,可以通过$watch方法增加属性变化回调。使用方法如下: @@ -103,9 +100,9 @@ export default { ``` -## computed 计算属性 +## computed -自定义组件中经常需要在读取或设置某个属性时进行预先处理,提高开发效率,此种情况就需要使用computed字段。computed字段中可通过设置属性的getter和setter方法在属性读写的时候进行触发,使用方式如下: +自定义组件中经常需要在读取或设置某个属性时进行预先处理,提高开发效率,此种情况就需要使用computed计算属性。computed字段中可通过设置属性的getter和setter方法在属性读写的时候进行触发,使用方式如下: ```js // comp.js @@ -137,4 +134,4 @@ export default { } ``` -这里声明的第一个计算属性message默认只有getter函数,message的值会取决于objTitle的值的变化。getter函数只能读取不能改变设值,当需要赋值给计算属性的时候可以提供一个setter函数,如示例中的notice。 +这里声明的第一个计算属性message默认只有getter函数,message的值会取决于objTitle的值的变化。getter函数只能读取不能改变参数值,例如data中初始化定义的time,当需要赋值给计算属性的时候可以提供一个setter函数,如示例中的notice。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md index f52f75e1abffbf7d0c7516b06dcd9757afe73dee..f5bceca1a24068409268c4e600872f24afafcba3 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-slot.md @@ -1,6 +1,7 @@ # slot插槽 > **说明:** +> > 从API Version 7 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 @@ -54,4 +55,5 @@ ``` > **说明:** +> > name 和 slot 属性不支持绑定动态数据。 diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-custom-style.md b/zh-cn/application-dev/reference/arkui-js/js-components-custom-style.md index e17307394e34e23ee1c65349938df6e6a782a9a8..75bcb99c870765c86099d71132db87e198c18357 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-custom-style.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-custom-style.md @@ -1,5 +1,7 @@ # 继承样式 + > **说明:** +> > 从API version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 自定义组件具有inherit-class属性,定义如下: @@ -10,7 +12,8 @@ 可以通过设置inherit-calss属性来继承父组件的样式。 -父页面的hml文件,其中自定义组件comp通过inherit-class属性来指定继承其父组件的样式:parent-class1和parent-class2。 +父组件的hml文件,其中自定义组件comp通过inherit-class属性来指定继承其父组件的样式,即parent-class1和parent-class2: + ```html @@ -20,7 +23,8 @@ ``` -父页面的css文件 +父组件的css文件: + ```css /* xxx.css */ .parent-class1 { @@ -33,7 +37,8 @@ } ``` -自定义组件的hml文件,其中parent-class1和parent-class2是从父组件继承的样式。 +自定义组件的hml文件,其中parent-class1和parent-class2是从父组件继承的样式: + ```html
diff --git a/zh-cn/application-dev/reference/arkui-js/js-components-media-video.md b/zh-cn/application-dev/reference/arkui-js/js-components-media-video.md index 64066963bcd7664ceb0a409403984bf8ead3c203..73090b6498defa2b2ac7b9a27028fae45ec809dd 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-media-video.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-media-video.md @@ -5,15 +5,6 @@ > > - 从API version 4开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > -> - 需要在config.json对应的"abilities"中设置"configChanges"属性为"orientation" -> ``` -> "abilities": [ -> { -> "configChanges": ["orientation"], -> ... -> } -> ] -> ``` 视频播放组件。 diff --git a/zh-cn/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md index 890e8e08f9d68ad387547f9cc37e3d61b334bb45..f6807fbb67924a99dbe3103c5e762587c2fd3b7f 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-js/js-offscreencanvasrenderingcontext2d.md @@ -18,7 +18,7 @@ **示例:** ```html -
+
``` @@ -94,7 +94,7 @@ isPointInPath(path?: Path2D, x: number, y: number): boolean **示例:** ```html -
+
In path:{{textValue}}
@@ -144,7 +144,7 @@ isPointInStroke(path?: Path2D, x: number, y: number): boolean **示例:** ```html -
+
In path:{{textValue}}
@@ -180,7 +180,7 @@ resetTransform(): void **示例:** ```html -
+
In path:{{textValue}}
diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index a18461d4052bad0b0abaad9ab8925115a424b12f..3fa8f6e43b7c1a789255a82c614f3d686cd608e7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -1,5 +1,6 @@ # 基于ArkTS的声明式开发范式 +- [组件导读](ts-components-summary.md) - 组件通用信息 - 通用事件 - [点击事件](ts-universal-events-click.md) @@ -65,6 +66,8 @@ - [LoadingProgress](ts-basic-components-loadingprogress.md) - [Marquee](ts-basic-components-marquee.md) - [Navigation](ts-basic-components-navigation.md) + - [NavRouter](ts-basic-components-navrouter.md) + - [NavDestination](ts-basic-components-navdestination.md) - [PatternLock](ts-basic-components-patternlock.md) - [PluginComponent](ts-basic-components-plugincomponent.md) - [Progress](ts-basic-components-progress.md) @@ -140,8 +143,6 @@ - [OffscreenCanvasRenderingContext2D对象](ts-offscreencanvasrenderingcontext2d.md) - [Path2D对象](ts-components-canvas-path2d.md) - [Lottie](ts-components-canvas-lottie.md) - - - 动画 - [属性动画](ts-animatorproperty.md) - [显式动画](ts-explicit-animation.md) @@ -164,5 +165,4 @@ - [枚举说明](ts-appendix-enums.md) - [类型说明](ts-types.md) - 已停止维护的组件 - - - [GridContainer(栅格)](ts-container-gridcontainer.md) + - [GridContainer(栅格)](ts-container-gridcontainer.md) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.gif deleted file mode 100644 index 391353977d32956cde03890e501d11766dae2648..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.gif and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.png new file mode 100644 index 0000000000000000000000000000000000000000..4248727e91ebbd2ad2dd35211936745a8800f94c Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001169582302.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219864159.gif b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219864159.gif index 557213e5ff5c63c5f3b3db7ffbd56e80eef688f1..badadbdb856c478fdb2ec53f70015b29bb10041f 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219864159.gif and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001219864159.gif differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index 95ea376b2a4dec554b07cc11bcb75c95eff7dbf1..37fd11682e2db8cd265f3ea405fc3f40af8412bb 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -35,14 +35,14 @@ Image(src: string | PixelMap | Resource) | 名称 | 参数类型 | 描述 | | --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | -| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片和网络图片。 | +| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。 | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。
默认值:ImageFit.Cover | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。
默认值:NoRepeat
**说明:**
svg类型图源不支持该属性。 | | interpolation | [ImageInterpolation](#imageinterpolation) | 设置图片的插值效果,即减轻低清晰度图片在放大显示的时候出现的锯齿问题,仅针对图片放大插值。
默认值:ImageInterpolation.None
**说明:**
svg类型图源不支持该属性。
PixelMap资源不支持该属性。 | | renderMode | [ImageRenderMode](#imagerendermode) | 设置图片渲染的模式。
默认值:ImageRenderMode.Original
**说明:**
svg类型图源不支持该属性。 | | sourceSize | {
width: number,
height: number
} | 设置图片裁剪尺寸,将原始图片解码成pixelMap,指定尺寸的图片,单位为px。
**说明:**
PixelMap资源不支持该属性。 | | matchTextDirection | boolean | 设置图片是否跟随系统语言方向,在RTL语言环境下显示镜像翻转显示效果。
默认值:false | -| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:true | +| fitOriginalSize | boolean | 图片组件尺寸未设置时,其显示尺寸是否跟随图源尺寸。
默认值:false | | fillColor | [ResourceColor](ts-types.md#resourcecolor) | 填充颜色。设置的填充颜色会覆盖在图片上。仅对svg图源生效,设置后会替换svg图片的fill颜色。 | | autoResize | boolean | 是否需要在图片解码过程中对图源做resize操作,该操作会根据显示区域的尺寸决定用于绘制的图源尺寸,有利于减少内存占用。
默认值:true | | syncLoad8+ | boolean | 设置是否同步加载图片,默认是异步加载。同步加载时阻塞UI线程,不会显示占位图。
默认值:false | @@ -349,53 +349,3 @@ struct ImageExample3 { ``` ![zh-cn_image_0000001205972610](figures/zh-cn_image_0000001205972610.gif) - -### 渲染沙箱路径图片 - -``` -import fileio from '@ohos.fileio' -import image from '@ohos.multimedia.image' - -const EMPTY_PATH = 'file://' - -@Entry -@Component -struct LoadImageExample { - @State fileContent: string = '' - @State path: string = EMPTY_PATH - @State accountInfoHeadPic: any = '' - - build() { - Column() { - Button('读取沙箱图片') - .margin({ bottom: 10 }) - .onClick(() => { - try { - this.path = EMPTY_PATH - let context = getContext(this) - let path = context.getApplicationContext().filesDir + '/icon.png' - console.log(`读取沙箱图片=========>${path}`) - let fd = fileio.openSync(path, 0o100, 0o666) - console.log(`create file========>${fd}`) - let srcPath = context.bundleCodeDir + '/entry/resource/base/media/icon.png' - fileio.copyFileSync(srcPath, path) - console.log(`error:=============>${e.message}`) - } - }) - Button('读取资源图片') - .margin({ bottom: 10 }) - .onClick(() => { - this.path = EMPTY_PATH; - this.path += getContext(this.bundleCodeDir + '/entry/resource/base/media/icon.png') - }) - Text(`图片路径:${this.path}`) - .fontSize(20) - .margin({ bottom: 10 }) - Image(this.path) - .width(100) - .height(100) - } - .width('100%').height('100%') - } -} -``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md index 9b838578ffc69b47438dd1ae96ec56e90bb7c9dd..6dbad78bfabc1c813c34b6f2e04c3e27803b377f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-imageanimator.md @@ -36,10 +36,10 @@ ImageAnimator() | 参数名称 | 参数类型 | 必填 | 参数描述 | | -------- | -------------- | -------- | -------- | | src | string \| [Resource](ts-types.md#resource)9+ | 是 | 图片路径,图片格式为svg,png和jpg,从API Version9开始支持[Resource](ts-types.md#resource)类型的路径。| -| width | [Length](ts-types.md#length) | 否 | 图片宽度。
默认值:0 | -| height | [Length](ts-types.md#length) | 否 | 图片高度。
默认值:0 | -| top | [Length](ts-types.md#length) | 否 | 图片相对于组件左上角的纵向坐标。
默认值:0 | -| left | [Length](ts-types.md#length) | 否 | 图片相对于组件左上角的横向坐标。
默认值:0 | +| width | number \| string | 否 | 图片宽度。
默认值:0 | +| height | number \| string | 否 | 图片高度。
默认值:0 | +| top | number \| string | 否 | 图片相对于组件左上角的纵向坐标。
默认值:0 | +| left | number \| string | 否 | 图片相对于组件左上角的横向坐标。
默认值:0 | | duration | number | 否 | 每一帧图片的播放时长,单位毫秒。
默认值:0 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md new file mode 100644 index 0000000000000000000000000000000000000000..49669a8f1be61875c2538ee030347e2edb559ea4 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navdestination.md @@ -0,0 +1,27 @@ +# NavDestination + +作为NavRouter组件的子组件,用于显示导航内容区。 + +> **说明:** +> +> 该组件从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +可以包含子组件。 + + +## 接口 + +NavDestination() + + +## 属性 + +仅支持[backgroundColor](ts-universal-attributes-background.md)通用属性。 + +| 名称 | 参数类型 | 描述 | +| -------------- | ---------------------------------------- | ---------------------------------------- | +| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle类型说明) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle类型说明) | 页面标题。 | +| hideTitleBar | boolean | 是否显示标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index 9c21ba142bb83e9a3a8c4443ea8d074dd0041d79..69a4680cbbbc930a8f69485fc2f03ef6342457a6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -1,6 +1,6 @@ # Navigation -Navigation组件一般作为Page页面的根容器,通过属性设置来展示页面的标题、工具栏、菜单。 +Navigation组件一般作为Page页面的根容器,通过属性设置来展示页面的标题栏、工具栏、导航栏等。 > **说明:** > @@ -9,14 +9,13 @@ Navigation组件一般作为Page页面的根容器,通过属性设置来展示 ## 子组件 -可以包含子组件。 +可以包含子组件。从API Version 9开始,推荐与[NavRouter](ts-basic-components-navrouter.md)组件搭配使用。 ## 接口 Navigation() -创建可以根据属性设置,自动展示导航栏、标题、工具栏的组件。 ## 属性 @@ -24,14 +23,20 @@ Navigation() | 名称 | 参数类型 | 描述 | | -------------- | ---------------------------------------- | ---------------------------------------- | -| title | string \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 页面标题。 | -| subTitle | string | 页面副标题。 | +| title | string \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle类型说明)9+ \| [NavigationCustomTitle](#navigationcustomtitle类型说明)9+ | 页面标题。 | +| subTitledeprecated | string | 页面副标题。从API Version 9开始废弃,建议使用title代替。 | | menus | Array<[NavigationMenuItem](#navigationmenuitem类型说明)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 页面右上角菜单。 | | titleMode | [NavigationTitleMode](#navigationtitlemode枚举说明) | 页面标题栏显示模式。
默认值:NavigationTitleMode.Free | | toolBar | [object](#object类型说明) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | 设置工具栏内容。
items: 工具栏所有项。 | -| hideToolBar | boolean | 隐藏工具栏:
默认值:false
true: 隐藏工具栏。
false: 显示工具栏。 | +| hideToolBar | boolean | 隐藏工具栏。
默认值:false
true: 隐藏工具栏。
false: 显示工具栏。 | | hideTitleBar | boolean | 隐藏标题栏。
默认值:false
true: 隐藏标题栏。
false: 显示标题栏。 | | hideBackButton | boolean | 隐藏返回键。
默认值:false
true: 隐藏返回键。
false: 显示返回键。 | +| navBarWidth9+ | [Length](ts-types.md#length) | 导航栏宽度。
默认值:200vp | +| navBarPosition9+ | [NavBarPosition](#navbarposition枚举说明) | 导航栏位置。
默认值:NavBarPosition.Start | +| mode9+ | [NavigationMode](#navigationmode枚举说明) | 导航栏的显示模式。
默认值:NavigationMode.Auto | +| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | 设置导航栏返回图标。 | +| hideNavBar9+ | boolean | 是否显示导航栏(仅在mode为NavigationMode.Split时生效)。 | + ## NavigationMenuItem类型说明 @@ -54,8 +59,45 @@ Navigation() | 名称 | 描述 | | ---- | ---------------------------------------- | | Free | 当内容为可滚动组件时,标题随着内容向上滚动而缩小(子标题的大小不变、淡出)。向下滚动内容到顶时则恢复原样。 | -| Mini | 固定为小标题模式(图标+主副标题)。 | -| Full | 固定为大标题模式(主副标题)。 | +| Mini | 固定为小标题模式。 | +| Full | 固定为大标题模式。 | + +## NavigationCommonTitle类型说明 + +| 名称 | 类型 | 必填 | 描述 | +| ------ | --------- | ---- | -------- | +| main | string | 是 | 设置主标题。 | +| sub | string | 是 | 设置副标题。 | + +## NavigationCustomTitle类型说明 + +| 名称 | 类型 | 必填 | 描述 | +| ------ | ----------------------- | ---- | ------------------------------ | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 设置标题栏内容。 | +| height | [TitleHeight](#titleheight枚举说明) \| [Length](ts-types.md#length) | 是 | 设置标题栏高度。 | + +## NavBarPosition枚举说明 + +| 名称 | 描述 | +| ---- | ---------------------------------------- | +| Start | 双栏显示时,主列在主轴方向首部。 | +| End | 双栏显示时,主列在主轴方向尾部。 | + +## NavigationMode枚举说明 + +| 名称 | 描述 | +| ---- | ---------------------------------------- | +| Stack | 导航栏与内容区独立显示,相当于两个页面。 | +| Split | 导航栏与内容区分两栏显示。 | +| Auto | 窗口宽度>=520vp时,采用Split模式显示;窗口宽度<520vp时,采用Stack模式显示。 | + +## TitleHeight枚举说明 + +| 名称 | 描述 | +| ---- | ---------------------------------------- | +| MainOnly | 只有主标题时标题栏的推荐高度(56vp)。 | +| MainWithSub | 同时有主标题和副标题时标题栏的推荐高度(82vp)。 | + > **说明:** > 目前可滚动组件只支持List。 @@ -66,6 +108,7 @@ Navigation() | 名称 | 功能描述 | | ---------------------------------------- | ---------------------------------------- | | onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | 当titleMode为NavigationTitleMode.Free时,随着可滚动组件的滑动标题栏模式发生变化时触发此回调。 | +| onNavBarStateChange(callback: (isVisible: boolean) => void) | 导航栏显示状态切换时触发该回调。返回值isVisible为true时表示显示,为false时表示隐藏。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md new file mode 100644 index 0000000000000000000000000000000000000000..124c299714c41b97f5239c3d3ad2087b24573ca0 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-navrouter.md @@ -0,0 +1,22 @@ +# NavRouter + +导航组件,默认提供点击响应处理,不需要开发者自定义点击事件逻辑。 + +> **说明:** +> +> 该组件从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 子组件 + +必须包含两个子组件,其中第二个子组件必须为[NavDestination](ts-basic-components-navdestination.md)。 + +## 接口 + +NavRouter() + + +## 事件 + +| 名称 | 功能描述 | +| ---------------------------------------- | ---------------------------------------- | +| onStateChange(callback: (isActivated: boolean) => void) | 组件激活状态切换时触发该回调。返回值isActivated为true时表示激活,为false时表示未激活。
**说明:**用户点击NavRouter,激活NavRouter,加载对应的NavDestination子组件时,回调onStateChange(true);NavRouter对应的NavDestination子组件不再显示时,回调onStateChange(false)。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index c2bdbd8b10ce8588b99e41090ac5c27b34bad87c..96f6ea4e8d5d0d27c45970c2d4c744fa703d5123 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -38,7 +38,8 @@ TimePicker(options?: {selected?: Date}) | ---------------------------------------- | ----------- | | onChange(callback: (value: TimePickerResult ) => void) | 选择时间时触发该事件。 | -### TimePickerResult对象说明 +## TimePickerResult对象说明 + | 名称 | 参数类型 | 描述 | | ------ | ------ | ------- | | hour | number | 选中时间的时。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md index c98b994e927e91c33a8f7d559536941e92bfdc92..c53162cfdc10a7e7a6ff28649469cadbcb56e6f5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -148,35 +148,6 @@ fileAccess(fileAccess: boolean) } ``` -### fileFromUrlAccess9+ - -fileFromUrlAccess(fileFromUrlAccess: boolean) - -设置是否允许通过网页中的JavaScript脚本访问应用文件系统中的内容,默认未启用。[$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md)中rawfile路径的文件不受该属性影响而限制访问。 - -**参数:** - -| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | -| ----------------- | ------- | ---- | ----- | ---------------------------------------- | -| fileFromUrlAccess | boolean | 是 | false | 设置是否允许通过网页中的JavaScript脚本访问应用文件系统中的内容,默认未启用。 | - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - .fileFromUrlAccess(true) - } - } - } - ``` - ### imageAccess imageAccess(imageAccess: boolean) @@ -581,7 +552,7 @@ cacheMode(cacheMode: CacheMode) } ``` -### textZoomRatio +### textZoomRatio9+ textZoomRatio(textZoomRatio: number) @@ -611,6 +582,36 @@ textZoomRatio(textZoomRatio: number) } ``` +### initialScale9+ + +initialScale(percent: number) + +设置整体页面的缩放百分比,默认为100%。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ------------ | ------ | ---- | ---- | --------------- | +| percent | number | 是 | 100 | 要设置的整体页面的缩放百分比。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + @State percent: number = 100 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .initialScale(this.percent) + } + } + } + ``` + ### userAgent userAgent(userAgent: string) @@ -741,7 +742,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) = onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) -刷新或关闭场景下,在即将离开当前页面时触发此回调。刷新当前页面应先通过点击等方式获取焦点,才会触发此回调。 +刷新或关闭场景下,在即将离开当前页面时触发此回调。刷新或关闭当前页面应先通过点击等方式获取焦点,才会触发此回调。 **参数:** @@ -1345,6 +1346,71 @@ onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector } ``` +### onResourceLoad9+ + +onResourceLoad(callback: (event: {url: string}) => void) + +通知Web组件所加载的资源文件url信息。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ---- | ---------------------------------------- | --------- | +| url | string | 所加载的资源文件url信息。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onResourceLoad((event) => { + console.log('onResourceLoad: ' + event.url) + }) + } + } + } + ``` + +### onScaleChange9+ + +onScaleChange(callback: (event: {oldScale: number, newScale: number}) => void) + +当前页面显示比例的变化时触发该回调。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ---- | ---------------------------------------- | --------- | +| oldScale | number | 变化前的显示比例百分比。 | +| newScale | number | 变化后的显示比例百分比。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onScaleChange((event) => { + console.log('onScaleChange changed from ' + event.oldScale + ' to ' + event.newScale) + }) + } + } + } + ``` + ### onUrlLoadIntercept onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) @@ -1793,6 +1859,38 @@ onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocatio } ``` +### onGeolocationHide + +onGeolocationHide(callback: () => void) + +通知用户先前被调用[onGeolocationShow](#ongeolocationshow)时收到地理位置信息获取请求已被取消。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ----------- | ------------------------------- | ---------------- | +| callback | () => void | 地理位置信息获取请求已被取消的回调函数。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller:WebController = new WebController() + build() { + Column() { + Web({ src:'www.example.com', controller:this.controller }) + .geolocationAccess(true) + .onGeolocationHide(() => { + console.log("onGeolocationHide...") + }) + } + } + } + ``` + ### onFullScreenEnter9+ onFullScreenEnter(callback: (event: { handler: FullScreenExitHandler }) => void) @@ -1922,7 +2020,7 @@ onWindowExit(callback: () => void) build() { Column() { Web({ src:'www.example.com', controller: this.controller }) - .onWindowExit((event) => { + .onWindowExit(() => { console.log("onWindowExit...") }) } @@ -1930,6 +2028,41 @@ onWindowExit(callback: () => void) } ``` +### onSearchResultReceive9+ + +onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute + +回调通知调用方网页页内查找的结果。 + +**参数:** + +| 参数名 | 参数类型 | 参数描述 | +| ------------------ | ------------- | ----------------------------------- | +| activeMatchOrdinal | number | 当前匹配的查找项的序号(从0开始)。 | +| numberOfMatches | number | 所有匹配到的关键词的个数。 | +| isDoneCounting | boolean | 当次页内查找操作是否结束。该方法可能会回调多次,直到isDoneCounting为true为止。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onSearchResultReceive(ret => { + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) + }) + } + } + } + ``` + ## ConsoleMessage Web组件获取控制台信息对象。示例代码参考[onConsole事件](#onconsole)。 @@ -3771,6 +3904,113 @@ getUrl(): string } ``` +### searchAllAsync9+ + +searchAllAsync(searchString: string): void + +异步查找网页中所有匹配关键字'searchString'的内容并高亮,结果通过[onSearchResultReceive](#onsearchresultreceive9)异步返回。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ---- | ------ | ---- | ---- | --------------------- | +| searchString | string | 是 | - | 查找的关键字。 | + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + @State searchString: string = "xxx" + + build() { + Column() { + Button('searchString') + .onClick(() => { + this.controller.searchAllAsync(this.searchString) + }) + Button('clearMatches') + .onClick(() => { + this.controller.clearMatches() + }) + Button('searchNext') + .onClick(() => { + this.controller.searchNext(true) + }) + Web({ src: 'www.example.com', controller: this.controller }) + .onSearchResultReceive(ret => { + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) + }) + } + } + } + ``` + +### clearMatches9+ + +clearMatches(): void + +清除所有通过[searchAllAsync](#searchallasync9)匹配到的高亮字符查找结果。 + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Button('clearMatches') + .onClick(() => { + this.controller.clearMatches() + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### searchNext9+ + +searchNext(forward: boolean): void + +滚动到下一个匹配的查找结果并高亮。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ---- | ------ | ---- | ---- | --------------------- | +| forward | boolean | 是 | - | 从前向后或者逆向查找。 | + + +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + + build() { + Column() { + Button('searchNext') + .onClick(() => { + this.controller.searchNext(true) + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + ## HitTestValue9+ 提供点击区域的元素信息。示例代码参考[getHitTestValue](#gethittestvalue9)。 @@ -5028,147 +5268,6 @@ static getOriginUsage(origin : string) : Promise\ } } ``` -### searchAllAsync9+ - -searchAllAsync(searchString: string): void - -异步查找网页中所有匹配关键字'searchString'的内容并高亮,结果通过[onSearchResultReceive](#onsearchresultreceive9)异步返回。 - -**参数:** - -| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | -| ---- | ------ | ---- | ---- | --------------------- | -| searchString | string | 是 | - | 查找的关键字。 | - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - @State searchString: string = "xxx" - - build() { - Column() { - Button('searchString') - .onClick(() => { - this.controller.searchAllAsync(this.searchString) - }) - Button('clearMatches') - .onClick(() => { - this.controller.clearMatches() - }) - Button('searchNext') - .onClick(() => { - this.controller.searchNext(true) - }) - Web({ src: 'www.example.com', controller: this.controller }) - .onSearchResultReceive(ret => { - console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + - "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) - }) - } - } - } - ``` - -### clearMatches9+ - -clearMatches(): void - -清除所有通过[searchAllAsync](#searchallasync9)匹配到的高亮字符查找结果。 - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('clearMatches') - .onClick(() => { - this.controller.clearMatches() - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### searchNext9+ - -searchNext(forward: boolean): void - -滚动到下一个匹配的查找结果并高亮。 - -**参数:** - -| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | -| ---- | ------ | ---- | ---- | --------------------- | -| forward | boolean | 是 | - | 从前向后或者逆向查找。 | - - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('searchNext') - .onClick(() => { - this.controller.searchNext(true) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` - -### onSearchResultReceive9+ - -onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute - -回调通知调用方网页页内查找的结果。 - -**参数:** - -| 参数名 | 参数类型 | 参数描述 | -| ------------------ | ------------- | ----------------------------------- | -| activeMatchOrdinal | number | 当前匹配的查找项的序号(从0开始)。 | -| numberOfMatches | number | 所有匹配到的关键词的个数。 | -| isDoneCounting | boolean | 当次页内查找操作是否结束。该方法可能会回调多次,直到isDoneCounting为true为止。 | - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - .onSearchResultReceive(ret => { - console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + - "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting) - }) - } - } - } - ``` ## WebStorageOrigin9+ @@ -5238,6 +5337,7 @@ onRenderExited接口返回的渲染进程退出的具体原因。 | HttpAnchorImg | 带有超链接的图片,其中超链接的src为http。 | | Img | HTML::img标签。 | | Map | 地理地址。 | +| Phone | 手机电话号码。 | | Unknown | 未知内容。 | ## SslError9+枚举说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md index d52be4b42cf43deaf76502b419e26a36fa63694e..e810ec960e554e29a36275ff78400e3e6da2a499 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md @@ -19,7 +19,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb | -------- | -------- | -------- | -------- | | fingers | number | 否 | 触发拖动的最少手指数,最小为1指, 最大取值为10指。
默认值:1 | | direction | PanDirection | 否 | 触发拖动的手势方向,此枚举值支持逻辑与(&)和逻辑或(\|)运算。
默认值:PanDirection.All | -| distance | number | 否 | 最小拖动识别距离,单位为vp。
默认值:5
**说明:**
> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | +| distance | number | 否 | 最小拖动识别距离,单位为vp。
默认值:5
**说明:**
[Tabs组件](ts-container-tabs.md)滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | ## PanDirection枚举说明 @@ -47,7 +47,7 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance | --------- | ------------ | ---- | ------------------------------------------------------------ | | fingers | number | 否 | 触发滑动的最少手指数,最小为1指, 最大取值为10指。
默认值:1 | | direction | PanDirection | 否 | 设置滑动方向,此枚举值支持逻辑与(&)和逻辑或(\|)运算。
默认值:All | -| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | +| distance | number | 否 | 最小滑动识别距离,单位为vp。
默认值:5.0
**说明:**
> [Tabs组件](ts-container-tabs.md)滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | **接口** diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md index 0bc8ae2307857deca73d21c02c55a1be8f53c17f..8abf78ab1d71dbdb0b6d16b3c427f1f984af61de 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-basic-gestures-tapgesture.md @@ -15,8 +15,8 @@ TapGesture(value?: { count?: number, fingers?: number }) | 参数名称 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| count | number | 否 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。
默认值:1
>  **说明:**
> 如配置多击,上一次抬起和下一次按下的超时时间为300毫秒。 | -| fingers | number | 否 | 触发点击的手指数,最小为1指, 最大为10指。
默认值:1
>  **说明:**
> 1. 当配置多指时,第一根手指按下后300毫秒内未有足够的手指数按下,手势识别失败。
> 2. 实际点击手指数超过配置值,手势识别失败。 | +| count | number | 否 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。
默认值:1
**说明:**
如配置多击,上一次抬起和下一次按下的超时时间为300毫秒。 | +| fingers | number | 否 | 触发点击的手指数,最小为1指, 最大为10指。
默认值:1
**说明:**
1. 当配置多指时,第一根手指按下后300毫秒内未有足够的手指数按下,手势识别失败。
2. 实际点击手指数超过配置值,手势识别失败。 | ## 事件 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index b9efef870d9d5be85079e46c3f4b9c9624652212..66adc3e73e3083a309db834bd5b0db9795e8df4b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -306,9 +306,7 @@ struct CanvasExample { this.context.moveTo(140, 10) this.context.lineTo(140, 160) this.context.stroke() - this.context.font = '18px sans-serif' - this.context.textAlign = 'start' this.context.fillText('textAlign=start', 140, 60) this.context.textAlign = 'end' @@ -351,9 +349,7 @@ struct TextBaseline { this.context.moveTo(0, 120) this.context.lineTo(400, 120) this.context.stroke() - this.context.font = '20px sans-serif' - this.context.textBaseline = 'top' this.context.fillText('Top', 10, 120) this.context.textBaseline = 'bottom' @@ -1749,7 +1745,7 @@ rotate(angle: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.rotate(45 * Math.PI / 180) // Rotate the rectangle 45 degrees + this.context.rotate(45 * Math.PI / 180) this.context.fillRect(70, 20, 50, 50) }) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 191b9ffab8e744a75626d610f1ade17d89d61025..165735247a627b14db1e3f5b33575d59beb61038 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -17,40 +17,41 @@ addColorStop(offset: number, color: string): void **参数:** - | 参数 | 类型 | 必填 | 默认值 | 描述 | - | ------ | ------ | ---- | --------- | ---------------------------- | - | offset | number | 是 | 0 | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 | - | color | string | 是 | '#ffffff' | 设置渐变的颜色。 | +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| ------ | ------ | ---- | --------- | ---------------------------- | +| offset | number | 是 | 0 | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 | +| color | string | 是 | '#ffffff' | 设置渐变的颜色。 | **示例:** ```ts - // xxx.ets - @Entry - @Component - struct Page45 { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) - grad.addColorStop(0.0, 'red') - grad.addColorStop(0.5, 'white') - grad.addColorStop(1.0, 'green') - this.context.fillStyle = grad - this.context.fillRect(0, 0, 500, 500) - }) - } - .width('100%') - .height('100%') - }} +// xxx.ets +@Entry +@Component +struct Page45 { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() => { + var grad = this.context.createLinearGradient(50, 0, 300, 100) + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') + this.context.fillStyle = grad + this.context.fillRect(0, 0, 500, 500) + }) + } + .width('100%') + .height('100%') + } +} ``` ![zh-cn_image_0000001194032516](figures/zh-cn_image_0000001194032516.png) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md new file mode 100644 index 0000000000000000000000000000000000000000..4ddc18329b5ed829cd3258012a3ca3c8befa6157 --- /dev/null +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-summary.md @@ -0,0 +1,290 @@ +# 组件导读 + + +## 行列与分栏 + +- [Column](ts-container-column.md) + + 沿垂直方向布局的容器组件。 +- [ColumnSplit](ts-container-columnsplit.md) + + 垂直方向分隔布局容器组件,将子组件纵向布局,并在每个子组件之间插入一根横向的分割线。 +- [Row](ts-container-row.md) + + 沿水平方向布局的容器组件。 +- [RowSplit](ts-container-rowsplit.md) + + 水平方向分隔布局容器组件,将子组件横向布局,并在每个子组件之间插入一根纵向的分割线。 +- [SideBarContainer](ts-container-sidebarcontainer.md) + + 提供侧边栏可以显示和隐藏的侧边栏容器组件,通过子组件定义侧边栏和内容区,第一个子组件表示侧边栏,第二个子组件表示内容区。 + + +## 堆叠Flex与栅格 + +- [Stack](ts-container-stack.md) + + 堆叠容器组件,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。 +- [Flex](ts-container-flex.md) + + 以弹性方式布局子组件的容器组件。 +- [GridContainer](ts-container-gridcontainer.md) + + 纵向排布栅格布局容器组件,仅在栅格布局场景中使用。 +- [GridRow](ts-container-gridrow.md) + + 栅格容器组件,仅可以和栅格子组件(GridCol)在栅格布局场景中使用。 +- [GridCol](ts-container-gridcol.md) + + 栅格子组件,必须作为栅格容器组件(GridRow)的子组件使用。 +- [RelativeContainer](ts-container-relativecontainer.md) + + 相对布局组件,用于复杂场景中元素对齐的布局。 + + +## 列表与宫格 + +- [List](ts-container-list.md) + + 列表包含一系列相同宽度的列表项,适合连续、多行呈现同类数据,例如图片和文本。 +- [ListItem](ts-container-listitem.md) + + 用来展示具体列表项,必须配合List来使用。 +- [ListItemGroup](ts-container-listitemgroup.md) + + 用来展示分组列表项的组件,必须配合List组件来使用。 +- [Grid](ts-container-grid.md) + + 网格容器组件,由“行”和“列”分割的单元格所组成,通过指定“项目”所在的单元格做出各种各样的布局。 +- [GridItem](ts-container-griditem.md) + + 网格容器中单项内容容器。 + + +## 滚动与滑动 + +- [Scroll](ts-container-scroll.md) + + 可滚动的容器组件,当子组件的布局尺寸超过父组件的尺寸时,内容可以滚动。 +- [Swiper](ts-container-swiper.md) + + 滑块视图容器组件,提供子组件滑动轮播显示的能力。 +- [WaterFlow](ts-container-waterflow.md) + + 瀑布流容器组件,由“行”和“列”分割的单元格所组成,通过容器自身的排列规则,将不同大小的“项目”自上而下,如瀑布般紧密布局。 +- [FlowItem](ts-container-flowitem.md) + + 瀑布流组件WaterFlow的子组件,用来展示瀑布流具体item。 + + +## 导航 + +- [Navigator](ts-container-navigator.md) + + 路由容器组件,提供路由跳转能力。 +- [Navigation](ts-basic-components-navigation.md) + + 一般作为Page页面的根容器,通过属性设置来展示页面的标题栏、工具栏、导航栏等。 +- [NavRouter](ts-basic-components-navrouter.md) + + 导航组件,默认提供点击响应处理,不需要开发者自定义点击事件逻辑。 +- [NavDestination](ts-basic-components-navdestination.md) + + 作为NavRouter组件的子组件,用于显示导航内容区。 +- [Stepper](ts-basic-components-stepper.md) + + 步骤导航器组件,适用于引导用户按照步骤完成任务的导航场景。 +- [StepperItem](ts-basic-components-stepperitem.md) + + Stepper组件的子组件。 +- [Tabs](ts-container-tabs.md) + + 通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图。 +- [TabContent](ts-container-tabcontent.md) + + 仅在Tabs组件中使用,对应一个切换页签的内容视图。 + + +## 按钮与选择 + +- [Button](ts-basic-components-button.md) + + 按钮组件,可快速创建不同样式的按钮。 +- [Toggle](ts-basic-components-toggle.md) + + 组件提供勾选框样式、状态按钮样式及开关样式。 +- [Checkbox](ts-basic-components-checkbox.md) + + 提供多选框组件,通常用于某选项的打开或关闭。 +- [CheckboxGroup](ts-basic-components-checkboxgroup.md) + + 多选框群组,用于控制多选框全选或者不全选状态。 +- [DatePicker](ts-basic-components-datepicker.md) + + 选择日期的滑动选择器组件。 +- [TextPicker](ts-basic-components-textpicker.md) + + 滑动选择文本内容的组件。 +- [TimePicker](ts-basic-components-timepicker.md) + + 滑动选择时间的组件。 +- [Radio](ts-basic-components-radio.md) + + 单选框,提供相应的用户交互选择项。 +- [Rating](ts-basic-components-rating.md) + + 提供在给定范围内选择评分的组件。 +- [Select](ts-basic-components-select.md) + + 提供下拉选择菜单,可以让用户在多个选项之间选择。 +- [Slider](ts-basic-components-slider.md) + + 滑动条组件,通常用于快速调节设置值,如音量调节、亮度调节等应用场景。 +- [Counter](ts-container-counter.md) + + 计数器组件,提供相应的增加或者减少的计数操作。 + + +## 文本与输入 + +- [Text](ts-basic-components-text.md) + + 显示一段文本的组件。 +- [Span](ts-basic-components-span.md) + + 作为Text组件的子组件,用于显示行内文本片段的组件。 +- [Search](ts-basic-components-search.md) + + 搜索框组件,适用于浏览器的搜索内容输入框等应用场景。 +- [TextArea](ts-basic-components-textarea.md) + + 多行文本输入框组件,当输入的文本内容超过组件宽度时会自动换行显示。 +- [TextInput](ts-basic-components-textinput.md) + + 单行文本输入框组件。 +- [PatternLock](ts-basic-components-patternlock.md) + + 图案密码锁组件,以九宫格图案的方式输入密码,用于密码验证场景。手指在PatternLock组件区域按下时开始进入输入状态,手指离开屏幕时结束输入状态完成密码输入。 +- [RichText](ts-basic-components-richtext.md) + + 富文本组件,解析并显示HTML格式文本。 + + +## 图片视频与媒体 + +- [Image](ts-basic-components-image.md) + + 图片组件,支持本地图片和网络图片的渲染展示。 +- [ImageAnimator](ts-basic-components-imageanimator.md) + + 提供逐帧播放图片能力的帧动画组件,可以配置需要播放的图片列表,每张图片可以配置时长。 +- [Video](ts-media-components-video.md) + + 用于播放视频文件并控制其播放状态的组件。 +- [PluginComponent](ts-basic-components-plugincomponent.md) + + 提供外部应用组件嵌入式显示功能,即外部应用提供的UI可在本应用内显示。 +- [XComponent](ts-basic-components-xcomponent.md) + + 用于EGL/OpenGLES和媒体数据写入。 + + +## 信息展示 + +- [DataPanel](ts-basic-components-datapanel.md) + + 数据面板组件,用于将多个数据占比情况使用占比图进行展示。 +- [Gauge](ts-basic-components-gauge.md) + + 数据量规图表组件,用于将数据展示为环形图表。 +- [LoadingProgress](ts-basic-components-loadingprogress.md) + + 用于显示加载动效的组件。 +- [Marquee](ts-basic-components-marquee.md) + + 跑马灯组件,用于滚动展示一段单行文本,仅当文本内容宽度超过跑马灯组件宽度时滚动。 +- [Progress](ts-basic-components-progress.md) + + 进度条组件,用于显示内容加载或操作处理等进度。 +- [QRCode](ts-basic-components-qrcode.md) + + 用于显示单个二维码的组件。 +- [TextClock](ts-basic-components-textclock.md) + + 通过文本将当前系统时间显示在设备上。支持不同时区的时间显示,最高精度到秒级。 +- [TextTimer](ts-basic-components-texttimer.md) + + 通过文本显示计时信息并控制其计时器状态的组件。 + + +## 空白与分隔 + +- [Blank](ts-basic-components-blank.md) + + 空白填充组件,在容器主轴方向上,空白填充组件具有自动填充容器空余部分的能力。仅当父组件为Row/Column时生效。 +- [Divider](ts-basic-components-divider.md) + + 分隔器组件,分隔不同内容块/内容元素。 + + +## 画布与图形绘制 + +- [Canvas](ts-components-canvas-canvas.md) + + 提供画布组件,用于自定义绘制图形。 +- [Circle](ts-drawing-components-circle.md) + + 用于绘制圆形的组件。 +- [Ellipse](ts-drawing-components-ellipse.md) + + 椭圆绘制组件。 +- [Line](ts-drawing-components-line.md) + + 直线绘制组件。 +- [Polyline](ts-drawing-components-polyline.md) + + 折线绘制组件。 +- [Polygon](ts-drawing-components-polygon.md) + + 多边形绘制组件。 +- [Path](ts-drawing-components-path.md) + + 路径绘制组件,根据绘制路径生成封闭的自定义形状。 +- [Rect](ts-drawing-components-rect.md) + + 矩形绘制组件。 +- [Shape](ts-drawing-components-shape.md) + + 作为绘制组件的父组件,实现类似SVG的效果,父组件中会描述所有绘制组件均支持的通用属性。 + + +## 网络 + +- [Web](ts-basic-components-web.md) + + 提供具有网页显示能力的Web组件。 + + +## 其他 + +- [ScrollBar](ts-basic-components-scrollbar.md) + + 滚动条组件,用于配合可滚动组件使用,如List、Grid、Scroll等。 +- [Badge](ts-container-badge.md) + + 可以附加在单个组件上用于信息标记的容器组件。 +- [AlphabetIndexer](ts-container-alphabet-indexer.md) + + 可以与容器组件联动用于按逻辑结构快速定位容器显示区域的索引条组件。 +- [Panel](ts-container-panel.md) + + 可滑动面板,提供一种轻量的内容展示窗口,方便在不同尺寸中切换。 +- [Refresh](ts-container-refresh.md) + + 可以进行页面下拉操作并显示刷新动效的容器组件。 +- [AbilityComponent](ts-container-ability-component.md) + + 独立显示Ability的容器组件。 +- [RemoteWindow](ts-basic-components-remotewindow.md) + + 远程控制窗口组件,可以通过此组件控制应用窗口,提供启动退出过程中控件动画和应用窗口联动动画的能力。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md index 6b34c3cee54a5b1d6094505abe506a6b9e2bc00b..0e4a307c4f856cf2d330051642853dd1d94c285b 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-column.md @@ -20,7 +20,7 @@ Column(value?: {space?: string | number}) | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| space | string \| number | 否 | 纵向布局元素垂直方向间距。
默认值:0 | +| space | string \| number | 否 | 纵向布局元素垂直方向间距。
从API version 9开始,space为负数时不生效。
默认值:0 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md index f73274dd13e4b481a00842e4cdf50015d7adc74d..2083ff7d49c7296f09a434ac0d805a775f5530d7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridcol.md @@ -15,11 +15,11 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------- | ---- | ------------------------------------------------------------ | -| span | number \| GridColColumnOption | 否 | 占用列数。span为0表示该元素不参与布局计算,即不会被渲染。
默认值:1。 | -| offset | number \| GridColColumnOption | 否 | 相对于前一个栅格子组件偏移的列数。
默认值:0。 | -| order | number \| GridColColumnOption | 否 | 元素的序号,根据栅格子组件的序号,从小到大对栅格子组件做排序。
默认值:0。 | +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| span | number \| [GridColColumnOption](#gridcolcolumnoption) | 否 | 占用列数。span为0表示该元素不参与布局计算,即不会被渲染。
默认值:1。 | +| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | 否 | 相对于前一个栅格子组件偏移的列数。
默认值:0。 | +| order | number \| [GridColColumnOption](#gridcolcolumnoption) | 否 | 元素的序号,根据栅格子组件的序号,从小到大对栅格子组件做排序。
默认值:0。 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md index c67914d7f0af03f543fc272e3b187cc8df3683d8..75e927bf604194c4d19b99c2a291b8cd94c1876d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-gridrow.md @@ -133,17 +133,18 @@ onBreakpointChange(callback: (breakpoints: string) => void) struct GridRowExample { @State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown] @State currentBp: string = 'unknown' + build() { Column() { GridRow({ columns: 5, - gutter: {x:5, y:10}, - breakpoints: {value:["400vp", "600vp", "800vp"], - reference: BreakpointsReference.WindowSize}, + gutter: { x: 5, y: 10 }, + breakpoints: { value: ["400vp", "600vp", "800vp"], + reference: BreakpointsReference.WindowSize }, direction: GridRowDirection.Row }) { - ForEach(this.bgColors, (color)=>{ - GridCol({ span: {xs:1, sm:2, md:3, lg:4}}) { + ForEach(this.bgColors, (color) => { + GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { Row().width("100%").height("20vp") }.borderColor(color).borderWidth(2) }) @@ -151,8 +152,8 @@ struct GridRowExample { .onBreakpointChange((breakpoint) => { this.currentBp = breakpoint }) - }.width('80%').margin({ left: 10,top: 5, bottom:5 }).height(200) - .border({color:Color.Blue, width:2}) + }.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200) + .border({ color: '#880606', width: 2 }) } } ``` diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md index 281dbaeca112580429e30278772597160d41a568..0f36cfe25611d736164106ad72b19df528e1d555 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -22,12 +22,13 @@ ListItem(value?: string) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| sticky | [Sticky](#sticky枚举说明) | 设置ListItem吸顶效果。
默认值:Sticky.None | +| sticky(deprecated) | [Sticky](#stickydeprecated枚举说明) | 设置ListItem吸顶效果。
默认值:Sticky.None
从API version9开始废弃,推荐使用[List组件sticky属性](ts-container-list.md#属性)。 | | editable | boolean \| [EditMode](#editmode枚举说明) | 当前ListItem元素是否可编辑,进入编辑模式后可删除或移动列表项。
默认值:false | | selectable8+ | boolean | 当前ListItem元素是否可以被鼠标框选。
**说明:**
外层List容器的鼠标框选开启时,ListItem的框选才生效。
默认值:true | | swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9枚举说明),
} | 用于设置ListItem的划出组件。
- start: ListItem向右划动时item左边的组件(List垂直布局时)或ListItem向下划动时item上方的组件(List水平布局时)。
- end: ListItem向左划动时item右边的组件(List垂直布局时)或ListItem向上划动时item下方的组件(List水平布局时)。
- edgeEffect: 滑动效果。
| -## Sticky枚举说明 +## Sticky(deprecated)枚举说明 +从API version9开始废弃,推荐使用[List组件stickyStyle枚举](ts-container-list.md#stickystyle9枚举说明)。 | 名称 | 描述 | | -------- | -------- | | None | 无吸顶效果。 | @@ -63,35 +64,18 @@ ListItem(value?: string) @Component struct ListItemExample { private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - @State editFlag: boolean = false build() { Column() { List({ space: 20, initialIndex: 0 }) { - ListItem() { - Text('sticky:Normal , click me edit list') - .width('100%').height(40).fontSize(12).fontColor(0xFFFFFF) - .textAlign(TextAlign.Center).backgroundColor(0x696969) - .onClick(() => { - this.editFlag = !this.editFlag - }) - }.sticky(Sticky.Normal) - ForEach(this.arr, (item) => { ListItem() { Text('' + item) .width('100%').height(100).fontSize(16) .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) - }.editable(this.editFlag) + } }, item => item) - } - .editMode(true) - .onItemDelete((index: number) => { - console.info(this.arr[index - 1] + 'Delete') - this.arr.splice(index - 1,1) - this.editFlag = false - return true - }).width('90%') + }.width('90%') }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md index a5c39cd63bb5a4d76bf939a4748781b1187ebace..2cce7da6c3f8fc6db03069205acff62a4ad92c51 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-navigator.md @@ -78,7 +78,7 @@ import router from '@ohos.router' @Component struct DetailExample { // 接收Navigator.ets的传参 - @State text: any = router.getParams().text + @State text: any = router.getParams()['text'] build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md index ba536c338ffb88ce73f1a0619d722f8b1c2743c0..f9039ed0b31460923fc72a386ac31dab47ac6eba 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-row.md @@ -20,7 +20,7 @@ Row(value?:{space?: number | string }) | 参数名 | 参数类型 | 必填 | 参数描述 | | -------- | -------- | -------- | -------- | -| space | string \| number | 否 | 横向布局元素间距。
默认值:0,单位vp | +| space | string \| number | 否 | 横向布局元素间距。
从API version 9开始,space为负数时不生效。
默认值:0,单位vp | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md index 305facc51a69b54fe0fe82e8e5b37d1f55a9abe4..4afb957f54b269836a33bbebba12473ce1811ba0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -245,8 +245,11 @@ struct NestedScroll { Text("Scroll Area") .width("100%").height("40%").backgroundColor(0X330000FF) .fontSize(16).textAlign(TextAlign.Center) + .onClick(() => { + this.scroller.scrollToIndex(5) + }) - List({ space: 20 }) { + List({ space: 20, scroller: this.scroller }) { ForEach(this.arr, (item) => { ListItem() { Text("ListItem" + item) @@ -255,7 +258,9 @@ struct NestedScroll { }.width("100%").height(100) }, item => item) } - .width("100%").height("50%").edgeEffect(EdgeEffect.None) + .width("100%") + .height("50%") + .edgeEffect(EdgeEffect.None) .onReachStart(() => { this.listPosition = 0 }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md index b9d2e3f3300160393745c24a49bc8b3ac82b479b..5ac4e16276a39de5b64b2e1a558413162ca40671 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -52,14 +52,6 @@ Swiper(controller?: SwiperController) | Stretch | Swiper滑动一页的宽度为Swiper组件自身的宽度。| | AutoLinear | Swiper滑动一页的宽度为子组件宽度中的最大值。| -## EdgeEffect枚举说明 - -| 名称 | 描述 | -| ------ | ------------------------------------------------------------------------- | -| Spring | 弹性物理动效,滑动到边缘后可以通过触摸事件继续滑动一段距离,松手后回弹。 | -| Fade | 滑动到边缘后,可以通过触摸事件继续滑动一段阴影,松手后阴影回弹。 | -| None | 滑动到边缘后无效果。 | - ## SwiperController Swiper容器组件的控制器,可以将此对象绑定至Swiper组件,然后通过它控制翻页。 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md index 425b58cef2a90d2c7089d5ce332e1ed77e5d3153..388a78aad718f534728d8ade84fb8e0fdf9434a9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-waterflow.md @@ -22,10 +22,10 @@ WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller}) **参数:** - | 参数名 | 参数类型 | 必填 | 参数描述 | - | ---------- | ----------------------------------------------- | ------ | -------------------------------------------- | - | footer | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 设置WaterFlow尾部组件。 | - | scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。
目前瀑布流仅支持Scroller组件的scrollToIndex接口。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| ---------- | ----------------------------------------------- | ------ | -------------------------------------------- | +| footer | [CustomBuilder](ts-types.md#custombuilder8) | 否 | 设置WaterFlow尾部组件。 | +| scroller | [Scroller](ts-container-scroll.md#scroller) | 否 | 可滚动组件的控制器,与可滚动组件绑定。
目前瀑布流仅支持Scroller组件的scrollToIndex接口。 | ## 属性 @@ -259,8 +259,8 @@ struct WaterflowDemo { .objectFit(ImageFit.Fill) } } - .width(this.itemWidthtArray[item1]) - .height(this.itemHeightArray[item1]) + .width(this.itemWidthArray[item]) + .height(this.itemHeightArray[item]) .backgroundColor(this.colors[item % 5]) }, item => item) } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md index 1d790cb18e416d3369d63c4d07e7513972c67a81..e22cce09553a92a516fc3ffc7fd2c182000fbf1f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-circle.md @@ -16,29 +16,30 @@ Circle(options?: {width?: string | number, height?: string | number}) -- 参数 - | 参数名 | 参数类型 | 必填 | 参数描述 | - | -------- | -------- | -------- | -------- | - | width | string \| number | 否 | 宽度。
默认值:0 | - | height | string \| number | 否 | 高度。
默认值:0 | +**参数:** + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| width | string \| number | 否 | 宽度。
默认值:0 | +| height | string \| number | 否 | 高度。
默认值:0 | ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | 否 | 设置填充区域颜色。
默认值:Color.Black | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 否 | 设置填充区域透明度。
默认值:1 | -| stroke | [ResourceColor](ts-types.md) | 否 | 设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | 否 | 设置边框间隙。
默认值:[] | -| strokeDashOffset | number \| string | 否 | 边框绘制起点的偏移量。
默认值:0 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 否 | 设置边框端点绘制样式。
默认值:LineCapStyle.Butt | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | 否 | 设置边框拐角绘制样式。
默认值:LineJoinStyle.Miter | -| strokeMiterLimit | number \| string | 否 | 设置锐角绘制成斜角的极限值。
默认值:4 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 否 | 设置边框透明度。
默认值:1 | -| strokeWidth | Length | 否 | 设置边框宽度。
默认值:1 | -| antiAlias | boolean | 否 | 是否开启抗锯齿效果。
默认值:true | +| 名称 | 类型 | 描述 | +| -------- | -------- | -------- | +| fill | [ResourceColor](ts-types.md) | 设置填充区域颜色。
默认值:Color.Black | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置填充区域透明度。
默认值:1 | +| stroke | [ResourceColor](ts-types.md) | 设置边框颜色,不设置时,默认没有边框。 | +| strokeDashArray | Array<Length> | 设置边框间隙。
默认值:[] | +| strokeDashOffset | number \| string | 边框绘制起点的偏移量。
默认值:0 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | 设置边框端点绘制样式。
默认值:LineCapStyle.Butt | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | 设置边框拐角绘制样式。
默认值:LineJoinStyle.Miter | +| strokeMiterLimit | number \| string | 设置锐角绘制成斜角的极限值。
默认值:4
**说明:**
Circle组件无法设置锐角图形,该属性设置无效。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 设置边框透明度。
默认值:1 | +| strokeWidth | Length | 设置边框宽度。
默认值:1 | +| antiAlias | boolean | 是否开启抗锯齿效果。
默认值:true | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md index bedfc7713757b2291914cab626aa27af1501923f..090fb561e60a7cdcf8dd5b79bdcbea8bb7c8a1d9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-ellipse.md @@ -14,7 +14,7 @@ ## 接口 -ellipse(options?: {width?: string | number, height?: string | number}) +Ellipse(options?: {width?: string | number, height?: string | number}) **参数:** @@ -27,19 +27,19 @@ ellipse(options?: {width?: string | number, height?: string | number}) 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 |设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置边框透明度。 | -| strokeWidth | Length | 1 | 否 | 设置边框宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - |设置边框颜色,不设置时,默认没有边框。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。 | +| strokeWidth | Length | 1 | 设置边框宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md index 8c5b3995696b5a85498a5b7f4dd5a49012493832..6487fe0fa436e686a9f093c158f49d46933e68a7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-line.md @@ -34,21 +34,21 @@ Line(value?: {width?: string | number, height?: string | number}) 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| startPoint | Array<Length> | [0, 0] | 否 | 直线起点坐标点(相对坐标),单位vp。 | -| endPoint | Array<Length> | [0, 0] | 否 | 直线终点坐标点(相对坐标),单位vp。 | -| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 否 | 设置线条颜色。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置线条透明度。 | -| strokeWidth | Length | 1 | 否 | 设置线条宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| startPoint | Array<Length> | [0, 0] | 直线起点坐标点(相对坐标),单位vp。 | +| endPoint | Array<Length> | [0, 0] | 直线终点坐标点(相对坐标),单位vp。 | +| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 设置填充区域颜色。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。
**说明:**
Line组件无法形成闭合区域,该属性设置无效。 | +| stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | 设置线条颜色。 | +| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。
**说明:**
Line组件无法设置锐角图形,该属性设置无效。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。 | +| strokeWidth | Length | 1 | 设置线条宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md index fbf5860c2bc5b6fc98d7bb9a8c113e3c247aacc9..097259b858a7a7c3be9fab7c87c6450cd128e63f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-path.md @@ -27,20 +27,20 @@ Path(value?: { width?: number | string; height?: number | string; commands?: str 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | ----------------------------------- | ---- | ---- | ---------------------------------------- | -| commands | string | '' | 否 | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](ts-pixel-units.md)。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 | 设置线条颜色。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置线条透明度。 | -| strokeWidth | Length | 1 | 否 | 设置线条宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| commands | string | '' | 路径绘制的命令字符串,单位为px。像素单位转换方法请参考[像素单位转换](ts-pixel-units.md)。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置线条颜色。 | +| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。 | +| strokeWidth | Length | 1 | 设置线条宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | commands支持的绘制命令如下: diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md index eefd1d43c4fc7e487001ed1c1945591f5a38f0fc..d573d7a8b0a22e6dffdc0c6b785455ca6f3ebf00 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md @@ -28,20 +28,20 @@ Polygon(value?: {width?: string | number, height?: string | number}) 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | 否 | 多边形的顶点坐标列表。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置边框透明度。 | -| strokeWidth | Length | 1 | 否 | 设置边框宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| points | Array<Point> | [] | 多边形的顶点坐标列表。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。 | +| strokeWidth | Length | 1 | 设置边框宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | ## Point diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md index 8042a9947528a5f0e70761fb56a9df721a8a688c..a592609717b8bbd07c2eff7524b369a308dc0a0d 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md @@ -28,20 +28,20 @@ Polyline(value?: {width?: string | number, height?: string | number}) 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | 否 | 折线经过坐标点列表。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 | 设置线条颜色。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置线条间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 线条绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置线条端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置线条拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置线条透明度。 | -| strokeWidth | Length | 1 | 否 | 设置线条宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| points | Array<Point> | [] | 折线经过坐标点列表。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置线条颜色。 | +| strokeDashArray | Array<Length> | [] | 设置线条间隙。 | +| strokeDashOffset | number \| string | 0 | 线条绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置线条端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置线条拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置线条透明度。 | +| strokeWidth | Length | 1 | 设置线条宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | ## Point diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index 9ea5950c76a29569a4352278022675b9d4235e67..7ef5471abf93317154a1b385e5ce36b83744a1d9 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -32,22 +32,22 @@ Rect(value?: {width?: string | number,height?: string | number,radius?: string | 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| radiusWidth | string \| number | 0 | 否 | 圆角的宽度,仅设置宽时宽高一致。 | -| radiusHeight | string \| number | 0 | 否 | 圆角的高度,仅设置高时宽高一致。 | -| radius | string \| number \| Array<string \| number> | 0 | 否 | 圆角半径大小。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 | 设置边框颜色,不设置时,默认没有边框。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置边框透明度。 | -| strokeWidth | Length | 1 | 否 | 设置边框宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| radiusWidth | string \| number | 0 | 圆角的宽度,仅设置宽时宽高一致。 | +| radiusHeight | string \| number | 0 | 圆角的高度,仅设置高时宽高一致。 | +| radius | string \| number \| Array<string \| number> | 0 | 圆角半径大小。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。 | +| strokeWidth | Length | 1 | 设置边框宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index 365f1333b677c98e55b5323b45cb20c2daa6ebde..b3f695718de89fe04b96d7074ed21839b0eccd44 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -21,31 +21,32 @@ Shape(value?: PixelMap) -- 参数 - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------- | -------- | -------- | -------- | -------- | - | value | [PixelMap](../apis/js-apis-image.md#pixelmap7) | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 | +**参数:** + +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| -------- | -------- | -------- | -------- | -------- | +| value | [PixelMap](../apis/js-apis-image.md#pixelmap7) | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 | ## 属性 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: -| 参数名称 | 参数类型 | 默认值 | 必填 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | 否 | 形状的视口。 | -| fill | [ResourceColor](ts-types.md) | Color.Black | 否 | 设置填充区域颜色。 | -| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置填充区域透明度。 | -| stroke | [ResourceColor](ts-types.md) | - | 否 | 设置边框颜色,不设置时,默认没有边框线条。 | -| strokeDashArray | Array<Length> | [] | 否 | 设置边框间隙。 | -| strokeDashOffset | number \| string | 0 | 否 | 边框绘制起点的偏移量。 | -| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 否 | 设置边框端点绘制样式。 | -| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 否 | 设置边框拐角绘制样式。 | -| strokeMiterLimit | number \| string | 4 | 否 | 设置锐角绘制成斜角的极限值。 | -| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 否 | 设置边框透明度。 | -| strokeWidth | number \| string | 1 | 否 | 设置边框宽度。 | -| antiAlias | boolean | true | 否 | 是否开启抗锯齿效果。 | -| mesh8+ | Array<number>,number,number | [],0,0 | 否 | 设置mesh效果。第一个参数为长度(column + 1)* (row + 1)* 2的数组,它记录了扭曲后的位图各个顶点位置,第二个参数为mesh矩阵列数column,第三个参数为mesh矩阵行数row。 | +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| viewPort | {
x?: number \| string,
y?: number \| string,
width?: number \| string,
height?: number \| string
} | { x:0, y:0, width:0, height:0 } | 形状的视口。 | +| fill | [ResourceColor](ts-types.md) | Color.Black | 设置填充区域颜色。 | +| fillOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置填充区域透明度。 | +| stroke | [ResourceColor](ts-types.md) | - | 设置边框颜色,不设置时,默认没有边框线条。 | +| strokeDashArray | Array<Length> | [] | 设置边框间隙。 | +| strokeDashOffset | number \| string | 0 | 边框绘制起点的偏移量。 | +| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | 设置边框端点绘制样式。 | +| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | 设置边框拐角绘制样式。 | +| strokeMiterLimit | number \| string | 4 | 设置锐角绘制成斜角的极限值。 | +| strokeOpacity | number \| string \| [Resource](ts-types.md#resource类型) | 1 | 设置边框透明度。 | +| strokeWidth | number \| string | 1 | 设置边框宽度。 | +| antiAlias | boolean | true | 是否开启抗锯齿效果。 | +| mesh8+ | Array<number>,number,number | [],0,0 | 设置mesh效果。第一个参数为长度(column + 1)* (row + 1)* 2的数组,它记录了扭曲后的位图各个顶点位置,第二个参数为mesh矩阵列数column,第三个参数为mesh矩阵行数row。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md index d31658612f6d098d7bac990af1899929c541aed6..820834e1daac886c0781895b1b73c89200da08e5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -40,10 +40,11 @@ 组件通过手势事件绑定不同GestureType的手势对象,各手势对象在响应手势操作的事件回调中提供手势相关信息。下面通过TapGesture手势对象的onAction事件响应点击事件,获取事件相关信息。其余手势对象的事件定义见各个手势对象章节。 若需绑定多种手势请使用 [组合手势](ts-combined-gestures.md)。 -- TapGesture事件说明 - | 名称 | 功能描述 | - | -------- | -------- | - | onAction((event?:GestureEvent) => void) | Tap手势识别成功回调。 | +**TapGesture事件说明** + +| 名称 | 功能描述 | +| -------- | -------- | +| onAction((event?:GestureEvent) => void) | Tap手势识别成功回调。 | ## GestureEvent对象说明 | 名称 | 类型 | 描述 | @@ -60,6 +61,10 @@ | timestamp8+ | number | 事件时间戳。 | | target8+ | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 触发手势事件的元素对象显示区域。 | | source8+ | [SourceType](#sourcetype枚举说明) | 事件输入设备。 | +| pressure9+ | number | 按压的压力大小。 | +| tiltX9+ | number | 手写笔在设备平面上的投影与设备平面X轴的夹角。 | +| tiltY9+ | number | 手写笔在设备平面上的投影与设备平面Y轴的夹角。 | +| sourceTool9+ | [SourceTool](#sourcetool枚举说明) | 事件输入源。 | ## SourceType枚举说明 | 名称 | 描述 | @@ -77,6 +82,13 @@ | localX | number | 相对于当前组件元素左上角的x轴坐标。 | | localY | number | 相对于当前组件元素左上角的y轴坐标。 | +## SourceTool枚举说明 +| 名称 | 描述 | +| -------- | -------- | +| Unknown | 未知输入源。 | +| Finger | 手指输入。 | +| Pen | 手写笔输入。 | + ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index eefeda849adbbaa2e4d9333f31da124de59ce010..8036320cf4dcd4d0db51338505eb181225b1d55a 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -17,8 +17,8 @@ show(value: { title: string | Resource, message: string  | 参数名 | 参数类型 | 必填 | 参数描述 | | ---------- | -------------------------- | ------- | ----------------------------- | -| title | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗标题。 | -| message | [ResourceStr](ts-types.md#resourcestr) | 是 | 弹窗内容。 | +| title | [Resource](ts-types.md#resource) \| string | 是 | 弹窗标题。 | +| message | [Resource](ts-types.md#resource) \| string | 是 | 弹窗内容。 | | autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。
默认值:true | | confirm | {
value: [ResourceStr](ts-types.md#resourcestr),
action: () => void
} | 否 | 确认按钮的文本内容和点击回调。
默认值:
value:按钮文本内容。
action: 按钮选中时的回调。 | | cancel | () => void | 否 | 点击遮障层关闭dialog时的回调。 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 7330ab11ee2cca5e1c9ba87f81952b0fd4cae3f3..50d072a9a221958dc2a7b21aa4608c913bc004fd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -13,17 +13,17 @@ show(options?: DatePickerDialogOptions) 定义日期滑动选择器弹窗并弹出。 -- DatePickerDialogOptions参数说明 +**DatePickerDialogOptions参数:** - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | -------- | -------- | -------- | -------- | -------- | - | start | Date | 否 | Date('1970-1-1') | 设置选择器的起始日期。 | - | end | Date | 否 | Date('2100-12-31') | 设置选择器的结束日期。 | - | selected | Date | 否 | 当前系统日期 | 设置当前选中的日期。 | - | lunar | boolean | 否 | false | 日期是否显示为农历。 |确定 - | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 点击弹窗中的“确定”按钮时触发该回调。 | - | onCancel | () => void | 否 | - | 点击弹窗中的“取消”按钮时触发该回调。 | - | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| -------- | -------- | -------- | -------- | -------- | +| start | Date | 否 | Date('1970-1-1') | 设置选择器的起始日期。 | +| end | Date | 否 | Date('2100-12-31') | 设置选择器的结束日期。 | +| selected | Date | 否 | 当前系统日期 | 设置当前选中的日期。 | +| lunar | boolean | 否 | false | 日期是否显示为农历。 |确定 +| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 点击弹窗中的“确定”按钮时触发该回调。 | +| onCancel | () => void | 否 | - | 点击弹窗中的“取消”按钮时触发该回调。 | +| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult对象说明)) => void | 否 | - | 滑动弹窗中的滑动选择器使当前选中项改变时触发该回调。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 981e3657b58f26359fe17d126a73a4763836f6f4..7bb99f5f46e8bcd2992b36025ca6e3c74a6465fc 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -13,24 +13,24 @@ show(options?: TextPickerDialogOptions) 定义文本滑动选择器弹窗并弹出。 -**TextPickerDialogOptions参数说明:** +**TextPickerDialogOptions参数:** - | 参数名 | 参数类型 | 必填 | 参数描述 | - | -------- | -------- | -------- | -------- | - | range | string[] \| [Resource](ts-types.md#resource) | 是 | 设置文本选择器的选择范围。 | - | selected | number | 否 | 设置选中项的索引值。
默认值:0 | - | value | string | 否 | 设置选中项的文本内容。当设置了selected参数时,该参数不生效。如果设置的value值不在range范围内,则默认取range第一个元素。| - | defaultPickerItemHeight | number \| string | 否 | 设置选择器中选项的高度。 | - | onAccept | (value: TextPickerResult) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | - | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | - | onChange | (value: TextPickerResult) => void | 否 | 滑动弹窗中的选择器使当前选中项改变时触发该回调。 | +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| range | string[] \| [Resource](ts-types.md#resource) | 是 | 设置文本选择器的选择范围。 | +| selected | number | 否 | 设置选中项的索引值。
默认值:0 | +| value | string | 否 | 设置选中项的文本内容。当设置了selected参数时,该参数不生效。如果设置的value值不在range范围内,则默认取range第一个元素。| +| defaultPickerItemHeight | number \| string | 否 | 设置选择器中选项的高度。 | +| onAccept | (value: [TextPickerResult](#textpickerresult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | +| onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | +| onChange | (value: [TextPickerResult](#textpickerresult对象说明)) => void | 否 | 滑动弹窗中的选择器使当前选中项改变时触发该回调。 | ## TextPickerResult对象说明 - | 名称 | 类型 | 描述 | - | -------- | -------- | -------- | - | value | string | 选中项的文本内容。 | - | index | number | 选中项在选择范围数组中的索引值。 | +| 名称 | 类型 | 描述 | +| -------- | -------- | -------- | +| value | string | 选中项的文本内容。 | +| index | number | 选中项在选择范围数组中的索引值。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 61dd5ab8e724f97b8e9d0b4a87bc71627980d9da..97229576c98b61f2d7fb69cf0512adc03e00f8c6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -12,15 +12,16 @@ show(options?: TimePickerDialogOptions) 定义时间滑动选择器弹窗并弹出。 -- TimePickerDialogOptions参数 +**TimePickerDialogOptions参数:** - | 参数名 | 参数类型 | 必填 | 参数描述 | - | -------- | -------- | -------- | -------- | - | selected | Date | 否 | 设置当前选中的时间。
默认值:当前系统时间 | - | useMilitaryTime | boolean | 否 | 展示时间是否为24小时制,默认为12小时制。
默认值:false | - | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | - | onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | - | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 滑动弹窗中的选择器使当前选中时间改变时触发该回调。 | + +| 参数名 | 参数类型 | 必填 | 参数描述 | +| -------- | -------- | -------- | -------- | +| selected | Date | 否 | 设置当前选中的时间。
默认值:当前系统时间 | +| useMilitaryTime | boolean | 否 | 展示时间是否为24小时制,默认为12小时制。
默认值:false | +| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 点击弹窗中的“确定”按钮时触发该回调。 | +| onCancel | () => void | 否 | 点击弹窗中的“取消”按钮时触发该回调。 | +| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult对象说明)) => void | 否 | 滑动弹窗中的选择器使当前选中时间改变时触发该回调。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index f243c3342ad7ee14e6d77fece525d2c149cd1e78..a6e2d28cb802e7bfe22f90fb8fc3bcaa368f0007 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1850,7 +1850,7 @@ rotate(angle: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rotate(45 * Math.PI / 180) // Rotate the rectangle 45 degrees + this.offContext.rotate(45 * Math.PI / 180) this.offContext.fillRect(70, 20, 50, 50) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md index 9d33eb2accfe8ee3e57310dc1db7b0391fce5864..da8af9d48ef6997675a1933f68725ad0ac5847b5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-page-transition-animation.md @@ -25,7 +25,7 @@ | 参数名称 | 参数类型 | 必填 | 参数描述 | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| slide | SlideEffect | 否 | 设置页面转场时的滑入滑出效果。
默认值:SlideEffect.Right | +| slide | [SlideEffect](#slideeffect枚举说明) | 否 | 设置页面转场时的滑入滑出效果。
默认值:SlideEffect.Right | | translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | 否 | 设置页面转场时的平移效果,为入场时起点和退场时终点的值,和slide同时设置时默认生效slide。
- x:横向的平移距离。
- y:纵向的平移距离。
- z:竖向的平移距离。 | | scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | 否 | 设置页面转场时的缩放效果,为入场时起点和退场时终点的值。
- x:横向放大倍数(或缩小比例)。
- y:纵向放大倍数(或缩小比例)。
- z:竖向放大倍数(或缩小比例)。
- centerX、centerY缩放中心点。
- 中心点为0时,默认的是组件的左上角。
| | opacity | number | 否 | 设置入场的起点透明度值或者退场的终点透明度值。
默认值:1 | diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md index aa077567dec5f971cb4ecc13de55214026107413..5df2adf1743dc74464863df7ecc0f3c5aa29c747 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -71,7 +71,7 @@ struct Example { } ``` -![zh-cn_image_0000001169582302](figures/zh-cn_image_0000001169582302.gif) +![zh-cn_image_0000001169582302](figures/zh-cn_image_0000001169582302.png) ## 相关实例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md index b014e51db0a0cbfa071a32edd98ffbd4aa98e327..25b640efc283b43e386883a4263e172f1ba98a6c 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-state-management.md @@ -261,7 +261,7 @@ IsMutable(propName: string): boolean | boolean | 返回此属性是否存在并且是否可以改变。 | ```ts -let simple = AppStorage.IsMutable() +let simple = AppStorage.IsMutable('simpleProp') ``` ### Size @@ -520,7 +520,7 @@ delete(propName: string): boolean | 类型 | 描述 | | ------- | ------------------------------------------------------------ | -| boolean | 删除key指定的键值对,如果存在且删除成功返回true,不存在或删除失败返回false。 | +| boolean | 删除key指定的键值对。存在且删除成功,返回true。不存在、删除失败或有状态变量依旧引用propName,返回false。 | ```ts this.storage = new LocalStorage() @@ -643,7 +643,7 @@ PersistProps(properties: {key: string, defaultValue: any}[]): void; | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | ```ts -PersistentStorage.PersistProps([{'highScore', '0'},{'wightScore','1'}]) +PersistentStorage.PersistProps([{key: 'highScore', defaultValue: '0'},{key: 'wightScore',defaultValue: '1'}]) ``` ### Keys @@ -699,14 +699,14 @@ EnvProp\(key: string, value: S): boolean **内置环境变量说明:** -| key | 类型 | 说明 | -| ------------ | ------------- | ------------------- | -| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | -| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | -| fontScale | number | 字体大小比例。 | -| fontWeightScale | number | 字重比例。 | -| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | -| languageCode | string | 当前系统语言,小写字母,例如zh。 | +| key | 类型 | 说明 | +| ------------ | ------------- | ------------------- | +| accessibilityEnabled | boolean | 无障碍屏幕朗读是否启用。 | +| colorMode | ColorMode | 深浅色模式,可选值为:
- ColorMode.LIGHT:浅色模式;
- ColorMode.DARK:深色模式。 | +| fontScale | number | 字体大小比例。 | +| fontWeightScale | number | 字重比例。 | +| layoutDirection | LayoutDirection | 布局方向类型,可选值为:
- LayoutDirection.LTR:从左到右;
- LayoutDirection.RTL:从右到左。 | +| languageCode | string | 当前系统语言,小写字母,例如zh。 | ```ts Environment.EnvProp('accessibilityEnabled', 'default') @@ -725,7 +725,7 @@ EnvProps(props: {key: string, defaultValue: any}[]): void | key | {key: string, defaultValue: any}[] | 是 | 要关联的属性数组。 | 要关联的属性数组。 | ```ts -Environment.EnvProps([{'accessibilityEnabled', 'default'},{'accessibilityUnEnabled','undefault'}]) +Environment.EnvProps([{key: 'accessibilityEnabled', defaultValue: 'default'},{key: 'accessibilityUnEnabled', defaultValue: 'undefault'}]) ``` ### Keys diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md index 1f97c15861aa8fb6b9e0627760346dd2a5262e58..b8ec7ae00273c1ca6b671dd24dc6f67fe90b8760 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md @@ -20,9 +20,9 @@ | -------- | -------- | -------- | -------- | | type | [TransitionType](ts-appendix-enums.md#transitiontype) | 否 | 默认包括组件新增和删除。
默认值:TransitionType.All
**说明:**
不指定Type时说明插入删除使用同一种效果。 | | opacity | number | 否 | 设置组件转场时的透明度效果,为插入时起点和删除时终点的值。
默认值:1 | -| translate | {
x? : number,
y? : number,
z? : number
} | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。
-x:横向的平移距离。
-y:纵向的平移距离。
-z:竖向的平移距离。 | -| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number,
centerY? : number
} | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。
-x:横向放大倍数(或缩小比例)。
-y:纵向放大倍数(或缩小比例)。
-z:竖向放大倍数(或缩小比例)。
- centerX、centerY缩放中心点。
- 中心点为0时,默认的是组件的左上角。
| -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: Angle,
centerX?: Length,
centerY?: Length
} | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。
-x:横向的旋转向量。
-y:纵向的旋转向量。
-z:竖向的旋转向量。
- centerX,centerY指旋转中心点。
- 中心点为(0,0)时,默认的是组件的左上角。 | +| translate | {
x? : number \| string,
y? : number \| string,
z? : number \| string
} | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。
-x:横向的平移距离。
-y:纵向的平移距离。
-z:竖向的平移距离。 | +| scale | {
x? : number,
y? : number,
z? : number,
centerX? : number \| string,
centerY? : number \| string
} | 否 | 设置组件转场时的缩放效果,为插入时起点和删除时终点的值。
-x:横向放大倍数(或缩小比例)。
-y:纵向放大倍数(或缩小比例)。
-z:竖向放大倍数(或缩小比例)。
- centerX、centerY指缩放中心点,centerX和centerY默认值是"50%"。
- 中心点为0时,默认的是组件的左上角。
| +| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | 否 | 设置组件转场时的旋转效果,为插入时起点和删除时终点的值。
-x:横向的旋转向量。
-y:纵向的旋转向量。
-z:竖向的旋转向量。
- centerX,centerY指旋转中心点,centerX和centerY默认值是"50%"。
- 中心点为(0,0)时,默认的是组件的左上角。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index 021cc278c448273ae8cf0fbec7af7d77cf919152..82fd60584cbbf0dab54f234136342a5a760a8722 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -12,7 +12,7 @@ | 名称 | 参数 | 参数描述 | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| sharedTransition | id: string,
{
 duration?: number,
 curve?: Curve \| string,
 delay?: number,
 motionPath?:
{
 path: string,
 form?: number,
 to?: number,
 rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:单位为毫秒,默认动画时长为1000毫秒。
- curve:默认曲线为Linear,有效值参见[Curve](ts-animatorproperty.md) 说明。
- delay:单位为毫秒,默认不延时播放。
- motionPath:运动路径信息。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- type:动画类型。 | +| sharedTransition | id: string,
{
 duration?: number,
 curve?: Curve \| string,
 delay?: number,
 motionPath?:
{
 path: string,
 form?: number,
 to?: number,
 rotatable?: boolean
},
zIndex?: number,
type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)
} | 两个页面中id值相同且不为空字符串的组件即为共享元素,在页面转场时可显示共享元素转场动效。
- id:设置组件的id。
- duration:单位为毫秒,默认动画时长为1000毫秒。
- curve:默认曲线为Linear,有效值参见[Curve](ts-animatorproperty.md)说明。
- delay:单位为毫秒,默认不延时播放。
- motionPath:运动路径信息,详细说明请参考[路径动画](ts-motion-path-animation.md)。
- path:设置路径。
- from:设置起始值。
- to:设置终止值。
- rotatable:是否旋转。
- zIndex:设置Z轴。
- type:动画类型。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md index 268745a58a2edbff9dd22bd06d6ca3558eb84fd5..bc7115c31ae1c215eb12669c0b8ccc875cbdd78e 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-border-image.md @@ -85,7 +85,7 @@ struct Index { build() { Row() { Column() { - Text('This is gradient color.').textAlign(TextAlign.Center) + Text('This is gradient color.').textAlign(TextAlign.Center).width(68) .borderImage({ source: { angle: 90, diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index f1ad36dfd7f9caec182fb07f44812112c588ebe6..6a779423197d371aa4a5f96447f5dd12b16a4f72 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -229,7 +229,11 @@ struct IdExample { } } }, - source: SourceType.Mouse + source: SourceType.Mouse, + pressure: 1, + tiltX: 1, + tiltY: 1, + sourceTool: SourceTool.Unknown } sendMouseEvent(mouseEvent) // 发送鼠标事件 }, 2000) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index c909c6988b7711c00f9febca084960e0d3caebe1..ab47fc96adfd0e3f7bfa5b006be15dfe050f15dd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -85,7 +85,7 @@ struct PopupExample { } }, onStateChange: (e) => { - console.info(e.isVisible.toString()) + console.info(JSON.stringify(e.isVisible)) if (!e.isVisible) { this.handlePopup = false } diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md index ec171ef02230000c1aad11682469370568732370..33cfcba164e7b09d9a4f44c64cd94a0592620cb5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md @@ -9,12 +9,12 @@ ## 属性 -| 名称 | 参数类型 | 描述 | -| --------- | ------------------------------------------------------------------------ | ---------------------------------------- | -| rotate | {
x?: number,
y?: number,
z?: number,
angle?: Angle,
centerX?: number \| string,
centerY?: number \| string
} | (x, y, z)指定一个矢量,表示旋转轴,正角度为顺时针转动,负角度为逆时针转动,默认值为0,同时可以通过centerX和centerY设置旋转的中心点。
默认值:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
} | -| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | 可以分别设置X轴、Y轴、Z轴的平移距离,距离的正负控制平移的方向。不支持百分比形式的输入。
默认值:
{
x: 0,
y: 0,
z: 0
}| +| 名称 | 参数类型 | 描述 | +| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| rotate | {
x?: number,
y?: number,
z?: number,
angle?: number \| string,
centerX?: number \| string,
centerY?: number \| string
} | (x, y, z)指定一个矢量,表示旋转轴,正角度为顺时针转动,负角度为逆时针转动,默认值为0,同时可以通过centerX和centerY设置旋转的中心点。
默认值:
{
x: 0,
y: 0,
z: 0,
angle: 0,
centerX: '50%',
centerY: '50%'
} | +| translate | {
x?: number \| string,
y?: number \| string,
z? : number \| string
} | 可以分别设置X轴、Y轴、Z轴的平移距离,距离的正负控制平移的方向。不支持百分比形式的输入。
默认值:
{
x: 0,
y: 0,
z: 0
} | | scale | {
x?: number,
y?: number,
z?: number,
centerX?: number \| string,
centerY?: number \| string
} | 可以分别设置X轴、Y轴、Z轴的缩放比例,默认值为1,同时可以通过centerX和centerY设置缩放的中心点。
默认值:
{
x: 1,
y: 1,
z: 1,
centerX:'50%',
centerY:'50%'
} | -| transform | [Matrix4Transit](../apis/js-apis-matrix4.md) | 设置当前组件的变换矩阵。 | +| transform | [Matrix4Transit](../apis/js-apis-matrix4.md) | 设置当前组件的变换矩阵。 | ## 示例 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index 09c1d74aa7bb7ca2ee484ab339996a88825c94fd..505d064a9d292f502a440dbda39b4ff3c0da5382 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -8,13 +8,13 @@ ## 事件 -| 名称 | 支持冒泡 | 功能描述 | -| ---------------------------------------- | ---- | ---------------------------------------- | -| onDragStart(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) =>  [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
返回值:当前跟手效果所拖拽的对象,用于显示拖拽时的提示组件。
长按150ms可触发拖拽事件。优先级:长按手势配置时间小于等于150ms时,长按手势优先触发,否则拖拽事件优先触发。 | -| onDragEnter(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽进入组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | -| onDragMove(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽在组件范围内移动时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | -| onDragLeave(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽离开组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | -| onDrop(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。 | +| 名称 | 支持冒泡 | 功能描述 | +| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | +| onDragStart(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) =>  [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明)) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
返回值:当前跟手效果所拖拽的对象,用于显示拖拽时的提示组件。
长按150ms可触发拖拽事件。优先级:长按手势配置时间小于等于150ms时,长按手势优先触发,否则拖拽事件优先触发。 | +| onDragEnter(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽进入组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | +| onDragMove(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽在组件范围内移动时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | +| onDragLeave(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 拖拽离开组件范围内时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。
当监听了onDrop事件时,此事件才有效。 | +| onDrop(event: (event?: [DragEvent](#dragevent说明), extraParams?: string) => void) | 否 | 绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
- event:拖拽事件信息,包括拖拽点坐标。
- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。 | ## DragItemInfo说明 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md index f2a9dc6bf283788e6facda74f53f3f208cce2ebf..22da939eda01d7ba40d4e80a91baddbc9f6739e1 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-universal-events-show-hide.md @@ -12,7 +12,7 @@ | 名称 | 支持冒泡 | 功能描述 | | ------------------------------------------------ | -------- | -------------------------- | | onAppear(event: () => void) | 否 | 组件挂载显示时触发此回调。 | -| onDisappear(event: () => void) | 否 | 组件卸载消失时触发此回调。 | +| onDisAppear(event: () => void) | 否 | 组件卸载消失时触发此回调。 | ## 示例 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md b/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md new file mode 100644 index 0000000000000000000000000000000000000000..9c5fe5a338ad282b66cced8a4ebe3ef477580545 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-CommonEventService.md @@ -0,0 +1,127 @@ +# 事件错误码 + +## 1500001 want中Action为空 + +**错误信息** +Want action is null + +**错误描述** +发送事件的want中的Action属性为空时系统会产生此错误码。 + +**可能原因** +发送事件的want中的Action属性为空。 + +**处理步骤** +检查传入want的Action属性是否为空。 + +## 1500002 沙箱引用无法发送公共事件 + +**错误信息** +sandbox application can not send common event + +**错误描述** +沙箱引用无法发送公共事件。 + +**可能原因** +事件发送方应用为沙箱应用,发送事件会被拦截。 + +**处理步骤** +检查事件发送是否为沙箱应用,若是,则无法发送。请不要使用沙箱应用发送事件。 + +## 1500003 事件发送频率过高 + +**错误信息** +common event send frequency too high + +**错误描述** +应用发送事件过于频繁。 + +**可能原因** +短时间内应用发送过多事件。 + +**处理步骤** +检查应用是否过于频繁地发送事件。 + +## 1500004 无法发送系统公共事件 + +**错误信息** +not System services or System app + +**错误描述** +当前应用无法发送系统公共事件。 + +**可能原因** +非系统应用或非系统服务发送系统公共事件。 + +**处理步骤** +检查应用是否为系统应用或者系统服务;若不是,则无法发送。 + +## 1500005 未找到订阅者 + +**错误信息** +subscriber can not found + +**错误描述** +找不到订阅者。 + +**可能原因** +订阅者被删除。 + +**处理步骤** +检查是否有重复取消订阅。 + +## 1500006 无效userId + +**错误信息** +usreId is invalid + +**错误描述** +无效的userId。 + +**可能原因** +和系统userId不一致或不是系统应用或子系统进程。 + +**处理步骤** +检查当前userId是否和系统userId一致;若不一致,检查系统应用或子系统进程。 + +## 1500007 IPC请求发送失败 + +**错误信息** +message send error + +**错误描述** +IPC发送请求失败。 + +**可能原因** +没有成功创建连接对象。 + +**处理步骤** +请勿频繁建立链接,稍后重新尝试。 + +## 1500008 读取数据失败 + +**错误信息** +CEMS error + +**错误描述** +服务端发生错误。 + +**可能原因** +服务端处理数据时发现业务异常。 + +**处理步骤** +稍后重新尝试。 + +## 1500009 system error + +**错误信息** +system error + +**错误描述** +处理业务时系统发生异常,如获取系统当前时间失败。 + +**可能原因** +系统故障,获取系统当前时间发生异常。 + +**处理步骤** +稍后重新尝试。 diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-DeviceUsageStatistics.md b/zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-DeviceUsageStatistics.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-DeviceUsageStatistics.md diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-DistributedNotificationService.md b/zh-cn/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-DistributedNotificationService.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-DistributedNotificationService.md diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md b/zh-cn/application-dev/reference/errorcodes/errorcode-DistributedSchedule.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-DistributedSchedule.md diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md b/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..d5aa62b58c0c5d3a97e72f9d9e0cc82afb15a30f --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @@ -0,0 +1,713 @@ +# 元能力子系统错误码 + +## 16000001 指定的Ability名称不存在 + +**错误信息** + +Input error. The specified ability name does not exist. + +**错误描述** + +当指定的Ability名称不存在时,方法将返回该错误码。 + +**可能原因** + +所查询的Ability不存在。 + +**处理步骤** + +1. 检查包名称是否正确。 +2. 检查包名对应的Ability是否正确。 + +## 16000002 接口调用Ability类型错误 + +**错误信息** + +Ability type error. The specified ability type is wrong. + +**错误描述** + +当接口调用Ability类型错误时,方法将返回该错误码。 + +**可能原因** + +接口调用所在的Ability类型不支持该接口调用。 + +**处理步骤** + +1. 检查包名对应的Ability是否正确。 +2. 根据Ability类型调用不同接口。 + +## 16000003 指定的ID不存在 + +**错误信息** + +Input error. The specified id does not exist. + +**错误描述** + +当指定的ID不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标ID不存在。 + +**处理步骤** + +确认操作的ID是否存在。 + +## 16000004 可见性校验失败 + +**错误信息** + +Visibility verification failed. + +**错误描述** + +当可见性校验失败时,方法将返回该错误码。 + +**可能原因** + +应用可见性校验失败。 + +**处理步骤** + +请检查应用是否满足被拉起应用可见性限制。 + +## 16000006 不允许跨用户操作 + +**错误信息** + +Can not cross user operations. + +**错误描述** + +当应用跨用户操作时,方法将返回该错误码。 + +**可能原因** + +应用进行了跨用户操作。 + +**处理步骤** + +确认是否进行了跨用户操作。 + +## 16000007 服务繁忙 + +**错误信息** + +Service busyness. There are concurrent tasks, waiting for retry. + +**错误描述** + +当服务繁忙时,方法将返回该错误码。 + +**可能原因** + +服务繁忙。 + +**处理步骤** + +服务繁忙,请稍后重试。 + +## 16000008 众测应用到期 + +**错误信息** + +Crowdtest App Expiration. + +**错误描述** + +当众测应用到期时,方法将返回该错误码。 + +**可能原因** + +众测应用到期,无法打开。 + +**处理步骤** + +请检查应用是否众测到期。 + +## 16000009 wukong模式,不允许启动/停止ability + +**错误信息** + +Can not start ability in wukong mode. + +**错误描述** + +当wukong模式下,启动/停止ability时,方法将返回该错误码。 + +**可能原因** + +wukong模式,不允许启动/停止ability。 + +**处理步骤** + +请勿在wukong模型下启动/停止Ability。 + +## 16000010 不允许带迁移flag + +**错误信息** + +Can not operation with continue flag. + +**错误描述** + +当调用携带迁移flag时,方法将返回该错误码。 + +**可能原因** + +当前调用不允许携带迁移flag。 + +**处理步骤** + +请检查是否携带迁移flag。 + +## 16000011 上下文对象不存在 + +**错误信息** + +Context does not exist. + +**错误描述** + +当上下文对象不存在时,方法将返回该错误码。 + +**可能原因** + +当前上下文对象不存在。 + +**处理步骤** + +请检查上下文对象是否可用。 + +## 16000050 内部错误 + +**错误信息** + +Internal Error. + +**错误描述** + +当内存申请、多线程处理异常等内部处理错误时,方法将返回该错误码。 + +**可能原因** + +内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +确认系统内存是否足够。 + +## 16000051 网络异常 + +**错误信息** + +Network error. The network is abnormal. + +**错误描述** + +当网络异常时,方法将返回该错误码。 + +**可能原因** + +网络不可用。 + +**处理步骤** + +网络异常,请稍后重试,或者重连网络尝试。 + +## 16000052 不支持免安装 + +**错误信息** + +Free install not support. The applicaiotn dose not support free install. + +**错误描述** + +当前应用不支持免安装时,方法将返回该错误码。 + +**可能原因** + +应用包不满足免安装要求,如包大小超过限制等。 + +**处理步骤** + +请检查应用是否支持免安装。 + +## 16000053 非顶层应用 + +**错误信息** + +Not top ability. The application is not top ability. + +**错误描述** + +当前应用未显示在界面顶层时,方法将返回该错误码。 + +**可能原因** + +应用未显示在界面顶层。 + +**处理步骤** + +请检查应用是否显示在界面顶层。 + +## 16000054 免安装服务繁忙 + +**错误信息** + +Free install busyness. There are concurrent tasks, waiting for retry. + +**错误描述** + +当免安装服务繁忙时,方法将返回该错误码。 + +**可能原因** + +已有相同免安装任务在执行。 + +**处理步骤** + +免安装服务繁忙,请稍后重试。 + +## 16000055 免安装超时 + +**错误信息** + +Free install timeout. + +**错误描述** + +当免安装超时时,方法将返回该错误码。 + +**可能原因** + +免安装超时。 + +**处理步骤** + +免安装超时,请稍后重试。 + +## 16000056 不允许免安装其他应用 + +**错误信息** + +Can not free install other ability. + +**错误描述** + +当免安装其他应用时,方法将返回该错误码。 + +**可能原因** + +不允许免安装其他应用。 + +**处理步骤** + +确认免安装的是正确的应用。 + +## 16000057 不支持跨设备免安装 + +**错误信息** + +Not support cross device free install. + +**错误描述** + +当持跨设备免安装时,方法将返回该错误码。 + +**可能原因** + +不支持跨设备免安装。 + +**处理步骤** + +确认为非跨设备免安装应用。 + +## 16000101 执行shell命令失败 + +**错误信息** + +execute shell command failed. + +**错误描述** + +当命令不是有效的shell命令时,方法将返回该错误码。 + +**可能原因** + +命令不是有效的shell命令。 + +**处理步骤** + +检查命令是否为有效的shell命令。 + +## 16000151 无效wantAgent对象 + +**错误信息** + +Invalid wantagent object. + +**错误描述** + +当传入接口的wantAgent对象无效时,方法将返回该错误码。 + +**可能原因** + +传入接口的wantAgent对象无效。 + +**处理步骤** + +检查传入接口的wantAgent对象。 + +## 16000152 未找到wantAgent对象 + +**错误信息** + +wantAgent object not found. + +**错误描述** + +当传入接口的wantAgent对象不存在时,方法将返回该错误码。 + +**可能原因** + +传入接口的wantAgent对象不存在。 + +**处理步骤** + +检查传入接口的wantAgent对象是否合法。 + +## 16000153 wangAgent对象已取消 + +**错误信息** + +wangAgent object canceled. + +**错误描述** + +当传入接口的wangAgent对象已取消时,方法将返回该错误码。 + +**可能原因** + +传入接口的触发的wantAgent已取消。 + +**处理步骤** + +检查触发的wantAgent对象是否已取消。 + +## 16100001 指定Uri的Ability不存在 + +**错误信息** + +Input error. The specified uri does not exist. + +**错误描述** + +当指定Uri的Ability不存在时,方法将返回该错误码。 + +**可能原因** + +所查询的Ability不存在。 + +**处理步骤** + +确认查询的Ability是否存在。 + +## 16100002 接口调用Ability类型错误 + +**错误信息** + +Ability type error. The specified ability type is wrong. + +**错误描述** + +当接口调用Ability类型错误时,方法将返回该错误码。 + +**可能原因** + +接口调用所在的Ability类型不支持该接口调用。 + +**处理步骤** + +1. 检查包名对应的Ability是否正确。 +2. 根据Ability类型调用不同接口。 + +## 16200001 通用组件客户端(Caller)已回收 + +**错误信息** + +Caller released. The caller has been released. + +**错误描述** + +当通用组件客户端(Caller)已回收时,方法将返回该错误码。 + +**可能原因** + +通用组件客户端(Caller)已回收。 + +**处理步骤** + +请重新注册有效通用组件客户端调用接口。 + +## 16200002 通用组件服务端(Callee)无效 + +**错误信息** + +Callee Invalid. The callee does not exist. + +**错误描述** + +当通用组件服务端(Callee)无效时,方法将返回该错误码。 + +**可能原因** + +通用组件服务端(Callee)不存在。 + +**处理步骤** + +请检查通用组件服务端是否存在。 + +## 16200003 回收失败 + +**错误信息** + +Release error. The caller does not call any callee. + +**错误描述** + +当回收失败时,方法将返回该错误码。 + +**可能原因** + +通用组件客户端(Caller)对象未注册通用组件服务端(Callee)。 + +**处理步骤** + +请检查是否已注册通用组件服务端。 + +## 16200004 方法已注册 + +**错误信息** + +Method registered. The method has registered. + +**错误描述** + +当方法已注册时,方法将返回该错误码。 + +**可能原因** + +方法已在通用组件服务端注册过。 + +**处理步骤** + +请检查是否已注册该方法。 + +## 16200005 方法未注册 + +**错误信息** + +Method not registered. The method has not registered. + +**错误描述** + +当方法未注册时,方法将返回该错误码。 + +**可能原因** + +方法未在通用组件服务端注册。 + +**处理步骤** + +请检查是否未注册该方法。 + +## 16300001 指定的任务不存在 + +**错误信息** + +Mission id error. The specified mission id does not exist. + +**错误描述** + +当指定的任务不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标任务不存在。 + +**处理步骤** + +确认操作的任务是否存在。 + +## 16300002 指定的任务监听器不存在 + +**错误信息** + +Input error. The specified mission listener id does not exist. + +**错误描述** + +当指定的任务监听器不存在时,方法将返回该错误码。 + +**可能原因** + +操作的目标任务监听器不存在。 + +**处理步骤** + +确认操作的任务监听器是否存在。 + +## 18500001 指定的包名无效 + +**错误信息** + +The specified bundleName is invalid. + +**错误描述** + +当指定的包名无效时,方法将返回该错误码。 + +**可能原因** + +待查询的bundle不存在或未安装。 + +**处理步骤** + +确认查询的应用是否已安装。 + +## 18500002 指定的补丁包无效 + +**错误信息** + +The specified hqf is invalid. Hqf may not exist or inaccessible. + +**错误描述** + +当指定的补丁包无效,补丁包不存在或不可访问时,方法将返回该错误码。 + +**可能原因** + +待安装的补丁包文件不存在或不可以访问。 + +**处理步骤** + +1. 请检查传递的补丁包文件路径是否有效。 +2. 请检查是否有权限访问此补丁包文件。 + +## 18500003 补丁包部署失败 + +**错误信息** + +Deploy hqf failed. + +**错误描述** + +当补丁包部署失败时,方法将返回该错误码。 + +**可能原因** + +1. patch.json中type只能为patch或者hotreload,否则部署失败。 +2. 若对应bundleName的hap包未安装,部署失败。 +3. bundleName、versionCode必须和已安装的hap应用相同,如果为patch类型,还需确保versionName相同,否则部署失败。 +4. 如果已经部署过补丁包,新部署的补丁包的versionCode必须大于之前补丁包的versionCode,否则部署失败。 +5. 对于patch类型的补丁会校验签名信息,使用的签名证书需要和应用相同,签名不一致,部署失败。 +6. 在部署patch类型的补丁包时,如果是debug版本,先判断是否有在使用的补丁包,如果在使用的补丁包为hotreload类型,则部署失败。 +7. 在部署hotreload类型的补丁包时,如果是debug版本,先判断是否有在使用的补丁包,如果在使用的补丁包为patch类型,则部署失败;如果是release版本,则部署失败。 + +**处理步骤** + +请检查补丁包是否符合规则。 + +## 18500004 补丁包使能失败 + +**错误信息** + +Switch hqf failed. + +**错误描述** + +当补丁包使能失败时,方法将返回该错误码。 + +**可能原因** + +使能补丁时补丁包状态不正确。 + +**处理步骤** + +请检查补丁包状态。 + +## 18500005 补丁包删除失败 + +**错误信息** + +Delete hqf failed. + +**错误描述** + +当补丁包删除失败时,方法将返回该错误码。 + +**可能原因** + +删除旧补丁时补丁包状态不正确。 + +**处理步骤** + +请检查补丁包状态。 + +## 18500006 加载补丁失败 + +**错误信息** + +Load patch failed. + +**错误描述** + +当加载补丁失败时,方法将返回该错误码。 + +**可能原因** + +方舟引擎加载补丁失败。 + +**处理步骤** + +请检查补丁包是否正确。 + +## 18500007 卸载旧补丁失败 + +**错误信息** + +Unload patch failed. + +**错误描述** + +当方舟引擎卸载旧补丁失败时,方法将返回该错误码。 + +**可能原因** + +方舟引擎加载补丁失败。 + +**处理步骤** + +请检查补丁包是否正确。 + +## 18500008 快速修复内部错误 + +**错误信息** + +Internal error. + +**错误描述** + +当内存申请、多线程处理异常等内部处理错误时,方法将返回该错误码。 + +**可能原因** + +内存申请、多线程处理等内核通用错误。 + +**处理步骤** + +确认系统内存是否足够。 diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md b/zh-cn/application-dev/reference/errorcodes/errorcode-account.md similarity index 99% rename from zh-cn/application-dev/reference/errorcodes/errcode-Account.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-account.md index b7c29b43401ba05a1bf6a4d0b908271f6ba701d2..0894a278080b8ac2be19eb4b7ccade4a82c324d5 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-account.md @@ -320,7 +320,7 @@ The auth type is not supported. 请提供系统支持的认证类型。 -## 12300007 认证类型不存在 +## 12300107 认证类型不存在 **错误信息** @@ -335,7 +335,7 @@ The auth type does not exist. 请使用存在的认证类型查询/删除。 -## 12300008 认证会话不存在 +## 12300108 认证会话不存在 **错误信息** diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md b/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md similarity index 62% rename from zh-cn/application-dev/reference/errorcodes/errcode-bundle.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md index 509944b152d70c4c7062af64456e1bd82a7d9f18..1995604ae0c45e85c04bfeb1df7205c79a7f23ce 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-bundle.md @@ -6,7 +6,7 @@ The specified bundle name is not found. **错误描述**
-调用接口时,传入的bundleName不存在。 +调用查询等接口时,传入的bundleName不存在。 **可能原因**
1. 输入的bundleName有误。 @@ -22,14 +22,14 @@ The specified bundle name is not found. The specified module name is not found. **错误描述**
-调用接口时,传入的moduleName不存在。 +调用查询或者免安装相关接口时,传入的moduleName不存在。 **可能原因**
1. 输入的moduleName有误。 2. 系统中对应的应用没有安装该模块。 **处理步骤**
-1. 检查bundleName拼写是否正确。 +1. 检查moduleName拼写是否正确。 2. 确认对应的应用是否安装该模块。 ## 17700003 指定的abilityName不存在 @@ -38,7 +38,7 @@ The specified module name is not found. The specified ability name is not found. **错误描述**
-调用接口时,传入的abilityName不存在。 +调用查询等接口时,传入的abilityName不存在。 **可能原因**
1. 输入的abilityName有误。 @@ -46,15 +46,15 @@ The specified ability name is not found. **处理步骤**
1. 检查abilityName拼写是否正确。 -2. 确认对应的应用是否安装该模块。 +2. 确认对应的应用是否安装该组件。 ## 17700004 指定的用户不存在 **错误信息**
-The specified user id is not found. +The specified user ID is not found. **错误描述**
-调用接口时,传入的用户不存在。 +调用与用户相关接口时,传入的用户不存在。 **可能原因**
输入的用户名有误,系统中没有该用户。 @@ -66,10 +66,10 @@ The specified user id is not found. ## 17700005 指定的appId不存在 **错误信息**
-The specified appId is not found. +The specified app ID is not found. **错误描述**
-调用接口时,传入的appId为空字符串。 +调用appControl模块中的相关接口时,传入的appId为空字符串。 **可能原因**
传入的appId为空字符串。 @@ -83,7 +83,7 @@ The specified appId is not found. The specified permission is not found. **错误描述**
-调用接口时,传入的权限不存在。 +调用bundleManager模块中的getPermissionDef接口时,传入的权限不存在。 **可能原因**
1. 传入的permission名称拼写有误。 @@ -96,10 +96,10 @@ The specified permission is not found. ## 17700007 输入的设备Id有误 **错误信息**
-The specified deviceId is not found. +The specified device ID is not found. **错误描述**
-调用接口时,传入的设备id有误。 +调用distributedBundle模块相关接口时,传入的设备id有误。 **可能原因**
1. 传入的deviceId拼写有误。 @@ -112,10 +112,10 @@ The specified deviceId is not found. ## 17700010 文件解析失败导致应用安装失败 **错误信息**
-Failed to install the hap since the hap fails to be parsed. +Failed to install the HAP because the HAP fails to be parsed. **错误描述**
-文件解析失败导致应用安装失败。 +调用installer模块中的install接口时,传入的HAP包解析失败。 **可能原因**
1. hap包的格式不是zip格式。 @@ -127,15 +127,16 @@ Failed to install the hap since the hap fails to be parsed. 2. 确认hap的配置文件满足[配置文件json格式](../../quick-start/stage-structure.md)。 3. 检查DevEco Studio编译hap时是否有错误提示,缺省字段时会有相应的报错。 -## 17700011 签名校验失败失败导致应用安装失败 +## 17700011 签名校验失败导致应用安装失败 **错误信息**
-Failed to install the hap since the hap signature fails to be verified. +Failed to install the HAP because the HAP signature fails to be verified. **错误描述**
-签名校验失败失败导致应用安装失败。 +调用installer模块中的install接口时,签名校验失败导致应用安装失败。 **可能原因**
+ 1. hap包没有签名。 2. hap签名信息来源不可靠。 3. 升级的hap包与已安装的hap包签名信息不一致。 @@ -146,57 +147,31 @@ Failed to install the hap since the hap signature fails to be verified. 2. 确认多个hap签名时使用的证书相同。 3. 确认升级的hap签名证书与已安装的hap相同。 -## 17700012 安装包路径无效导致应用安装失败 +## 17700012 安装包路径无效或者文件过大导致应用安装失败 **错误信息**
-Failed to install the hap since the path of the hap is invalid. +Failed to install the HAP because the HAP path is invalid or the HAP is too large. **错误描述**
-安装包路径无效导致应用安装失败。 +调用installer模块中的install接口时,安装包路径无效或者文件过大导致应用安装失败。 **可能原因**
1. 输入错误,hap包的文件路径不存在。 2. hap包的路径无法访问。 +3. hap包的大小超过最大限制4G。 **处理步骤**
1. 确认hap是否存在。 2. 查看hap的可执行权限,是否可读。 - -## 17700013 应用包过大导致应用安装失败 - -**错误信息**
-Failed to install the hap since the hap is too large. - -**错误描述**
-应用包过大导致应用安装失败。 - -**可能原因**
-hap包过大,一个hap不能超过4GB。 - -**处理步骤**
-确认hap包的大小。 - -## 17700014 应用包后缀有误导致应用安装失败 - -**错误信息**
-Failed to install the hap since the extension name of the hap is not .hap. - -**错误描述**
-应用包后缀有误导致应用安装失败。 - -**可能原因**
-hap包的文件后缀名不为.hap。 - -**处理步骤**
-确认hap包的后缀是否为.hap。 +3. 查看hap包的大小是否超过4G。 ## 17700015 多个hap包配置信息不同导致应用安装失败 **错误信息**
-Failed to install haps since the configuration information of multi haps is inconsistent. +Failed to install the HAPs because they have different configuration information. **错误描述**
-多个hap包配置信息不同导致应用安装失败。 +调用installer模块中的install接口时,多个hap包配置信息不同导致应用安装失败。 **可能原因**
多个hap包中配置文件app下面的字段不一致。 @@ -207,10 +182,10 @@ Failed to install haps since the configuration information of multi haps is inco ## 17700016 系统磁盘空间不足导致应用安装失败 **错误信息**
-Failed to install the hap since the system disk space is insufficient. +Failed to install the HAP because of insufficient system disk space. **错误描述**
-系统磁盘空间不足导致应用安装失败。 +调用installer模块中的install接口时,系统磁盘空间不足导致应用安装失败。 **可能原因**
系统空间不足。 @@ -221,10 +196,10 @@ Failed to install the hap since the system disk space is insufficient. ## 17700017 新安装的应用版本号低于已安装的版本号导致应用安装失败 **错误信息**
-Failed to install the hap since the version of the newly installed hap is too early. +Failed to install the HAP since the version of the HAP to install is too early. **错误描述**
-新安装的应用版本号低于已安装的版本号导致应用安装失败。 +调用installer模块中的install接口时,新安装的应用版本号低于已安装的版本号导致应用安装失败。 **可能原因**
新安装的应用版本号低于已安装的版本号。 @@ -238,7 +213,7 @@ Failed to install the hap since the version of the newly installed hap is too ea The preinstalled app cannot be uninstalled. **错误描述**
-预置应用无法卸载。 +调用installer模块中的uninstall接口卸载预置应用时,无法卸载。 **可能原因**
1. 传入的bundleName拼写有误。 @@ -254,7 +229,7 @@ The preinstalled app cannot be uninstalled. The specified uid is invalid. **错误描述**
-指定的uid无效。 +调用bundleManager模块中的getBundleNameByUid接口时,指定的uid无效。 **可能原因**
1. 传入的uid拼写有误。 @@ -270,7 +245,7 @@ The specified uid is invalid. The input source file is invalid. **错误描述**
-输入的待解析源文件无效。 +调用bundleManager模块中的getBundleArchiveInfo接口时,传入的HAP路径无效。 **可能原因**
1. 待解析的源文件不存在。 @@ -286,7 +261,7 @@ The input source file is invalid. The specified default app does not exist. **错误描述**
-指定的默认应用不存在。 +调用defaultAppManager模块中的getDefaultApplication接口时,指定的默认应用不存在。 **可能原因**
设备没有设置对应的默认应用。 @@ -297,10 +272,10 @@ The specified default app does not exist. ## 17700024 没有相应的配置文件 **错误信息**
-Failed to get profile since no profile in the hap. +Failed to get the profile because there is no profile in the HAP. **错误描述**
-没有相应的配置文件。 +调用查询profile文件的相关接口时,没有相应的配置文件。 **可能原因**
1. 输入的metadata name在配置文件中不存在。 @@ -316,7 +291,7 @@ Failed to get profile since no profile in the hap. The specified type is invalid. **错误描述**
-输入的type无效。 +调用defaultAppManager模块的相关接口时,输入的type无效。 **可能原因**
1. 输入的type拼写有误。 @@ -331,7 +306,7 @@ The specified type is invalid. The specified bundle is disabled. **错误描述**
-指定应用被禁用。 +当调用查询应用的相关信息接口时,指定应用被禁用。 **可能原因**
设备上对应的应用已经被禁用,无法查询。 @@ -345,7 +320,7 @@ The specified bundle is disabled. The distributed service is not running. **错误描述**
-分布式服务未启动。 +当调用distributedBundle模块的相关接口时,分布式服务未启动。 **可能原因**
设备未组网。 @@ -355,13 +330,42 @@ The distributed service is not running. ## 17700028 输入的ability与type不匹配 **错误信息**
-The distributed service is not running. +The ability does not match the type. **错误描述**
-输入的ability与type不匹配。 +当调用defaultAppManager模块中的setDefaultApplication接口时,输入的ability与type不匹配。 **可能原因**
输入的ability和type拼写有误。 **处理步骤**
确认输入的ability和type拼写是否正确。 + +## 17700029 指定的ability被禁用 + +**错误信息**
+The specified ability is disabled. + +**错误描述**
+当调用查询ability相关信息的接口时,指定的ability被禁用。 + +**可能原因**
+指定的ability被禁用。 + +**处理步骤**
+确认指定的ability是否被禁用,可以使用[bm工具](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md#bm)命令查询对应的应用信息。 + +## 17700030 指定的应用不支持清除缓存文件 + +**错误信息**
+The specified bundle does not support clearing of cache files. + +**错误描述**
+当调用bundleManager模块中的cleanBundleCacheFiles接口时,指定的应用不支持清除缓存文件。 + +**可能原因**
+指定的应用为系统应用且在签名证书中配置了不能清除数据(AllowAppDataNotCleared)的字段。 + +**处理步骤**
+1.确认指定的应用是否为系统应用,可以使用[bm工具](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md#bm)命令查询对应的应用信息,查看isSystemApp是否为true。 +2.确认指定的应用是否配置了能清除缓存(AllowAppDataNotCleared)的字段,可以使用[bm工具](../../../readme/%E5%8C%85%E7%AE%A1%E7%90%86%E5%AD%90%E7%B3%BB%E7%BB%9F.md#bm)命令查询对应的应用信息,查看userDataClearable是否为true。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md b/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md new file mode 100644 index 0000000000000000000000000000000000000000..14f6bfc1665c1b6e990f5d5ac610f6a137988032 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-data-rdb.md @@ -0,0 +1,79 @@ +# 关系型数据库错误码 + +## 14800010 数据库名称不合法 + +**错误信息** + +Invalid database name. + +**错误描述** + +数据库名称不合法。 + +**可能原因** + +无效的数据库名称,数据库名称为空或包含的字符超出1024字节。 + +**处理步骤** + +检查传入数据库名称,检查数据库名称是否为空或包含的字符超出1024字节。 + +## 14800011 数据库文件损坏 + +**错误信息** + +Database corrupted. + +**错误描述** + +该错误码表示在调用数据库增、删、查、数据同步等接口时,数据库已损坏。 + +**可能原因** + +调用数据库增、删、查、数据同步等接口操作数据库时,数据库文件已损坏。 + +**处理步骤** + +1. 如果之前备份过数据库,可尝试使用已备份的数据库文件恢复数据库。 +2. 如果之前没有备份过数据库,可尝试删除数据库后重新创建。 + +## 14800012 结果集为空或指定位置不合法 + +**错误信息** + +The result set is empty or the specified location is invalid. + +**错误描述** + +结果集为空或指定位置不合法。 + +**可能原因** + +结果集为空或结果集指定行号超出位置范围[0, m - 1],m = resultsetV9.rowCount。 + +**处理步骤** + +检查当前操作得到的结果集是否为空或指定的位置是否合法。 + +## 14800013 列值为空或列类型与当前调用接口不兼容 + +**错误信息** + +The column value is null or the column type is incompatible. + +**错误描述** + +列值为空或列类型与当前调用接口不兼容。 + +**可能原因** + +1. 结果集为空。 +2. 结果集当前行号超出范围[0, m - 1],m = resultsetV9.rowCount。 +3. 当前列号超出范围[0, n - 1],n = resultsetV9.columnCount。 +4. 当前列数据类型接口不支持。 + +**处理步骤** + +1. 检查结果集是否为空。 +2. 检查结果集当前行号、列号是否超出范围。 +3. 检查当前列数据类型是否支持。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md b/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md index 4ff21bd81fa914f96f5836dd73da6abd1b959643..e47bdda1481e9cae8480968f9379a0ebcc9e513f 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @@ -2,65 +2,81 @@ ## 15100001 超过最大订阅数量 -### 错误信息 +**错误信息** + Over max subscribe limits. -### 错误描述 +**错误描述** + 该错误码表示在调用数据库变化订阅on接口时,订阅数量已超过最大限制。 -### 可能原因 +**可能原因** + 在调用订阅数据库变化接口时,对数据库的订阅数量已超过最大限制。 -### 处理步骤 +**处理步骤** + 取消对数据库的部分订阅后,再次尝试订阅。 ## 15100002 打开已有数据库时参数配置发生变化 -### 错误信息 +**错误信息** + Open existed database with changed options. -### 错误描述 +**错误描述** + 该错误码表示在调用getKVStore接口打开已创建的数据库时,options配置参数发生变化。 -### 可能原因 +**可能原因** + 打开已创建的数据库时,options参数配置发生了变化,可能原因如下: 1. 期望新建数据库时,使用了已创建过的数据库名称storeId。 2. 期望改变已创建数据库的options参数配置。 -### 处理步骤 +**处理步骤** + 1. 新建数据库前,请检查数据库名称storeId不与已创建数据库的storeId重名。 2. 期望改变已创建数据库的options参数配置时,当前不支持该操作,请自行删除数据库后使用新的options参数重新创建。 ## 15100003 数据库损坏 -### 错误信息 +**错误信息** + Database corrupted. -### 错误描述 +**错误描述** + 该错误码表示在调用数据库增、删、查、数据同步等接口时,数据库已损坏。 -### 可能原因 +**可能原因** + 调用数据库增、删、查、数据同步等接口操作数据库时,数据库文件已损坏。 -### 处理步骤 +**处理步骤** + 1. 如果之前备份过数据库,可尝试使用已备份的数据库文件恢复数据库。 2. 如果之前没有备份过数据库,可尝试删除数据库后重新创建。 ## 15100004 未找到相关数据 -### 错误信息 +**错误信息** + Not found. -### 错误描述 +**错误描述** + 该错误码表示在调用数据库deleteKVStore、delete、deleteBatch、get等接口时,未找到相关数据。 -### 可能原因 +**可能原因** + 在调用删除数据库、数据查询、数据删除等接口时未找到相关数据,可能原因如下。 1. 删除数据库操作时,数据库不存在或已删除。 2. 数据库数据查询操作时,相关数据不存在或已删除。 3. 数据库数据删除操作时,相关数据不存在或已删除。 -### 处理步骤 +**处理步骤** + 1. 在删除数据库操作前,请检查数据库名称是否正确或是否重复删除。 2. 在数据库数据查询操作前,请检查查询关键字是否正确。 3. 在数据库数据删除操作前,请检查删除关键字是否正确或是否重复删除。 @@ -68,29 +84,37 @@ Not found. ## 15100005 不支持当前操作 -### 错误信息 +**错误信息** + Not support the operation. -### 错误描述 +**错误描述** + 该错误码表示在调用数据库backup、restore等接口时,当前数据库不支持该操作。 -### 可能原因 +**可能原因** + 在调用数据库备份、恢复等接口时,当前数据库不支持该操作。 -### 处理步骤 +**处理步骤** + 检查当前数据库是否支持备份、恢复操作。 ## 15100006 数据库或查询结果集已关闭 -### 错误信息 +**错误信息** + Database or result set already closed. -### 错误描述 +**错误描述** + 该错误码表示在调用数据库或查询结果集相关接口时,数据库或查询结果集为关闭状态。 -### 可能原因 +**可能原因** + 在数据库或查询结果集操作前,已经手动关闭了数据库或查询结果集。 -### 处理步骤 +**处理步骤** + 1. 在数据库相关操作前,请重新打开数据库之后再重试当前操作。 -2. 在查询结果集相关操作前,请重新查询获取结果集之后再重试当前操作。 +2. 在查询结果集相关操作前,请重新查询获取结果集之后再重试当前操作。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-enterpriseDeviceManager.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errorcode-EnterpriseDeviceManager.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-enterpriseDeviceManager.md diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md index 07ef23b7328f886e9eccb2352ee8609c30962e1f..5166f78088c57fdce16ca43bc2d54668bdea696e 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hiappevent.md @@ -253,7 +253,8 @@ Invalid max storage quota value. 传入的最大存储配额值字符串不符合以下规则: -- 最大存储配额值以数字开头,以大小单位(单位字符支持[b|k|kb|m|mb|g|gb|t|tb],不区分大小写)结尾,且不包含其他字符。 +- 配额值字符串只由数字字符和大小单位字符(单位字符支持[b|k|kb|m|mb|g|gb|t|tb],不区分大小写)构成。 +- 配额值字符串必须以数字开头,后面可以选择不传单位字符(默认使用byte作为单位),或者以单位字符结尾。 **处理步骤** diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md b/zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-inputmethod-framework.md diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-multimodalinput.md b/zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errorcodes-multimodalinput.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-multimodalinput.md diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-reminderAgentManager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-reminderAgentManager.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-request.md b/zh-cn/application-dev/reference/errorcodes/errorcode-request.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errorcodes-request.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-request.md diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-system-parameterV9.md b/zh-cn/application-dev/reference/errorcodes/errorcode-system-parameterV9.md similarity index 93% rename from zh-cn/application-dev/reference/errorcodes/errcode-system-parameterV9.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-system-parameterV9.md index effa914b588691613a686964e134ec2f400d4cc6..58b8a3e1340479efa4dae169c9f0c7e787654d29 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-system-parameterV9.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-system-parameterV9.md @@ -1,74 +1,74 @@ -# 系统参数错误码 - -## 14700101 系统参数查找失败 - -**错误信息** - -System parameter can not be found. - -**错误描述** - -workspace中没有相应节点,或者没有设置key值,系统会报此错误码。 - -**可能原因** - -参数没有设置,或设置失败。 - -**处理步骤** - -设置合法的参数。 - -## 14700102 系统参数值无效 - -**错误信息** - -System parameter value is invalid. - -**错误描述** - -当系统参数value值为空字符、非法字符或长度超出范围时,系统会报此错误码。 - -**可能原因** - -接口的参数值超出设置范围或者含有特殊字符,比如,"const..param.xxx"。 - -**处理步骤** - -修改value值为合法字符串。 - -## 14700103 系统权限操作权限被拒绝 - -**错误信息** - -System permission operation permission denied. - -**错误描述** - -系统参数没有DAC或MAC权限时,系统会报此错误码。 - -**可能原因** - -没有配置DAC或MAC权限。 - -**处理步骤** - -添加相应的DAC或MAC权限。 - -## 14700104 系统内部错误,包括内存不足,死锁等 - -**错误信息** - -System internal error including out of memory, deadlock etc. - -**错误描述** - -当试图修改const属性参数、socket连接失败、内存拷贝失败等错误时,系统会报此错误码。 - -**可能原因** - -当socket连接异常,添加节点或获取节点失败。 - -**处理步骤** - -1. 内存不足,需要分析整个进程的内存占用情况,是否有内存泄露的情况。 +# 系统参数错误码 + +## 14700101 系统参数查找失败 + +**错误信息** + +System parameter can not be found. + +**错误描述** + +workspace中没有相应节点,或者没有设置key值,系统会报此错误码。 + +**可能原因** + +参数没有设置,或设置失败。 + +**处理步骤** + +设置合法的参数。 + +## 14700102 系统参数值无效 + +**错误信息** + +System parameter value is invalid. + +**错误描述** + +当系统参数value值为空字符、非法字符或长度超出范围时,系统会报此错误码。 + +**可能原因** + +接口的参数值超出设置范围或者含有特殊字符,比如,"const..param.xxx"。 + +**处理步骤** + +修改value值为合法字符串。 + +## 14700103 系统权限操作权限被拒绝 + +**错误信息** + +System permission operation permission denied. + +**错误描述** + +系统参数没有DAC或MAC权限时,系统会报此错误码。 + +**可能原因** + +没有配置DAC或MAC权限。 + +**处理步骤** + +添加相应的DAC或MAC权限。 + +## 14700104 系统内部错误,包括内存不足,死锁等 + +**错误信息** + +System internal error including out of memory, deadlock etc. + +**错误描述** + +当试图修改const属性参数、socket连接失败、内存拷贝失败等错误时,系统会报此错误码。 + +**可能原因** + +当socket连接异常,添加节点或获取节点失败。 + +**处理步骤** + +1. 内存不足,需要分析整个进程的内存占用情况,是否有内存泄露的情况。 2. 死锁,多出现在多线程场景下,需要通过错误堆栈查看是否有死锁的场景。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-universal.md b/zh-cn/application-dev/reference/errorcodes/errorcode-universal.md new file mode 100644 index 0000000000000000000000000000000000000000..9ce15b0692b5bea93f3b82932dd3a5290a0ef8a9 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-universal.md @@ -0,0 +1,73 @@ +# 通用误码 + +## 201 权限校验失败 + +**错误信息** + +Permission verification failed, usually the result returned by VerifyAccessToken. + +**错误描述** + +权限校验失败,应用无权限使用该API,需要申请权限。 + +**可能原因** + +该错误码表示权限校验失败,通常为没有权限,却调用了需要权限的API。 + +**处理步骤** + +请检查是否有调用API的权限。 + +## 202 系统API权限校验失败 + +**错误信息** + +Permission verification failed, application which is not a system application uses system API. + +**错误描述** + +权限校验失败,非系统应用使用了系统API。 + +**可能原因** + +非系统应用,使用了系统API,请校验是否使用了系统API。 + +**处理步骤** + +请检查是否调用了系统API,并且去掉。 + +## 401 参数检查失败 + +**错误信息** + +BusinessError 401: Parameter error. The type of "${参数名}" must be ${正确的类型}[or ${其他正确的输入}]. + +**错误描述** + +参数检查失败,包括必选参数没有传入,参数类型错误。 + +**可能原因** + +必选参数没有传入,或者参数类型错误。 + +**处理步骤** + +请检查必选参数是否没有传入,或者传的参数类型是否错误。 + +## 801 该设备不支持此API + +**错误信息** + +BusinessError 801: Capability not supported. function ${函数名} can not work correctly due to limited device capabilities. + +**错误描述** + +该设备不支持此API,通常用于在设备已支持该SysCap时,针对其少量的API的支持处理。 + +**可能原因** + +该设备不支持此API。 + +**处理步骤** + +请检查设备是否支持使用的API。 diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-usb.md b/zh-cn/application-dev/reference/errorcodes/errorcode-usb.md similarity index 100% rename from zh-cn/application-dev/reference/errorcodes/errcode-usb.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-usb.md diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md b/zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md similarity index 83% rename from zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md rename to zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md index 559f2ba4a7e76e966212fc53bb96e88270e1c09a..d7038b823654fdaa4601f053f7f808a006113e46 100755 --- a/zh-cn/application-dev/reference/errorcodes/errorcodes-zlib.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-zlib.md @@ -16,7 +16,8 @@ The input source file is invalid. **处理步骤** -检查源文件是否存在。 +1. 检查源文件是否存在。 +2. 检查待压缩的文件路径是否存在,并且路径是否在正确的沙箱路径下。 ## 900002 传入的目标文件错误 diff --git a/zh-cn/application-dev/reference/native-apis/_drawing.md b/zh-cn/application-dev/reference/native-apis/_drawing.md index 9c9772d11d13c346cd19d1d5473f51b3e49d571c..64ce6a9a7ec1cf306fbe9647082038f249ea21b5 100644 --- a/zh-cn/application-dev/reference/native-apis/_drawing.md +++ b/zh-cn/application-dev/reference/native-apis/_drawing.md @@ -2154,7 +2154,7 @@ void OH_Drawing_SetTextStyleFontFamilies (OH_Drawing_TextStyle * , int , const c | -------- | -------- | | OH_Drawing_TextStyle | 指向OH_Drawing_TextStyle对象的指针 | | int | 字体名称数量 | -| char | 指向字体类型的指针 | +| fontFamilies | 指向字体类型的指针数组 | **自从:** diff --git a/zh-cn/application-dev/reference/native-apis/_mind_spore.md b/zh-cn/application-dev/reference/native-apis/_mind_spore.md index 061eece1bfb48ef62a390c389e1031b41aa04093..9812ce51e5efdaff2b432b82bab3386f99f698b8 100644 --- a/zh-cn/application-dev/reference/native-apis/_mind_spore.md +++ b/zh-cn/application-dev/reference/native-apis/_mind_spore.md @@ -84,7 +84,7 @@ | [OH_AI_ContextDestroy](#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 | | [OH_AI_ContextSetThreadNum](#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 | | [OH_AI_ContextGetThreadNum](#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 | -| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 | +| [OH_AI_ContextSetThreadAffinityMode](#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 | | [OH_AI_ContextGetThreadAffinityMode](#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 | | [OH_AI_ContextSetThreadAffinityCoreList](#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list,
size_t core_num) | 设置运行时线程绑定CPU核心的列表。 | | [OH_AI_ContextGetThreadAffinityCoreList](#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 | @@ -649,14 +649,14 @@ OH_AI_API void OH_AI_ContextSetThreadAffinityMode (OH_AI_ContextHandle context, **描述:** -设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 +设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 **参数:** | 名称 | 描述 | | -------- | -------- | | context | 指向上下文信息实例的[OH_AI_ContextHandle](#oh_ai_contexthandle)。 | -| mode | 绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为小核优先。 | +| mode | 绑核策略。一共有三种策略,0为不绑核, 1为大核优先, 2为中核优先。 | ### OH_AI_ContextSetThreadNum() diff --git a/zh-cn/application-dev/reference/native-apis/context_8h.md b/zh-cn/application-dev/reference/native-apis/context_8h.md index 3e8e1c05f91e5105290f48aa695ee42a60584f61..65a629a526bf12d6d37c7591cbadc2cf114ab8ce 100644 --- a/zh-cn/application-dev/reference/native-apis/context_8h.md +++ b/zh-cn/application-dev/reference/native-apis/context_8h.md @@ -33,7 +33,7 @@ | [OH_AI_ContextDestroy](_mind_spore.md#oh_ai_contextdestroy) (OH_AI_ContextHandle \*context) | 释放上下文对象。 | | [OH_AI_ContextSetThreadNum](_mind_spore.md#oh_ai_contextsetthreadnum) (OH_AI_ContextHandle context, int32_t thread_num) | 设置运行时的线程数量。 | | [OH_AI_ContextGetThreadNum](_mind_spore.md#oh_ai_contextgetthreadnum) (const OH_AI_ContextHandle context) | 获取线程数量。 | -| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大核与小核。 | +| [OH_AI_ContextSetThreadAffinityMode](_mind_spore.md#oh_ai_contextsetthreadaffinitymode) (OH_AI_ContextHandle context, int mode) | 设置运行时线程绑定CPU核心的策略,按照CPU物理核频率分为大、中、小三种类型的核心,并且仅需绑大核或者绑中核,不需要绑小核。 | | [OH_AI_ContextGetThreadAffinityMode](_mind_spore.md#oh_ai_contextgetthreadaffinitymode) (const OH_AI_ContextHandle context) | 获取运行时线程绑定CPU核心的策略。 | | [OH_AI_ContextSetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextsetthreadaffinitycorelist) (OH_AI_ContextHandle context, const int32_t \*core_list, size_t core_num) | 设置运行时线程绑定CPU核心的列表。 | | [OH_AI_ContextGetThreadAffinityCoreList](_mind_spore.md#oh_ai_contextgetthreadaffinitycorelist) (const OH_AI_ContextHandle context, size_t \*core_num) | 获取CPU绑核列表。 | diff --git a/zh-cn/application-dev/security/Readme-CN.md b/zh-cn/application-dev/security/Readme-CN.md index 5369b1392693a9a7ea842d1f9f96bd6bc2243788..af608f4bf4e0ca46bad71e67b842062b5027842b 100644 --- a/zh-cn/application-dev/security/Readme-CN.md +++ b/zh-cn/application-dev/security/Readme-CN.md @@ -17,3 +17,4 @@ - Hap包签名工具 - [Hap包签名工具概述](hapsigntool-overview.md) - [Hap包签名工具指导](hapsigntool-guidelines.md) + - [HarmonyAppProvision配置文件](app-provision-structure.md) diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 051aa7c462ad6a5beb732f4d14d4e1f64b673f7f..342754163710cdcd1481f51b796fffd56400bce0 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -113,7 +113,7 @@ 如上述示例所示,权限"ohos.permission.PERMISSION2"的权限等级为system_basic,高于此时应用的APL等级,开发者的最佳做法是使用ACL方式。 -在配置文件声明的基础上,应用还需要在Profile文件中声明不满足申请条件部分的权限。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 +在配置文件声明的基础上,应用还需要在Profile文件中声明不满足申请条件部分的权限。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 该场景中,开发者应该在字段"acls"中做声明如下: @@ -167,6 +167,30 @@ > **说明:** > 动态授权申请接口的使用详见[API参考](../reference/apis/js-apis-ability-context.md)。 +## user_grant权限预授权 +当前正常情况下,user_grant类型的权限默认不授权,需要时应通过拉起弹框由用户确认是否授予。对于一些预置应用,比如截屏应用,不希望出现弹框,则可以通过预授权的方式完成user_grant类型权限的授权。[预置配置文件](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json)在设备上的路径为system/etc/app/install_list_permission.json,设备开机启动时会读取该配置文件,在应用安装会对在文件中配置的user_grant类型权限授权。当前仅支持预置应用配置该文件。 +预授权配置文件字段内容包括bundleName、app_signature、permissions。 +1. 这里的权限仅对user_grant类型的权限生效[查看权限等级和类型](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/permission-list.md)。 +2. userCancellable配置为true,表示支持用户取消授权,为false则表示不支持用户取消授权。 + +```json +[ + { + "bundleName": "com.ohos.myapplication", // 包名 + "app_signature":[], // 指纹信息 + "permissions":[ + { + "name":"xxxx", // 权限名,不可缺省 + "userCancellable":false // 用户不可取消授权,不可缺省 + }, + { + "name":"yyy", // 权限名,不可缺省 + "userCancellable":true // 用户可取消授权,不可缺省 + } + ] + } +] +``` ## 相关实例 针对访问控制,有以下相关实例可供参考: diff --git a/zh-cn/application-dev/security/accesstoken-overview.md b/zh-cn/application-dev/security/accesstoken-overview.md index 9a37da6075ada7be976f6221f0b5c7e67d72ce39..5aae9b27ec59c39aac848a0c3653a27cc393b5fe 100644 --- a/zh-cn/application-dev/security/accesstoken-overview.md +++ b/zh-cn/application-dev/security/accesstoken-overview.md @@ -90,7 +90,7 @@ ATM (AccessTokenManager) 是OpenHarmony上基于AccessToken构建的统一的应 示例如下: -该示例仅涉及修改"apl"字段,其余信息请根据实际情况。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 +该示例仅涉及修改"apl"字段,其余信息请根据实际情况。Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 ```json { @@ -218,4 +218,4 @@ ACL方式的工作流程可以参考[ACL方式使用说明](#acl方式使用说 } ``` -Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](../quick-start/app-provision-structure.md)。 \ No newline at end of file +Profile文件的字段说明可参考[HarmonyAppProvision配置文件的说明](app-provision-structure.md)。 diff --git a/zh-cn/application-dev/quick-start/app-provision-structure.md b/zh-cn/application-dev/security/app-provision-structure.md similarity index 81% rename from zh-cn/application-dev/quick-start/app-provision-structure.md rename to zh-cn/application-dev/security/app-provision-structure.md index 1e97d44baf1f06e4405f80070fe71c4b6d50679f..a0bc15058289791d98d02b48bb1ff499d79e5faf 100644 --- a/zh-cn/application-dev/quick-start/app-provision-structure.md +++ b/zh-cn/application-dev/security/app-provision-structure.md @@ -63,28 +63,28 @@ HarmonyAppProvision文件示例: | 属性名称 | 含义 | 数据类型 | 是否必选 | 是否可缺省 | | ------------------------ | ------------------------------- | ------- | -------- | --------- | | developer-id | 表示开发者的唯一ID号,用于OEM厂商标识开发者,开源社区版本该属性不做强制要求。 | 字符串 | 必选 | 不可缺省 | -| development-certificate | 表示[调试证书](../security/hapsigntool-guidelines.md)的信息。 | 数值 | 当type属性为debug时,该属性必选;否则,该属性可选。 | 不可缺省 | -| distribution-certificate | 表示[发布证书](../security/hapsigntool-guidelines.md)的信息。 | 数值 | 当type属性为release时,该标签必选;否则,该标签可选。 | 不可缺省 | +| development-certificate | 表示[调试证书](hapsigntool-guidelines.md)的信息。 | 数值 | 当type属性为debug时,该属性必选;否则,该属性可选。 | 不可缺省 | +| distribution-certificate | 表示[发布证书](hapsigntool-guidelines.md)的信息。 | 数值 | 当type属性为release时,该标签必选;否则,该标签可选。 | 不可缺省 | | bundle-name | 表示应用程序的包名。 | 字符串 | 必选 | 不可缺省 | -| apl | 表示应用程序的[apl级别](../security/accesstoken-overview.md),系统预定义的apl包括:normal、system_basic和system_core。 | 字符串 | 必选 | 不可缺省 | -| app-feature | 表示应用程序的类型,系统预定义的app-feature包括hos_system_app (系统应用)和hos_normal_app(普通应用)。 | 字符串 | 必选 | 不可缺省 | +| apl | 表示应用程序的[apl级别](accesstoken-overview.md),系统预定义的apl包括:normal、system_basic和system_core。 | 字符串 | 必选 | 不可缺省 | +| app-feature | 表示应用程序的类型,系统预定义的app-feature包括hos_system_app (系统应用)和hos_normal_app(普通应用)。只有系统应用才允许调用系统API,普通应用调用系统API可能会调用失败或运行异常。 | 字符串 | 必选 | 不可缺省 | ### acls对象内部结构 -acls对象包含已授权的[acl权限](../security/accesstoken-overview.md)。需要指出的是,开发者仍然需要在应用包配置文件([config.json](package-structure.md))将acls权限信息填写到reqPermissions属性中。 +acls对象包含已授权的[acl权限](accesstoken-overview.md)。需要指出的是,开发者仍然需要在应用包配置文件([config.json](../quick-start/package-structure.md))将acls权限信息填写到reqPermissions属性中。 表4 acls对象的内部结构 | 属性名称 | 含义 | 数据类型 | 是否必选 | 是否可缺省 | | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| allowed-acls | 表示已授权的[acl权限](../security/accesstoken-overview.md)列表。 | 字符串数组 | 可选 | 不可缺省 | +| allowed-acls | 表示已授权的[acl权限](accesstoken-overview.md)列表。 | 字符串数组 | 可选 | 不可缺省 | ### permissions对象内部结构 -permissions对象包含允许使用的受限敏感权限。不同于acls对象,permissions对象中的权限仅代表应用允许使用该敏感权限,权限最终由用户运行时授权。需要指出的是,开发者仍然需要在应用包配置文件([config.json](package-structure.md))将permissions权限信息填写到reqPermissions属性中。 +permissions对象包含允许使用的受限敏感权限。不同于acls对象,permissions对象中的权限仅代表应用允许使用该敏感权限,权限最终由用户运行时授权。需要指出的是,开发者仍然需要在应用包配置文件([config.json](../quick-start/package-structure.md))将permissions权限信息填写到reqPermissions属性中。 表5 permissions对象的内部结构 | 属性名称 | 含义 | 数据类型 | 是否必选 | 是否可缺省 | | ------------------------ | ------------------------------- | ------- | ------- | --------- | -| restricted-permissions | 表示允许使用的[受限敏感权限](../security/accesstoken-overview.md)。 | 字符串数组 | 可选 | 不可缺省 | +| restricted-permissions | 表示允许使用的[受限敏感权限](accesstoken-overview.md)。 | 字符串数组 | 可选 | 不可缺省 | ### debug-info对象内部结构 debug-info对象包含应用调试场景下的信息,主要是设备管控的信息。 diff --git a/zh-cn/application-dev/security/hapsigntool-overview.md b/zh-cn/application-dev/security/hapsigntool-overview.md index c588b7ab0909530bffcf9c5b5149ca32394e1be4..0b5b41070fbecfe753411a5fe6b333484521fb04 100644 --- a/zh-cn/application-dev/security/hapsigntool-overview.md +++ b/zh-cn/application-dev/security/hapsigntool-overview.md @@ -26,11 +26,10 @@ Hap包签名工具支持本地签名需求的开发,为OpenHarmony应用提供 - Profile文件: - [HarmonyAppProvision配置文件](../quick-start/app-provision-structure.md),hap包中的描述文件,该描述文件描述了已授权的证书权限和设备ID信息等信息。 + [HarmonyAppProvision配置文件](app-provision-structure.md),hap包中的描述文件,该描述文件描述了已授权的证书权限和设备ID信息等信息。 ## 约束与限制 - Hap包签名工具基于Java语言开发,需要Java8以上Java环境运行。 - 一键签名等脚本文件基于Python语言开发,使用需配置环境python3.5及以上。 - diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index 15d28253e1e074bf5df91d00f863b5f400dfca96..35b64f31babadb390bbcf544ed6b24d8c3ed70db 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -4,7 +4,7 @@ HUKS(OpenHarmony Universal KeyStore,OpenHarmony通用密钥库系统)向 > **说明** > -> 本开发指导基于API version 9,仅适用于eTS语言开发 +> 本开发指导基于API version 9,仅适用于ArkTS语言开发 ### **前提条件** diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index d056945f608fe9681ff0f8bc555f583527319bd7..03b3ea481ba6732cf777300b0c70b311714ffb5f 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -94,9 +94,10 @@ | ohos.permission.MANAGE_SECURE_SETTINGS | system_basic | system_grant | TRUE | 允许应用修改安全类系统设置。 | | ohos.permission.READ_DFX_SYSEVENT | system_basic | system_grant | FALSE | 允许获取所有应用账号信息。 | | ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN | system_core | system_grant | TRUE | 允许应用激活设备管理员应用。 | -| ohos.permission.SET_ENTERPRISE_INFO | system_basic | system_grant | FALSE | 允许设备管理员应用设置企业信息。 | -| ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT | system_basic | system_grant | FALSE | 允许设备管理员应用订阅管理事件。 | -| ohos.permission.ENTERPRISE_SET_DATETIME | system_basic | system_grant | FALSE | 允许设备管理员应用设置系统时间。 | +| ohos.permission.SET_ENTERPRISE_INFO | system_basic | system_grant | TRUE | 允许设备管理员应用设置企业信息。 | +| ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT | system_basic | system_grant | TRUE | 允许设备管理员应用订阅管理事件。 | +| ohos.permission.ENTERPRISE_SET_DATETIME | system_basic | system_grant | TRUE | 允许设备管理员应用设置系统时间。 | +| ohos.permission.ENTERPRISE_GET_DEVICE_INFO | system_basic | system_grant | TRUE | 允许设备管理员读取设备信息。 | | ohos.permission.NFC_TAG | normal | system_grant | FALSE | 允许应用读取Tag卡片。 | | ohos.permission.NFC_CARD_EMULATION | normal | system_grant | FALSE | 允许应用实现卡模拟功能。 | | ohos.permission.PERMISSION_USED_STATS | system_basic | system_grant | TRUE | 允许系统应用访问权限使用记录。 | @@ -160,4 +161,5 @@ | ohos.permission.MOUNT_FORMAT_MANAGER | system_basic | system_grant | FALSE | 允许应用对外卡进行格式化操作。 | | ohos.permission.STORAGE_MANAGER | system_basic | system_grant | TRUE | 允许应用调用storage manager服务中对空间统计以及卷信息的查询接口。 | | ohos.permission.BACKUP | system_basic | system_grant | TRUE | 允许应用拥有备份恢复能力。 | -| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | 允许文件管理类应用通过FAF框架访问公共数据文件。 | \ No newline at end of file +| ohos.permission.FILE_ACCESS_MANAGER | system_basic | system_grant | TRUE | 允许文件管理类应用通过FAF框架访问公共数据文件。 | +| ohos.permission.MANAGE_AUDIO_CONFIG | system_basic | system_grant | TRUE | 允许应用进行全局麦克风静音等操作。 | \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md index 9d50c74836d61261433ced3a5a6b30e10163f446..b6e1859e17ddf15c6056de16bab6b148a520900c 100644 --- a/zh-cn/application-dev/task-management/continuous-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/continuous-task-dev-guide.md @@ -19,17 +19,17 @@ **表2** 后台模式类型 -| 参数名 | id值 | 描述 | 配置项 | -| ----------------------- | ---- | -------------- | --------------------- | -| DATA_TRANSFER | 1 | 数据传输 | dataTransfer | -| AUDIO_PLAYBACK | 2 | 音频播放 | audioPlayback | -| AUDIO_RECORDING | 3 | 录音 | audioRecording | -| LOCATION | 4 | 定位导航 | location | -| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | bluetoothInteraction | -| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | multiDeviceConnection | -| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | wifiInteraction | -| VOIP | 8 | 音视频通话(系统保留) | voip | -| TASK_KEEPING | 9 | 计算任务(仅供特定设备使用) | taskKeeping | +| 参数名 | 描述 | 配置项 | +| ----------------------- | -------------- | --------------------- | +| DATA_TRANSFER | 数据传输 | dataTransfer | +| AUDIO_PLAYBACK | 音频播放 | audioPlayback | +| AUDIO_RECORDING | 录音 | audioRecording | +| LOCATION | 定位导航 | location | +| BLUETOOTH_INTERACTION | 蓝牙相关 | bluetoothInteraction | +| MULTI_DEVICE_CONNECTION | 多设备互联 | multiDeviceConnection | +| WIFI_INTERACTION | WLAN相关(系统保留) | wifiInteraction | +| VOIP | 音视频通话(系统保留) | voip | +| TASK_KEEPING | 计算任务(仅供特定设备使用) | taskKeeping | ## 开发步骤 diff --git a/zh-cn/application-dev/task-management/transient-task-dev-guide.md b/zh-cn/application-dev/task-management/transient-task-dev-guide.md index 86ca50c4f7c8c8a3d0d606280ac2dd520e941531..18c3030bfe2fec8941c386c76a1078da52394cf9 100644 --- a/zh-cn/application-dev/task-management/transient-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/transient-task-dev-guide.md @@ -18,7 +18,7 @@ | 接口名 | 描述 | | ---------------------------------------- | ---------------------------------------- | -| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为180000,低电量时默认值为60000。 | +| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | 后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为3分钟,低电量时默认值为1分钟。 | | getRemainingDelayTime(requestId: number): Promise<number> | 获取应用程序进入挂起状态前的剩余时间。
使用Promise形式返回。 | | cancelSuspendDelay(requestId: number): void | 取消延迟挂起。 | diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif index 2283e46371317539004c0007886500c1a81dd83a..f59b87e0afc79eafbddef8de2a264cf2f41b97c7 100755 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001063148757.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png index 5000709da6dfadee24e10fdbd679b3a28e46578b..d39e5026790f8d85866b0e293f6b53ad455ff1c4 100755 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001071134933.png differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif index f470f5261becb6c2d7b30f691a0794db2b1feb93..75abb6f81315b55e677acd8c4d943b2f22d76fff 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001217168141.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif index d669cf40b97891ba3853be28574dceae172fe138..0be34d5b9598c7e03132b08e030fd71d977886b5 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001220635011.gif differ diff --git a/zh-cn/application-dev/ui/js-framework-syntax-css.md b/zh-cn/application-dev/ui/js-framework-syntax-css.md index a3961ebc73492776031d337f8a6c0be62925a9bb..16d19b5d25d8dd79a44f4398134426c32a6e2fcf 100644 --- a/zh-cn/application-dev/ui/js-framework-syntax-css.md +++ b/zh-cn/application-dev/ui/js-framework-syntax-css.md @@ -100,7 +100,7 @@ div { color: #007dff; } /* 对class="container"的组件下的直接后代text设置样式 */ -.container > text { +.container > text { color: #fa2a2d; } ``` diff --git a/zh-cn/application-dev/ui/js-framework-syntax-js.md b/zh-cn/application-dev/ui/js-framework-syntax-js.md index 6a1484b0d9d49c295ff7c99390d547d4bc589c81..f2dd1f51f3f802d66ce2811b4585ef57fd4e7f89 100644 --- a/zh-cn/application-dev/ui/js-framework-syntax-js.md +++ b/zh-cn/application-dev/ui/js-framework-syntax-js.md @@ -248,7 +248,7 @@ export default {
parent component click - hello parent component! + hello parent component!
``` @@ -257,11 +257,11 @@ export default { // parent.js export default { data: { - show: false, + showValue: false, text: 'I am parent component!', }, parentClicked () { - this.show = !this.show; + this.showValue = !this.showValue; console.info('parent component get parent text'); console.info(`${this.$parent().text}`); console.info("parent component get child function"); diff --git a/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md b/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md index ed82f95ad103deb99230ef795154d7f268b2bac0..01007ff725f78cf9e78507cf6d1bf2b4b2ddc7c3 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md +++ b/zh-cn/application-dev/ui/ui-js-animate-attribute-style.md @@ -26,8 +26,10 @@ justify-content: center; align-items: center; flex-direction: column; + width: 100%; + height: 100%; } -.fade{ +.fade { width: 30%; height: 200px; left: 35%; @@ -35,13 +37,13 @@ position: absolute; animation: 2s change infinite friction; } -.bigger{ +.bigger { width: 20%; height: 100px; background-color: blue; animation: 2s change1 infinite linear-out-slow-in; } -text{ +text { width: 100%; height: 100%; text-align: center; @@ -61,7 +63,7 @@ text{ } } /* 父组件大小变化 */ -@keyframes change1{ +@keyframes change1 { 0% { width: 20%; height: 100px; @@ -70,11 +72,11 @@ text{ width: 80%; height: 200px; } -} +} /* 子组件文字缩放 */ -@keyframes change2{ - 0%{ - transform: scale(0); +@keyframes change2 { + 0% { + transform: scale(0); } 100% { transform: scale(1.5); diff --git a/zh-cn/application-dev/ui/ui-js-animate-component.md b/zh-cn/application-dev/ui/ui-js-animate-component.md index 859fb01701d252c51c60600f2dd283bd62fbd1b5..4588277ce58dd416ba31db834e2edf841cbdac51 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-component.md +++ b/zh-cn/application-dev/ui/ui-js-animate-component.md @@ -83,6 +83,7 @@ export default { justify-content: center; align-items: center; width: 100%; + height: 100%; } .box{ width: 200px; @@ -103,7 +104,7 @@ export default { onInit() { this.options = { duration: 4000, - }; + } this.keyframes = [ { transform: { @@ -127,11 +128,11 @@ export default { width: 300, height: 300 } - ]; + ] }, Show() { - this.animation = this.$element('content').animate(this.keyframes, this.options); - this.animation.play(); + this.animation = this.$element('content').animate(this.keyframes, this.options) + this.animation.play() } } ``` @@ -225,16 +226,16 @@ animation对象支持动画事件和动画方法。可以通过添加开始和 ```html
-
-
-
- - -
-
- - -
+
+
+
+ + +
+
+ + +
``` @@ -244,6 +245,8 @@ animation对象支持动画事件和动画方法。可以通过添加开始和 flex-direction: column; align-items: center; justify-content: center; + width: 100%; + height: 100%; } button{ width: 200px; @@ -272,75 +275,64 @@ button{ ```js // xxx.js -import prompt from '@system.prompt'; export default { - data: { - animation: '', - }, - onInit() { - }, - onShow() { - var options = { - duration: 1500, - easing:'ease-in', - elay:5, - direction:'normal', - iterations:2 - }; - var frames = [ - { - transform: { - translate: '-150px -0px' - }, - opacity: 0.1, - offset: 0.0, - width: 200, - height: 200, - }, - { - transform: { - translate: '150px 0px' - }, - opacity: 1.0, - offset: 1.0, - width: 300, - height: 300, - } - ]; - this.animation = this.$element('content').animate(frames, options); - this.animation.onstart = function(){ - prompt.showToast({ - message: "start" - }); - }; //添加开始事件 - this.animation.onrepeat = function(){ - prompt.showToast({ - message: " repeated" - }); - };//添加重播事件 - this.animation.oncancel = function(){ - prompt.showToast({ - message: "canceled" - }); - };//添加取消事件 - this.animation.onfinish = function(){ - prompt.showToast({ - message: "finish" - }); - };//添加完成事件 - }, - playAnimation() { - this.animation.play();//调用播放开始的方法 - }, - pauseAnimation() { - this.animation.pause();//调用播放暂停的方法 - }, - reverseAnimation() { - this.animation.reverse();//调用播放倒放的方法 - }, - cancelAnimation() { - this.animation.cancel();//调用播放取消的方法 - } + data: { + animation: '', + }, + onShow() { + var options = { + duration: 1500, + easing:'ease-in', + delay:5, + direction:'normal', + iterations:2 + }; + var frames = [ + { + transform: { + translate: '-150px -0px' + }, + opacity: 0.1, + offset: 0.0, + width: 200, + height: 200, + }, + { + transform: { + translate: '150px 0px' + }, + opacity: 1.0, + offset: 1.0, + width: 300, + height: 300, + } + ]; + this.animation = this.$element('content').animate(frames, options); + this.animation.onstart = function() { + console.info('animation start') + } // 添加开始事件 + this.animation.onrepeat = function() { + console.info('animation repeated') + } // 添加重播事件 + this.animation.oncancel = function() { + console.info('animation canceled') + } // 添加取消事件 + this.animation.onfinish = function() { + console.info('animation finish') + } // 添加完成事件 + }, + playAnimation() { + this.animation.play() // 调用播放开始的方法 + }, + pauseAnimation() { + this.animation.pause() // 调用播放暂停的方法 + }, + reverseAnimation() { + this.animation.reverse() // 调用播放倒放的方法 + }, + cancelAnimation() { + this.animation.cancel() // 调用播放取消的方法 + } } ``` diff --git a/zh-cn/application-dev/ui/ui-js-animate-svg.md b/zh-cn/application-dev/ui/ui-js-animate-svg.md index beed6f9df285dc966a03ea46f63085d962fc16be..fee61aa781b123426fbbc5bc20324725fb99952b 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-svg.md +++ b/zh-cn/application-dev/ui/ui-js-animate-svg.md @@ -65,7 +65,7 @@ ## animateTransform动画 -在Svg的子组件[animateMotion](../reference/arkui-js/js-components-svg-animatetransform.md)中,通过attributeName绑定transform属性,type设置动画类型,from设置开始值,to设置结束值。 +在Svg的子组件[animateTransform](../reference/arkui-js/js-components-svg-animatetransform.md)中,通过attributeName绑定transform属性,type设置动画类型,from设置开始值,to设置结束值。 ```html diff --git a/zh-cn/application-dev/ui/ui-js-animate-transform.md b/zh-cn/application-dev/ui/ui-js-animate-transform.md index c189f6380ba1191a159fcbfeccc562c73383e015..18e1b65108dddef9fc99caabbf0feffe2f4b131d 100644 --- a/zh-cn/application-dev/ui/ui-js-animate-transform.md +++ b/zh-cn/application-dev/ui/ui-js-animate-transform.md @@ -38,8 +38,8 @@ height: 428px; background-color: #860303; transform: rotate(45deg); - margin-top: 230px; - margin-left: 266px; + margin-top: 284px; + margin-left: 148px; } .content{ margin-top: 500px; @@ -52,7 +52,7 @@ width: 100px; height: 150px; background-color: #1033d9; - transform: translate(150px,-150px); + transform: translate(150px,-137px); } .window{ z-index: 1; @@ -85,7 +85,7 @@ height: 100px; border-radius: 15px; background-color: #9a7404; - transform: translate(200px,-830px) skewX(-5deg); + transform: translate(200px,-710px) skewX(-5deg); } ``` @@ -202,22 +202,24 @@ display: flex; align-items: center; justify-content: center; + width: 100%; + height: 100%; } -.rect{ +.rect { width: 100px; height: 100px; animation: rotate 3s infinite; margin-left: 100px; } -.rect1{ +.rect1 { background-color: #f76160; } -.rect2{ +.rect2 { background-color: #60f76f; /* 改变原点位置*/ transform-origin: 10% 10px; } -.rect3{ +.rect3 { background-color: #6081f7; /* 改变原点位置*/ transform-origin: right bottom; @@ -231,7 +233,7 @@ } } /* 3d示例样式 */ -.rotate3d{ +.rotate3d { margin-top: 150px; flex-direction: column; background-color:#F1F3F5; @@ -242,36 +244,36 @@ border-radius: 300px; border: 1px solid #ec0808; } -.content{ +.content { padding-top: 150px; display: flex; align-items: center; justify-content: center; } /* react4 react5 翻转形成眼睛 */ -.rect4{ +.rect4 { width: 100px; height: 100px; - animation: rotate3d1 17ms infinite; + animation: rotate3d1 1000ms infinite; background: linear-gradient(#e6c4ec, #be15d9) } -.rect5{ +.rect5 { width: 100px; height: 100px; - animation: rotate3d1 17ms infinite; + animation: rotate3d1 1000ms infinite; margin-left: 100px; background: linear-gradient(#e6c4ec, #be15d9) } -.mouse{ +.mouse { margin-top: 150px; width: 200px; height: 100px; border-radius: 50px; border: 1px solid #e70303; - animation: rotate3d2 17ms infinite; + animation: rotate3d2 1000ms infinite; } /* 眼睛的动效 */ -@keyframes rotate3d1{ +@keyframes rotate3d1 { 0% { transform:rotate3d(0,0,0,0deg) } @@ -283,7 +285,7 @@ } } /* 嘴的动效 */ -@keyframes rotate3d2{ +@keyframes rotate3d2 { 0% { transform:rotate3d(0,0,0,0deg) } @@ -435,6 +437,8 @@ matrix是一个入参为六个值的矩阵,6个值分别代表:scaleX, skewY background-color:#F1F3F5; display: flex; justify-content: center; + width: 100%; + height: 100%; } .rect{ width: 100px; @@ -479,6 +483,8 @@ transform可以设置多个值并且多个值可同时设置,下面案例中 ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction:column; background-color:#F1F3F5; padding:50px; diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-animation.md b/zh-cn/application-dev/ui/ui-js-building-ui-animation.md index 03c99a2899ceea6680d97a434e3e0d527a8b7ef5..ca34f39427ebf3f32af73ad860fcc9df61eead6d 100755 --- a/zh-cn/application-dev/ui/ui-js-building-ui-animation.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-animation.md @@ -27,12 +27,14 @@ ```css /* xxx.css */ .container { + width: 100%; flex-direction: column; align-items: center; } .translate { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform: translate(200px); @@ -40,14 +42,16 @@ .rotate { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform-origin: 200px 100px; - transform: rotateX(45deg); + transform: rotate(45deg); } .scale { height: 150px; width: 300px; + margin: 50px; font-size: 50px; background-color: #008000; transform: scaleX(1.5); @@ -81,28 +85,24 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 ```html
- animation-name -
- color -
-
- opacity -
- +
+ color +
+
+ opacity +
+
``` ```css /* xxx.css */ .item-container { - margin-right: 60px; - margin-left: 60px; + margin: 60px; flex-direction: column; } -.header { - margin-bottom: 20px; -} .item { + width: 80%; background-color: #f76160; } .txt { @@ -112,6 +112,7 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 } .button { width: 200px; + margin: 10px; font-size: 30px; background-color: #09ba07; } @@ -141,7 +142,7 @@ animation样式需要在css文件中先定义keyframe,在keyframe中设置动 } ``` -``` +```js // xxx.js export default { data: { @@ -153,7 +154,7 @@ export default { this.opacityParam = ''; this.colorParam = 'color'; this.opacityParam = 'opacity'; - }, + } } ``` diff --git a/zh-cn/application-dev/ui/ui-js-component-tabs.md b/zh-cn/application-dev/ui/ui-js-component-tabs.md index 69b08d7edb002f75dadb8631e1d1a447444ca882..78a71ea6ded6be188e0c8b042d34ed29d04470aa 100644 --- a/zh-cn/application-dev/ui/ui-js-component-tabs.md +++ b/zh-cn/application-dev/ui/ui-js-component-tabs.md @@ -15,7 +15,7 @@ tabs是一种常见的界面导航结构。通过页签容器,用户可以快 item1 item2 - +
content1
@@ -35,6 +35,10 @@ tabs是一种常见的界面导航结构。通过页签容器,用户可以快 align-items: center; background-color: #F1F3F5; } +.tabContent{ + width: 100%; + height: 100%; +} .text{ width: 100%; height: 100%; diff --git a/zh-cn/application-dev/ui/ui-js-components-canvas.md b/zh-cn/application-dev/ui/ui-js-components-canvas.md index 9410a9d4ceda10a4fd7cb2169ca71afe7ec51a6c..06bc9dc1885d03d75e4b0acd345874aaadc4d4e0 100644 --- a/zh-cn/application-dev/ui/ui-js-components-canvas.md +++ b/zh-cn/application-dev/ui/ui-js-components-canvas.md @@ -20,6 +20,8 @@ Canvas组件提供画布,用于自定义绘制图形。具体用法请参考[C ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; diff --git a/zh-cn/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md b/zh-cn/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md index 85a737f4d78f8e9ec6aa60130dadf788c06090bc..dc01f3b2b906e931dada6c436f06a95344bf2fb7 100644 --- a/zh-cn/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md @@ -27,6 +27,8 @@ ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -227,6 +229,8 @@ export default { ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -324,6 +328,8 @@ export default { ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -448,6 +454,8 @@ export default { ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -591,6 +599,8 @@ export default { ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; background-color: #F1F3F5; align-items: center; @@ -760,6 +770,8 @@ save方法可对画笔样式进行存储,restore可对存储的画笔进行恢 ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; background-color: #F1F3F5; align-items: center; diff --git a/zh-cn/application-dev/ui/ui-js-components-form.md b/zh-cn/application-dev/ui/ui-js-components-form.md index e00ca0ea9bbc88eb8fe9bd8182f027baccffd4c0..836f46f8fbbfce291ccd8144f8f6098526d0c925 100644 --- a/zh-cn/application-dev/ui/ui-js-components-form.md +++ b/zh-cn/application-dev/ui/ui-js-components-form.md @@ -183,6 +183,8 @@ export default{ ```css /* index.css */ .container { + width: 100%; + height: 100%; flex-direction:column; align-items:center; background-color:#F1F3F5; diff --git a/zh-cn/application-dev/ui/ui-js-components-grid.md b/zh-cn/application-dev/ui/ui-js-components-grid.md index fcaaef6774c02e2fe0857c78291d4de066f1eabf..1d74d0cb6541165ddf74b309ad4fbaed8ef4a212 100644 --- a/zh-cn/application-dev/ui/ui-js-components-grid.md +++ b/zh-cn/application-dev/ui/ui-js-components-grid.md @@ -28,6 +28,7 @@ flex-direction: column; background-color: #F1F3F5; width: 100%; + height: 100%; justify-content: center; align-items: center; } @@ -67,6 +68,7 @@ grid-container点击组件调用getColumns、getColumnWidth、getGutterWidth方 flex-direction: column; background-color: #F1F3F5; width: 100%; + height: 100%; justify-content: center; align-items: center; } @@ -154,6 +156,7 @@ export default { flex-direction: column; background-color: #F1F3F5; width: 100%; + height: 100%; justify-content: center; align-items: center; } @@ -203,6 +206,7 @@ text{ flex-direction: column; background-color: #F1F3F5; width: 100%; + height: 100%; } text{ color: #0a0aef; diff --git a/zh-cn/application-dev/ui/ui-js-components-offscreencanvas.md b/zh-cn/application-dev/ui/ui-js-components-offscreencanvas.md index 21eb77734b4209734968bc7f73c8f99a40b865a8..03a50a6e2c1c4a133779f0ae31c5623c976ac832 100644 --- a/zh-cn/application-dev/ui/ui-js-components-offscreencanvas.md +++ b/zh-cn/application-dev/ui/ui-js-components-offscreencanvas.md @@ -26,6 +26,8 @@ ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -106,6 +108,8 @@ export default { ```css /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; diff --git a/zh-cn/application-dev/ui/ui-js-components-path2d.md b/zh-cn/application-dev/ui/ui-js-components-path2d.md index 636c694e48377be4ca33691f314ef53c0806e498..b1f1bb0c68c88d0734bbdee94d9159982cc84ec0 100644 --- a/zh-cn/application-dev/ui/ui-js-components-path2d.md +++ b/zh-cn/application-dev/ui/ui-js-components-path2d.md @@ -23,6 +23,7 @@ align-items: center; justify-content: center; width: 100%; + height: 100%; } canvas { @@ -105,6 +106,7 @@ export default { align-items: center; justify-content: center; width: 100%; + height: 100%; } canvas { diff --git a/zh-cn/application-dev/ui/ui-js-components-switch.md b/zh-cn/application-dev/ui/ui-js-components-switch.md index e236251483a79026fdcc87663ead6d309a221329..a8554912f7467a7ff1e667833fbd4965a9490027 100644 --- a/zh-cn/application-dev/ui/ui-js-components-switch.md +++ b/zh-cn/application-dev/ui/ui-js-components-switch.md @@ -21,8 +21,6 @@ switch为开关选择器,切换开启或关闭状态。具体用法请参考[s /* xxx.css */ .container { flex-direction: column; - justify-content: center; - align-items: center; background-color: #F1F3F5; } ``` diff --git a/zh-cn/application-dev/ui/ui-ts-animation-feature.md b/zh-cn/application-dev/ui/ui-ts-animation-feature.md index 16869cea7b746874566257d31d4e9448d0a3967f..115f4f365f715f07e2817044adb0f772785b6ff1 100644 --- a/zh-cn/application-dev/ui/ui-ts-animation-feature.md +++ b/zh-cn/application-dev/ui/ui-ts-animation-feature.md @@ -305,7 +305,7 @@ .height(184) .width('100%') .onClick(() => { - router.push({ url: 'pages/FoodDetail', params: { foodId: this.foodItem } }) + router.push({ url: 'pages/FoodDetail', params: { foodData: this.foodItem } }) }) } } diff --git a/zh-cn/application-dev/ui/ui-ts-components-intro.md b/zh-cn/application-dev/ui/ui-ts-components-intro.md index 5af40fbdf7ee2567a2d761431cea84c69eb31c98..098791ee5e3a4787d7a85eee43b417a5f88007d5 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-intro.md +++ b/zh-cn/application-dev/ui/ui-ts-components-intro.md @@ -17,8 +17,6 @@ - [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) -- [`Xcomponent`:XComponent(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) - - [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) - [`PatternLock`:图案密码锁组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) diff --git a/zh-cn/application-dev/ui/ui-ts-developing-intro.md b/zh-cn/application-dev/ui/ui-ts-developing-intro.md index d5bfbf46859bb2fe260f18d63eedf15aa7fb768f..62f4538cbe834025650e252f413ec7934b171cd4 100644 --- a/zh-cn/application-dev/ui/ui-ts-developing-intro.md +++ b/zh-cn/application-dev/ui/ui-ts-developing-intro.md @@ -2,15 +2,14 @@ ## 开发说明 -声明式UI的工程结构还请参考[OpenHarmony APP工程结构介绍](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-project-overview-0000001218440650#section133380945818)。其中,.ets结尾的ArkTS文件用于描述UI布局、样式、事件交互和页面逻辑,支持导入TypeScript和JavaScript文件。资源目录resources文件夹位于src/main下,此目录下资源文件的详细规范以及子目录结构规范参看[资源分类与访问](../quick-start/resource-categories-and-access.md)。 - -在开发页面之前,请先[学习ArkTS语言](../quick-start/arkts-get-started.md)了解声明式UI的基本语法。 - -在开发页面时,可先根据使用场景,在[常见布局](ui-ts-layout-linear.md)中选择合适的布局。再根据页面需要实现的内容,为页面添加系统内置组件,更新组件状态。页面开发过程中请参考[自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md)了解如何添加需要的生命周期回调方法。 - -也可在页面中添加[绘图](../reference/arkui-ts/ts-drawing-components-circle.md)和[动画](../reference/arkui-ts/ts-animatorproperty.md),丰富页面的展现形态。还可以使用[路由](../reference/apis/js-apis-router.md)实现多个页面之间的跳转和数据传递。 - -另外请参考[性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md),避免低性能代码对应用的性能造成负面影响。 +| 任务 | 简介 | 相关资源 | +| ---------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 准备开发环境 | 了解声明式UI的工程结构。
了解资源分类与访问。 | [OpenHarmony工程介绍](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-project-overview-0000001218440650)
[资源分类与访问](../quick-start/resource-categories-and-access.md) | +| 学习ArkTS语言 | ArkTS是HarmonyOS优选的主力应用开发语言,当前,ArkTS在TS基础上主要扩展了声明式UI能力。 | [学习ArkTS语言](../quick-start/arkts-get-started.md) | +| 开发页面 | 根据页面的使用场景,选择合适的布局。
根据页面需要实现的内容,添加系统内置组件,并修改组件样式。
更新页面内容,丰富页面展现形式。 | [创建页面](#创建页面)
[常见布局开发指导](ui-ts-layout-linear.md)
[常见组件说明](ui-ts-components-intro.md)
[修改组件样式](#修改组件样式)
[更新页面内容](#更新页面内容) | +| (可选)页面多样化 | 绘图和动画。 | [绘图组件](../reference/arkui-ts/ts-drawing-components-circle.md)
[画布组件](../reference/arkui-ts/ts-components-canvas-canvas.md)
[动画](../reference/arkui-ts/ts-animatorproperty.md) | +| (可选)页面之间的跳转 | 使用页面路由实现多个页面之前的跳转。 | [页面路由](../reference/apis/js-apis-router.md) | +| (可选)性能提升 | 避免低性能代码对应用的性能造成负面影响。 | [性能提升的推荐方法](ui-ts-performance-improvement-recommendation.md) | ## 创建页面 @@ -33,19 +32,10 @@ ## 修改组件样式 -创建系统内置组件时,若不设置属性方法,则会显示其默认样式。通过更改组件的属性样式或者组件支持的[通用属性](../reference/arkui-ts/ts-universal-attributes-size.md)样式,设置可以改变组件的UI显示。 +在页面中添加系统内置组件时,若不设置属性方法,则会显示其默认样式。通过更改组件的属性样式或者组件支持的[通用属性](../reference/arkui-ts/ts-universal-attributes-size.md)样式,改变组件的UI显示。 1. 通过修改Text组件的构造参数,将Text组件的显示内容修改为“Tomato”。 - -2. 修改Text组件的fontSize属性更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。fontWeight属性支持三种设置方式: - - a. number类型的取值范围为100到900,取值间隔为100,默认为400,取值越大,字体越粗。 - - b. FontWeight为内置枚举类型,取值支持FontWeight.Lighter、FontWeight.Normal、FontWeight.Regular、FontWeight.Medium、FontWeight.Bold、FontWeight.Bolder。FontWeight.Normal即为400数值的字体粗细。 - - c. string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。设置其他字符串则为无效,保持默认字体粗细显示。 - - 属性方法要紧随组件,通过“.”操作符连接,也可以通过链式调用的方式配置组件的多个属性。 +2. 修改Text组件的fontSize属性更改组件的字体大小,将字体大小设置为26,通过fontWeight属性更改字体粗细,将其设置为500。 ```ts // xxx.ets @@ -66,62 +56,13 @@ ![zh-cn_image_0000001168888224](figures/zh-cn_image_0000001168888224.png) -## 组件成员变量初始化 - -自定义组件的成员变量可以通过[本地初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)和[在构造组件时通过构造参数初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)两种方式实现,具体允许哪种方式取决于该变量所使用的装饰器: - - -**示例:** - -```ts -// xxx.ets -class ClassA { - public str: string - - constructor(str: string) { - this.str = str - } -} - -@Entry -@Component -struct Parent { - // Parent的变量parentState进行本地初始化 - @State parentState: ClassA = new ClassA('hello') - - build() { - Column() { - Row() { - CompA({ aState: new ClassA('Tomato'), aLink: $parentState }) - } - // aState在CompA中已进行初始化,因此可以缺省 - Row() { - CompA({ aLink: $parentState }) - } - }.width('100%') - } -} - -@Component -struct CompA { - // CompA中的变量aState进行本地初始化,aLink在Parent中使用时通过构造参数初始化 - @State aState: any = new ClassA('CompA') - @Link aLink: ClassA - - build() { - Row() { - Text(JSON.stringify(this.aState)).fontSize(20).margin(30) - Text(JSON.stringify(this.aLink)).fontSize(20).margin(30) - } - } -} -``` - -![component](figures/component.PNG) +## 更新页面内容 -## 组件的状态更新 +在创建基本的页面之后,可根据组件的状态来更新页面内容。以下示例展示了简单的更新页面方法。 -组件的状态可以通过动态修改组件成员变量的值来更新,下面以示例来进行说明。 +> **说明:** +> +> 更新组件的状态之前,请先初始化组件的成员变量。自定义组件的成员变量可以通过[本地初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)和[在构造组件时通过构造参数初始化](../quick-start/arkts-restrictions-and-extensions.md#自定义组件成员变量初始化的方式与约束)两种方式实现,具体允许哪种方式取决于该变量所使用的装饰器。 **示例:** @@ -197,11 +138,6 @@ struct TimerComponent { 2. 判断if条件,创建true条件下的元素; 1. 创建Image组件,并设置其图片源地址; 2. 使用给定的构造函数创建TimerComponent; - 1. 创建TimerComponent对象; - 2. 本地初始化成员变量初始值; - 3. 使用TimerComponent构造函数提供的参数更新成员变量的值; - 4. 执行TimerComponent的aboutToAppear函数; - 5. 执行TimerComponent的build函数,创建相应的UI描述结构; 3. 创建Button内置组件,设置相应的内容。 **状态更新:** @@ -218,10 +154,5 @@ struct TimerComponent { 1. Text组件会被重用,但使用新的文本内容进行重新初始化; 2. 判断if条件,使用false条件下的元素; 1. 原来true条件的组件不再使用,将这些组件销毁; - 1. 销毁Image组件实例; - 2. 销毁TimerComponent组件实例,aboutToDisappear函数被调用; 2. 创建false条件下的组件; - 1. 创建Image组件,并设置其图片源地址; - 2. 使用给定的构造函数重新创建TimerComponent; - 3. 初始化TimerComponent,并调用aboutToAppear函数和build函数。 - 3. 重用Button组件,使用新的图片源地址。 + 3. 重用Button组件,使用新的图片源地址。 \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md index deceb78528aafceed81f93b0352cd0d5f65efb52..565bdddd400c9a2fb32714855fdce94830292ea9 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-grid-container-new.md @@ -83,7 +83,7 @@ GridRow({ } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") }.backgroundColor(color) }) @@ -264,7 +264,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ForEach(this.bgColors, (color, index) => { GridCol({ span: 2 }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) @@ -281,7 +281,7 @@ GridCol组件作为GridRow组件的子组件,通过给GridCol传参或者设 ForEach(this.bgColors, (color, index) => { GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) { Row() { - Text(${index}) + Text(`${index}`) }.width("100%").height("50vp") } .backgroundColor(color) diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index 968540c91ddbf38ebc9ce853cb8a7dbe603a0568..353c14b0b00c2c417ba991337f2c340f2a29436f 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -91,20 +91,20 @@ ```js // 移动子窗口位置。 - windowClass.moveTo(300, 300, (err, data) => { + windowClass.moveTo(300, 300, (err) => { if (err.code) { console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window.'); }); // 改变子窗口大小。 - windowClass.resetSize(500, 1000, (err, data) => { + windowClass.resetSize(500, 1000, (err) => { if (err.code) { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size.'); }); ``` @@ -114,19 +114,19 @@ ```js // 为子窗口加载对应的目标页面。 - windowClass.loadContent("pages/page2", (err, data) => { + windowClass.loadContent("pages/page2", (err) => { if (err.code) { console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); // 显示子窗口。 - windowClass.show((err, data) => { + windowClass.show((err) => { if (err.code) { console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in showing the window.'); }); }); ``` @@ -137,12 +137,12 @@ ```js // 销毁子窗口。当不再需要某些子窗口时,可根据场景的具体实现逻辑,使用destroy接口销毁子窗口。 - windowClass.destroy((err, data) => { + windowClass.destroy((err) => { if (err.code) { console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in destroying the subwindow. Data: ' + JSON.stringify(data)); + console.info('Succeeded in destroying the subwindow.'); }); ``` @@ -186,31 +186,31 @@ ```js // 实现沉浸式效果。方式一:设置窗口全屏显示。 let isFullScreen = true; - mainWindowClass.setFullScreen(isFullScreen, (err, data) => { + mainWindowClass.setFullScreen(isFullScreen, (err) => { if (err.code) { console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in enabling the full-screen mode.'); }); // 实现沉浸式效果。方式二:设置导航栏、状态栏不显示。 let names = []; - mainWindowClass.setSystemBarEnable(names, (err, data) => { + mainWindowClass.setSystemBarEnable(names, (err) => { if (err.code) { console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be visible.'); }); // 实现沉浸式效果。 // 方式三:设置窗口为全屏布局,配合设置状态栏、导航栏的透明度、背景/文字颜色及高亮图标等属性,与主窗口显示保持协调一致。 let isLayoutFullScreen = true; - mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + mainWindowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => { if (err.code) { console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the window layout to full-screen mode.'); }); let sysBarProps = { statusBarColor: '#ff00ff', @@ -219,12 +219,12 @@ statusBarContentColor: '#ffffff', navigationBarContentColor: '#ffffff' }; - mainWindowClass.setSystemBarProperties(sysBarProps, (err, data) => { + mainWindowClass.setSystemBarProperties(sysBarProps, (err) => { if (err.code) { console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar properties.'); }); ``` @@ -234,19 +234,19 @@ ```js // 为沉浸式窗口加载对应的目标页面。 - mainWindowClass.loadContent("pages/page3", (err, data) => { + mainWindowClass.loadContent("pages/page3", (err) => { if (err.code) { console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); // 显示沉浸式窗口。 - mainWindowClass.show((err, data) => { + mainWindowClass.show((err) => { if (err.code) { console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in showing the window.'); }); }); ``` \ No newline at end of file diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 1cb4e281f1c78336a50df42cbe79e1e5b7f120f0..810980e39b18a114d661e73ee6709896060d95bc 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -82,21 +82,21 @@ class MainAbility extends Ability { console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data)); // 2.设置主窗口属性。以设置"是否可触"属性为例。 let isTouchable = true; - windowClass.setTouchable(isTouchable, (err, data) => { + windowClass.setTouchable(isTouchable, (err) => { if (err.code) { console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); + console.info('Succeeded in setting the window to be touchable.'); }) }) // 3.为主窗口加载对应的目标页面。 - windowStage.loadContent("pages/page2", (err, data) => { + windowStage.loadContent("pages/page2", (err) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); }); } }; @@ -149,34 +149,34 @@ class MainAbility extends Ability { sub_windowClass = data; }); // 2.子窗口创建成功后,设置子窗口的位置、大小及相关属性等。 - sub_windowClass.moveTo(300, 300, (err, data) => { + sub_windowClass.moveTo(300, 300, (err) => { if (err.code) { console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window.'); }); - sub_windowClass.resetSize(500, 1000, (err, data) => { + sub_windowClass.resetSize(500, 1000, (err) => { if (err.code) { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size.'); }); // 3.为子窗口加载对应的目标页面。 - sub_windowClass.loadContent("pages/page3", (err, data) => { + sub_windowClass.loadContent("pages/page3", (err) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); // 3.显示子窗口。 - sub_windowClass.show((err, data) => { + sub_windowClass.show((err) => { if (err.code) { - console.error('Failed to show the window. Cause:' + JSON.stringify(err)); + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in showing the window.'); }); }); }) @@ -184,12 +184,12 @@ class MainAbility extends Ability { destroySubWindow() { // 4.销毁子窗口。当不再需要子窗口时,可根据具体实现逻辑,使用destroy对其进行销毁。 - sub_windowClass.destroy((err, data) => { + sub_windowClass.destroy((err) => { if (err.code) { console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in destroying the window.'); }); } @@ -242,30 +242,30 @@ class MainAbility extends Ability { // 2.实现沉浸式效果。方式一:设置应用主窗口为全屏显示。 let isFullScreen = true; - windowClass.setFullScreen(isFullScreen, (err, data) => { + windowClass.setFullScreen(isFullScreen, (err) => { if (err.code) { console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in enabling the full-screen mode.'); }); // 2.实现沉浸式效果。方式二:设置导航栏、状态栏不显示。 let names = []; - windowClass.setSystemBarEnable(names, (err, data) => { + windowClass.setSystemBarEnable(names, (err) => { if (err.code) { console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be visible.'); }); // 2.实现沉浸式效果。方式三:设置窗口为全屏布局,配合设置导航栏、状态栏的透明度、背景/文字颜色及高亮图标等属性,与主窗口显示保持协调一致。 let isLayoutFullScreen = true; - windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + windowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => { if (err.code) { console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the window layout to full-screen mode.'); }); let sysBarProps = { statusBarColor: '#ff00ff', @@ -274,21 +274,21 @@ class MainAbility extends Ability { statusBarContentColor: '#ffffff', navigationBarContentColor: '#ffffff' }; - windowClass.setSystemBarProperties(sysBarProps, (err, data) => { + windowClass.setSystemBarProperties(sysBarProps, (err) => { if (err.code) { console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar properties.'); }); }) // 3.为沉浸式窗口加载对应的目标页面。 - windowStage.loadContent("pages/page2", (err, data) => { + windowStage.loadContent("pages/page2", (err) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); }); } }; @@ -356,43 +356,43 @@ class MainAbility extends Ability { console.info('Succeeded in creating the floatWindow. Data: ' + JSON.stringify(data)); windowClass = data; // 3.悬浮窗窗口创建成功后,设置悬浮窗的位置、大小及相关属性等。 - windowClass.moveTo(300, 300, (err, data) => { + windowClass.moveTo(300, 300, (err) => { if (err.code) { console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window.'); }); - windowClass.resetSize(500, 1000, (err, data) => { + windowClass.resetSize(500, 1000, (err) => { if (err.code) { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size.'); }); // 4.为悬浮窗加载对应的目标页面。 - windowClass.loadContent("pages/page4", (err, data) => { + windowClass.loadContent("pages/page4", (err) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); // 4.显示悬浮窗。 - windowClass.show((err, data) => { + windowClass.show((err) => { if (err.code) { console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in showing the window.'); }); }); //5.销毁悬浮窗。当不再需要悬浮窗时,可根据具体实现逻辑,使用destroy对其进行销毁。 - windowClass.destroy((err, data) => { + windowClass.destroy((err) => { if (err.code) { console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in destroying the window.'); }); }); } diff --git a/zh-cn/application-dev/windowmanager/system-window-stage.md b/zh-cn/application-dev/windowmanager/system-window-stage.md index a95c5e0335b969a4cf540ef8caea43d79bb6f734..90962f83e89293e0c77b60ceaceda0cc31e2aa6e 100644 --- a/zh-cn/application-dev/windowmanager/system-window-stage.md +++ b/zh-cn/application-dev/windowmanager/system-window-stage.md @@ -65,46 +65,46 @@ export default class ServiceExtensionAbility1 extends ExtensionContext { console.info('Succeeded in creating the volume window.') windowClass = data; // 2.创建音量条窗口成功之后,可以改变其大小、位置或设置背景色、亮度等属性。 - windowClass.moveTo(300, 300, (err, data) => { + windowClass.moveTo(300, 300, (err) => { if (err.code) { console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window.'); }); - windowClass.resetSize(500, 1000, (err, data) => { + windowClass.resetSize(500, 1000, (err) => { if (err.code) { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size.'); }); // 3.为音量条窗口加载对应的目标页面。 - windowClass.loadContent("pages/page_volume", (err, data) => { + windowClass.loadContent("pages/page_volume", (err) => { if (err.code) { console.error('Failed to load the content. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + console.info('Succeeded in loading the content.'); // 3.显示音量条窗口。 - windowClass.show((err, data) => { + windowClass.show((err) => { if (err.code) { console.error('Failed to show the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in showing the window.'); }); }); // 4.隐藏/销毁音量条窗口。当不再需要音量条时,可根据具体实现逻辑,对其进行隐藏或销毁。 // 此处以监听音量条区域外的点击事件为例实现音量条窗口的隐藏。 windowClass.on('touchOutside', () => { console.info('touch outside'); - windowClass.hide((err, data) => { + windowClass.hide((err) => { if (err.code) { console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hidinging the window. Data: ' + JSON.stringify(data)); + console.info('Succeeded in hidinging the window.'); }); }); }); diff --git a/zh-cn/design/API-Review-Template.md b/zh-cn/design/API-Review-Template.md index 0c7dacf02ef71c1ff7a2ab77afdddcb0d355bb74..ed26f538818e2a0da6131c63a6a7f1bd460480ab 100644 --- a/zh-cn/design/API-Review-Template.md +++ b/zh-cn/design/API-Review-Template.md @@ -2,7 +2,7 @@ ## 背景 -* API类型:[Public API | Test API| HDI] +* API类型:[Public API | System API |Test API| HDI] * API需求来源: * API使用场景: * API所属子系统: diff --git a/zh-cn/design/OpenHarmony-API-governance.md b/zh-cn/design/OpenHarmony-API-governance.md index a99e605980ecca03cb9e2f8a10e6d21f0136ca50..b56d09d461dd22683fcd66a0b4085fd865fa082d 100755 --- a/zh-cn/design/OpenHarmony-API-governance.md +++ b/zh-cn/design/OpenHarmony-API-governance.md @@ -28,7 +28,7 @@ OpenHarmony软件栈中包含了多个角色,因此API也分作多种类型。 各类型API说明如下: * Public API:OpenHarmony对所有应用开发者公开的API。 -* Test API:测试专用的API,供开发者使用。 +* Test API:测试专用的API,仅在测试阶段使用。 * System API:提供给系统特权应用使用的API,普通应用无法使用。 * HDI:描述硬件能力的接口。 * Driver API:提供给驱动开发者使用的接口。 @@ -41,6 +41,7 @@ OpenHarmony的目标是构建面向万物互联时代的新一代操作系统, * C/C++ * JavaScript * TypeScript +* ArkTS 本章程所描述的内容与编程语言无关。即:在不违反编程语言要求的情况下,API不分编程语言都要遵守章程的要求。 @@ -66,7 +67,7 @@ API评审流程如下: 1. API评审申请、代码提交(Owner:Contributor),所有涉及API新增或变更需同步提交相应的API评审文档,详细说明API的需求来源、场景与使用方法、权限设计、隐私保护澄清等,详见后面的API评审申请要素。为避免后续的返工,Contributor可以在正式的API评审申请、代码提交之前,先通过邮件方式将API设计文档提交Committer、领域SIG、API SIG等相关人员预审。 1. 代码评审(Owner:Committer),代码评审和API预审,涉及API提交Code Review通过后,还需要进一步领域SIG评审。如果单次提交同时涉及多个领域的API新增或变更,相应的API评审申请和代码需要同时提交给相关领域的Committer评审,只有所有对应领域的Committer都完成CodeReview后才能进入下一评审环节。 1. API评审(Owner:领域SIG),新增API相关的代码提交评审,领域SIG评审通过即可代码合入;变更API相关的代码提交,领域SIG评审通过后,还需要进一步提交API SIG。如果单次提交同时涉及多个领域的API新增,相应的API评审申请和代码需要同时提交给相关领域的SIG评审,只需一个领域SIG评审通过即可代码合入。如果单次提交同时涉及多个领域的API变更,相应的API评审申请和代码需要同时提交给相关领域的SIG评审,只有所有对应领域的SIG都要评审通过才能进入下一评审环节。 -1. API变更评审(Owner:API SIG),变更API相关的代码提交评审,评审通过即可代码。 +1. API变更评审(Owner:API SIG),变更API相关的代码提交评审,评审通过即可编码。 1. 评审完成。 ### API评审申请要素 @@ -74,88 +75,24 @@ API评审流程如下: 如果涉及API新增或变更需同步提交相应的API评审文档。API评审文档使用[《OpenHarmony API 评审模板》](API-Review-Template.md)描述。 针对新增API,需要包含如下要素: -1. 需求来源与使用场景(必须)。 -1. API现状与差距分析,说明API新增或变更的必要性(必须)。 -1. API原型设计与使用方法说明(必须);必要时,可以进一步包含相应的使用样例(可选)。 -1. API权限设计(必须)。 -1. API隐私保护方案与要求满足情况澄清(必须); -1. 提交代码的同时提交相应的API参考(必须);必要时,可同步提交相应的开发者指南文档(可选)。 -1. 兼容性/性能/功耗/可靠性/测试等相关情况说明(可选,如不满足本章程 “API设计要求”,则必须包含相关说明)。 +1. (必选)需求来源与使用场景。 +1. (必选)API现状与差距分析,说明API新增或变更的必要性。 +1. (可选)API原型设计与使用方法说明(必须);必要时,可以进一步包含相应的使用样例。 +1. (必选)API权限设计。 +1. (必选)API隐私保护方案与要求满足情况澄清; +1. (可选)提交代码的同时提交相应的API参考(必须);必要时,可同步提交相应的开发者指南文档。 +1. (可选)兼容性/性能/功耗/可靠性/测试等相关情况说明(如不满足本章程 “API设计要求”,则必须包含相关说明)。 针对变更API,需要额外包含如下要素: 1. 针对老接口的处理方式(废弃、隐藏或彻底删除)以及对使用老SDK开发应用的兼容措施(必须); 2. 变更影响、替代接口和相应的应用适配方案(必须)。 3. 刷新ChangeLog(必须) 和 API-diff文档(涉及JS/Native API变更,必须)。 -## API设计要求 - - -### 一致性要求 -1. 概念一致性:基于场景的业务模型抽象,形成OpenHarmony的连贯、一致、自恰的用户程序模型和业务概念。 -1. 术语一致性:相应的业务术语必须采用统一名词,不允许使用多个语意接近的名词表示同一个业务对象;同样地,为了避免产生混淆,也不允许针对不同的业务对象使用相同的名词或语言接近的名词。 -1. 操作一致性:相同的操作动作必须采用同一动词。 -1. 参数顺序一致性:相同参数/参数序列在多个API中的位置和顺序保持一致。 -1. 机制及算法一致性:通信机制、调用模式、认证机制、加密算法等保持一致。 -1. 帮助、Demo、模板风格一致性:排版、用法等保持一致。 - -### 易用性要求 -以“能力使用者”视角,而不是“能力提供者”视角设计API: -1. 可理解:API命名和功能特性必须容易理解。 -1. 易使用:提供简单易用的API,减少API之间不必要的耦合,避免多个无之间关联关系API之间调用顺序的依赖,尽可能使调用者优雅,尽量避免使用单一功能时必须同时组合调用多个包/模块或类中的多方法才能实现。 -1. 避免误导:提供使用者期望的能力,避免误导,减少误用。 -1. 提供必要的API文档。 - -### 命名要求 -1. 能清晰的表达意图:使用完整的描述性的单词。 -1. 避免造成误导:有误导的名字比表达不清的名字还要有危害性。 -1. 词义清晰明了,避免使用info,data,object等一般意义的词。 -1. 作用域越大,命名应越精确。 -1. 不用或少用缩写,业界通用术语遵从行业习惯允许使用缩写。 -1. 包名/模块名/命名空间前缀约定: - 1. JS API 统一模块名:@ohos.\*。 - 2. Native API 统一命名空间:namespace OHOS.\*。 - 3. 引用外部开源代码的,可以保留原包名/模块名/命名空间,也可以按照上述规则对包名统一进行替换。 -1. 包名/模块名/命名空间最短不少于2段,最长不超过4段;每一段建议使用一个单词,最长不超过2个单词。 -1. 类名、方法名/函数名、成员变量、变量名最多不超过4个单词。 - -### 权限控制要求 -1. 完备性原则:一切穿透应用沙箱的行为都需考虑使用权限来管控。 -1. 最优粒度原则:一个权限只保护一类对象;一个接口仅需申请一个权限即可访问。 -1. 清晰完整原则:权限定义中必须清晰说明保护对象、开放范围、敏感级别。 -1. 最小开放原则:一个权限仅对确有正当业务需求的应用开放,开放控制可通过权限来实现。 - -### 隐私保护要求 -1. API调用的返回仅包含必要的内容, 避免携带额外信息。 -1. API调用不允许获取、手机用户个人数据, 除非通过用户权限管控、由用户授权同意。 -1. API涉及跨应用调用时,如涉及个人数据向被调用者的披露,由调用方在隐私声明中说明披露的数据类型、数据接收者和数据使用目的。 -1. API涉及到用户敏感数据(如电话、通讯录、媒体等)访问时,需要使用system picker的机制,禁止API通过申请敏感权限方式访问。 -1. API开放禁止捆绑与所开放能力不相关的功能。 - -### 文档化要求 -1. API参考采用英文方式交付。 -1. 模块/包模块的API参考必须包括简要描述和详细描述。 -1. 类、方法、“Interface”、枚举或成员变量的API参考必须包括简要描述。 -1. 类、方法、“Interface”、枚举或成员变量的API参考可选包括详细描述。 -1. 方法、“Interface”的API参考必须包括所有入参的参数描述。 -1. 如果方法或“Interface”有返回值,则API参考必须包含返回值描述。 -1. 如果执行过程中可能抛出异常,则API参数必须包含相关的异常描述。 -1. 必须包含API的起始版本号(使用@since注释标记)。 -1. 可选包括本模块或类自己的版本号(使用@version注释标记)。 -1. 涉及API变更(不兼容),必须同步交付API-Diff和ChangeLog文档。 - -### 兼容性要求 -1. 按严格程度从高到低,API兼容要求包括:契约兼容 > 二进制兼容 > 源码兼容。 - 1. 源码兼容:指版本演进后,开发者已有的源代码可正常编译通过。 - 1. 二进制兼容:指版本演进后,开发者已有程序不用重新编译可正常链接、运行。 - 1. 契约兼容:也称语义兼容,指版本演进后,开发者原有程序行为不发生变化。 -1. OpenHarmony API后向兼容必须满足二进制兼容要求,例外情况需要通过API SIG评审并经过PMC批准。常见破坏二进制兼容的API变更包括: - 1. 任何API元素删除; - 1. 降低方法的可见性,例如protected修改为了private,或者public修改为protected。 - 1. 类类型发生变化,例如抽象类变更为非抽象类,或者接口类(“Interface”)变更为非接口类。 - 1. 方法原型发生变化,例如返回值类型修改,或入参顺序或入参类型发生变化。 - 1. 成员final/static等属性发生变化,例如非final成员变成final,或者非static的成员变成static。 -1. 禁止“原型相同、功能不兼容”的API修改,可受限使用“废弃old-api、新增new-api”的方式进行修改。 -1. 根据发布类型不同,API的生命周期和兼容性要求: +## API的生命周期和兼容性要求 + +OpenHarmony API会以API version的形式逐步演进。每个版本会经历如下图的发布周期。 + +不同周期的API其兼容性要求如下所述: ![](figures/API-Lifecycle.png) @@ -173,33 +110,6 @@ API评审流程如下: 1. 提供可替代接口。 1. 废弃API至少保留5个API Version版本(对废弃5个API Version的API可以彻底删除,不再支持)。 -### 性能要求 -1. 应及时响应,避免调用者等待;如果API调用执行时间过长应设计为异步方式。 -2. 应关注API调用时机、调用频次对RAM占用的影响。 -3. 应关注API调用时机、调用频次对功耗的影响。 -4. 对使用资源的API调用需要能及时释放资源,异常场景具备容错机制,保障资源及时释放。 - -### 功耗要求 - -1. 针对API调用时机、调用频次对功耗的影响做评估,有影响进行相关设计。 -2. 版本演进过程中,功耗不劣化。 - -### 可靠性要求 - -1. API不能因为外部输入(输入参数、系统状态、外部数据等)或者内部状态、数据异常而崩溃,应该返回确定的错误码或者抛出预定义的异常。 -2. API应明确调用是同步还是异步调用,若是同步调用,应明确超时上限或者允许调用者设置超时时间,避免调用卡死导致业务无响应。 -3. API务必支持多线程重入。 -4. 满足幂等性要求,相同业务含义的请求API调用一次或多次重试总能获得相同的效果(API调用依赖外部资源的变化除外)。针对可重入的API调用实现内部应尽量避免引入时变因素,如系统tick、静态变量、没有互斥保护的全局变量等;针对同一客户端的多次重复调用,可以使用contextID、clientToken、sequenceNo等作为调用入参。 -5. API内部创建对象的生命周期要闭合,避免对象资源泄漏。 -6. API要明确客户端调用失败后,能够发起重试的最大次数。 - -### 测试要求 -1. 新增API必须同步交付API自动化测试用例,用例100%覆盖API接口。 -2. 用例场景单一,单条用例覆盖接口单个功能场景,简化单条用例代码逻辑。 -3. 用例执行高效,每条用例执行时间控制在毫秒级。 -4. 用例执行全自动化:接口用例需要达成100%自动化。 -5. 用例有效性:用户要求必须存在断言,且不能仅是检查是否抛出异常,需要有功能逻辑的断言。 - -### 编程语言要求 +### API 设计规范 -API根据其编程语言类型,需要遵守相应的OpenHarmony编程语言规范。 +关于这部分内容,请参见[《OpenHarmony API设计规范》](OpenHarmony-API-quality.md)。 diff --git a/zh-cn/design/OpenHarmony-API-quality.md b/zh-cn/design/OpenHarmony-API-quality.md new file mode 100644 index 0000000000000000000000000000000000000000..21d0ca4e81dd6e15ebd7247439bd1953e5e09aef --- /dev/null +++ b/zh-cn/design/OpenHarmony-API-quality.md @@ -0,0 +1,858 @@ +# OpenHarmony API 设计规范 + +* 修订记录 + +| 版本 | 作者 | 时间 | 更新内容 | +| -------------- | ------------------- | ---------- | ---------- | +| v0.1,试运行版 | OpenHarmony API SIG | 2022年11月 | 初版发布 | + +## 目的 + +API是软件实现者提供给使用者在编程界面上的定义,API在很大程度上体现了软件实体的能力范围。 + +同时,API定义的好坏极大影响了使用者的体验。 + +为了保障OpenHarmony生态健康发展,保证开发者使用体验,现制定OpenHarmony API设计规范。 + +## 范围 + +OpenHarmony API主要包含了对应用开放的外部API,以及系统实现部分的内部API。 + +本设计规范主要用以约束以下API(不区分编程语言): + +* OpenHarmony Public API +* OpenHarmony System API + +关于OpenHarmony API的分类,请参见[《 OpenHarmony API治理章程》](https://gitee.com/openharmony/docs/blob/master/zh-cn/design/OpenHarmony-API-governance.md)。 + +## 接口设计目标 + +好的接口设计应该满足以下四点: + +* **可使用** (Operational):这一点是毋庸置疑的,接口必须要能完成它提供的能力。可使用是最基本的要求。 +* **富于表现力** (Expressive):与可使用同样重要的是,借助接口,使用者能够清晰表达他们想要做的事情。 +* **简单** (Simple):接口的设计要保证学习和使用简单,避免难于理解或者使用出错的情况发生。 +* **可预测** (Predictable):API应当始终一致的按照接口的定义完成使命。如果接口定义中不包含出错和异常的情况,那么这个API被调用任意多遍,都不应该发生任何异常。当然,如果实际情况是有可能出错或者失败的,那就要在接口定义中说明清楚什么情况下会出什么错,并准确的在相应的时机下返回对应的错误。 + +除此之外,API的设计还应该注意以下几点: + +* **API的稳定性和一致性是最重要的,API并非越多越好。** +* **API命名应当容易理解,API命名并非越短越好。** +* **API应当做好封装和抽象,并非暴露的信息或者能力越多越好。** + +从开发者使用API的阶段上来看,API应当做到: + +* **在学习阶段** + * 容易理解 + * 容易上手 +* **在开发阶段** + * 富于表现力 + * 简单 + * 可预测 +* **在维护阶段** + * 行为稳定 + * 容易维护 + +## API设计概述 + +为了使得规则尽可能通用,本规范不会涉及具体编程语言的差异,也不会涉及编码规约。这部分内容只要遵守相应的本地要求即可。 + +从整体上来看,本规范将API规范分成**发布前评审规范**和**发布后评价**两个部分。 + +* **发布前评审规范** :是对于API的最基本要求,所有API必须满足这些要求才能通过评审。 +* **发布后评价** :尽管在发布前已经做了很多的规则要求。但是仍然不能保证API是完美的。因此,API发布后仍然要保持对API的关注。发布后的审视将影响对API提供者的评价。 + +以下是所有的API设计规则的罗列,以供快速索引,详细的说明在后文中展开。 + +每一个OpenHarmony API提供者都应该熟悉以下规则。 + +### 发布前评审规范 + +* 易用性 + * 规则1:符合编码规则 + * 规则2:准确使用英语语法 + * 规则3:合理使用缩写 + * 规则4:准确使用对仗词 + * 规则5:准确使用设计/架构模式 + * 规则6:避免有争议的命名 + * 规则7:参数类型合理 + * 规则8:参数数量合理 + * 规则9:参数顺序合理 + * 规则10:返回值定义完备 + * 规则11:异常定义合理 + * 规则12:从正面表达 + * 规则13:降低出错的可能性 + * 规则14:避免顺序耦合 + * 规则15:准确表达所有逻辑 + * 规则16:注意封装 + * 规则17:单一职责 +* 可用性 + * 规则18:保证可靠性 + * 规则19:功能完备 + * 规则20:考虑权限与隐私保护 + * 规则21:考虑并发环境 + * 规则22:注意资源管理闭合 + * 规则23:考虑重试逻辑 + * 规则24:满足幂等要求 + * 规则25:考虑设备通用性 +* 一致性 + * 规则26:保证术语、概念一致性 + * 规则27:保证设备间行为一致性 + * 规则28:注意版本演进一致性 + * 规则29:命名风格保持一致 + * 规则30:参数顺序保持一致 + * 规则31:同步/异步风格一致 +* 兼容性 + * 规则32:注意新旧系统版本的兼容性 + * 规则33:二进制向后兼容性 +* API资料 + * 规则34:模块、命名空间、类需要包含基础说明 + * 规则35:使用场景说明清晰 + * 规则36:接口说明准确 + * 规则37:参数说明准确 + * 规则38:返回值/异常描述准确 + * 规则39:元信息完备 + * 规则40:风格一致 +* 组织方式 + * 规则41:分层合理 + * 规则42:模块划分合理 + * 规则43:应用描述文件也是接口的一部分 +* 质量属性 + * 规则44:性能满足要求 + * 规则45:功耗设计合理 + * 规则46:需要保证可测试性 + * 规则47:考虑环境适应性 + +### 发布后评价 + +* 稳定性 + * 规则48:接口废弃率/变更率越低越好 +* 安全性 + * 规则49:避免接口被滥用 + * 规则50:避免接口被利用 +* 可维护性 + * 规则51:能承载业务演进 + * 规则52:功能扩展后不影响原先行为 + * 规则53:文档和资料配套更新 +* 不可替代性 + * 规则54:保证API之间正交 +* 开发者反馈 + * 规则55:关注开发者反馈 + +## 发布前评审规范说明 + +### 易用性 + +任何设计都应该考虑易用性。对于OpenHarmony API来说,易用性需要考虑以下几个方面: + +#### 命名 + +* **规则1:符合编码规约** + +API的定义首先应当满足所属项目的编码规约,例如:大小写的定义、下划线、连字符规则、前缀规则等。 + +对于OpenHarmony生态而言,可参考如下编码规约: + +* [《OpenHarmony JavaScript语言通用编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-JavaScript-coding-style-guide.md) +* [《OpenHarmony C语言编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-c-coding-style-guide.md) +* [《OpenHarmony C++语言编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-cpp-coding-style-guide.md) +* [《OpenHarmony C&C++ 安全编程指南》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-c-cpp-secure-coding-guide.md) +* [《OpenHarmony HDF驱动编程规范》](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md) +* **规则2:准确使用英语语法** + +API命名只允许使用英语。通常,类的名称是名词,例如:`XXXManager`,`XXXService`,`XXXAnimation`等。函数通常是动词或动宾结构,例如:`start()`,`createUser()`,`startBoot()`等。 + +对于一个名称叫做`Start`的类,或者一个叫做`ball()`的函数,通常是错误的做法。 + +另外,还请注意及物动词和不及物动词,避免语法错误。对于动词,根据场景需要注意时态。例如:如果时机上就存在“开始传输”和“渲染完成”这些事件,就应该用上`transferStarted()`以及`renderDone()`这类的表达。 + +* **规则3:合理使用缩写** + +应当尽可能避免使用缩写。缩写不仅仅是难于理解,还有一个问题是:一个缩写可能会有多个解释,在上下文信息不全的情况下,使用者会很难分辨。 + +如果是大家都熟知的缩写是允许的,除此之外,应该尽量避免。尤其是,只有自己能明白的缩写,这是禁止的。 + +* **规则4:准确使用对仗词** + +在语言表达中,同一个含义可能有很多个类似的词可以表达,例如: + +| 词语 | 近义词 | +| ----- | -------------------------------------------------- | +| send | deliver, dispatch, announce, distribute, route | +| find | search, extract, locate, recover | +| start | launch, create, begin, open | +| make | create, set up, build, generate, compose, add, new | + +但在API命名中,应当注意对仗词的使用。 + +例如,如果你使用了`add`就应该使用`remove`,而不是`destroy`。使用了`increase`就应该使用`decrease`,而不是`reduce`。 + +下面是一些常见的对仗词: + +| 词语 | 对仗 | +| -------- | -------- | +| add | remove | +| increase | decrease | +| open | close | +| begin | end | +| insert | delete | +| show | hide | +| create | destroy | +| lock | unlock | +| source | target | +| first | last | +| min | max | +| start | stop | +| get | set | +| next | previous | +| up | down | +| new | old | + +* **规则5:准确使用模式** + +设计模式或者架构模式其实是软件行业的“行话”。既然是行话,就要正确的使用,否则别人就可能误解你的意思。 + +因此,当你的接口中包含了`Strategy`,`Builder`,`Factory`,`Singleton`这类的词语时,请确保你准确理解了这些设计模式,并且正确使用了它们。 + +另外,如果你确定的是在使用某个模式,那就准确的在名称上使用标准术语,不要随便修改词性或者打乱名称的词语顺序,这样使用者会更容易理解。 + +* **规则6:避免有争议命名** + +命名要遵守的底线,是应该避免有争议的名称。这其中,包括但不限于任何违反法律、产生宗教争议、或导致种族歧视的词语。 + +当然,使用脏话也是绝对禁止的。考虑到OpenHarmony会使能千行百业,对于避免有争议命名,需要思考得更多。 + +#### 参数 + +* **规则7:参数类型合理** + +通常,使用类类型参数比使用简单类型要更好。 + +例如:对于下面的一组接口看似没什么问题: + +* `addPerson(string id, string name, int age)` +* `removePerson(string id, string name, int age)` +* `modifyPerson(string id, string name, int age)` + +但是这个定义不便于扩展,因为后期可能要新增参数。但是如果一开始就通过一个类类型`Person`来定义参数,则添加一个字段就很容易,并且,对于接口本身不用做任何改变。 + +使用类类型而不是简单类型,还有一个好处是:参数数量会少,更容易记忆。 + +* **规则8:参数数量合理** + +参数数量应当控制在7个以内。在更多的情况下,参数控制在3~5会更容易使用。 + +在任何情况,参数的数量都不应当超过10个,这种接口通常很难记忆和使用。如果遇到这种情况,通常是对类型没有做很好的封装,或者是接口的实现逻辑包含太多的内容。请考虑拆解。 + +* **规则9:参数顺序合理** + +在一些编程语言中,常常会以先输入参数、后输出参数的顺序来组织参数列表。 + +但其实,如果能再根据参数的大小逻辑关系、参数的重要性来进行排序,那对于使用者来说,会更容易记忆和使用。 + +比如,可选参数应该放到必选参数的后面,回调函数作为参数应该放到最后等。以`fs.readFile` 方法为例,路径参数是必填的,`encoding` 和 `flag` 是有默认值的。 + +```js +fs.readFile(path[, options], callback) +``` + +```js +fs.readFile('/etc/passwd', (err, data) => { + if (err) throw err; + console.log(data); +}); + +fs.readFile('/etc/passwd', { + encoding: 'utf-8', + flag: 'r+' +}, (err, data) => { + if (err) throw err; + console.log(data); +}); +``` + +#### 返回值 + +* **规则10:返回值定义完备** + +返回值定义完备需要做到:不能只考虑正常情况,对于接口的定义,也要考虑异常和无效的情况。要让开发者能合理处理。 + +例如: + +* 对于数字类型的返回值,要定义清楚返回的范围,什么情况下会出现极值。 +* 对于布尔类型的返回值,要定义清楚什么时候返回`true`,什么时候返回`false`。 +* 对于数组或者集合类型的返回值,要定义清楚什么时候返回`null`,什么时候返回包含空元素的集合。 +* 对于枚举类型的返回值,要确保每种情况都准确定义了。 +* **规则11:异常定义合理** + +异常是特殊情况的返回,这通常意味着输入参数无效或者函数根本无法正常处理。 + +对于同一个模块,或者同样的业务,在何种情况下返回错误值,在何种情况下直接返回异常,应该有统一的定义。 + +另外,针对同样的异常情况下,应当返回同样的异常类型。 + +保持一致可以很大程度上降低开发者的使用难度,并且避免使用出错。 + +#### 其他 + +对于易用性而言,除了上面提到的内容,还有一些推荐的做法,可以降低开发者的使用难度。 + +* **规则12:从正面表达** + +从正面表达可以降低开发者的思考成本。 + +通俗来说就是:接口的命名尽量使用肯定的词语,而不是否定方式的表达。因为否定表达很难理解。 + +下面是一个反例: + +```js +if (!isNotAccessible() || !isNotWritable() || !isNotPrintable()) +``` + +如何接口都是正面表达,就更容易理解了,下面是推荐的做法: + +```js +if (isAccessible() && isWritable() && isPrintable()) +``` + +* **规则13:降低出错的可能性** + +调用者使用错误很大程度在于参数传递上。 + +例如下面这个函数。第二个和第三个参数都是布尔值,这样使用者很容易记错顺序,或者搞不清楚该传入`true`还是`false`。 + +```js +declare function findString(text: string, isForward: boolean, isCaseSensitive: boolean): string; +``` + +通过枚举在定义上就避免这种错误存在的可能: + +```js +enum SearchDirection { + FORWARD, + BACKWARD +}; + +enum CaseSensitivity { + SENSITIVE, + INSENSITIVE +}; + +declare function findString(text: string, direction: SearchDirection, sensitivity: CaseSensitivity): string; +``` + +很多时候,通过枚举代替布尔值以及整数表达的类型,可以减少使用者出错的可能性。 + +再者,通过将多个参数组成一个类型的形式,也可以降低参数传递出错的可能性。 + +* **规则14:避免顺序耦合** + +软件设计要尽可能保证高内聚,低耦合。这一点对于大型项目尤其重要。 + +耦合表达了软件模块之间的依赖程度,耦合过深常常意味着架构设计没有做好。 + +从一个软件静态结构或者分层架构图上可以看得出:如果模块之间的依赖关系比较少,上下层之间有明显的调用方向,则是比较好的设计。相反的,如果模块之间依赖关系非常复杂,或者上下层之间存在相反方向的调用链,则不是一个好的结构。 + +耦合有很多种,对于接口来说,顺序耦合就是要注意的。顺序耦合是指:类中方法需要按照某个特定的顺序调用才能工作。 + +类似下面这组命名的接口,很可能就是顺序耦合: + +```js +doSomethingFirst() +doSomethingSecond() +doSomethingThird() +``` + +这种设计的问题在于:对于使用者的要求太高了,很容易用错。 + +对于这类问题,通常可以使用`模板方法`设计模式来解决。 + +* **规则15:准确表达所有逻辑** + +有些接口是用来查询信息的,例如`getUserAccount()`。有些是进行操作的,会修改数据,例如`createUserAccount()`。 + +**永远不要在一个看起来是查询操作的接口里面去做修改数据的动作** ,因为这样使用者会非常的迷惑。 + +更通用的来讲, **接口的名称应当表达它所做的所有事情** ,不要有所隐瞒。只有这样,在阅读代码的时候,才能更容易理解代码到底做了什么。 + +如果接口包含了内容太多,很难通过几个单词描述清楚所做的所有事情该怎么办?对于这种情况,通常意味着需要将这个接口拆分成多个,因为这个接口不够“内聚”。 + +还有一些情况下,大家在做某件事的时候,会本能的以为别人也有同样的背景认识。但事实往往并不是这样。在编程时也是一样。 + +例如,对于一个描述编程语言的字段,可能会将其命名为`language`。这是因为大家默认认为已经在讨论编程语言了,但是`language`到底是编程语言还是国际化语言?是不是叫做`programmingLanuage`更好一些呢? + +当然,对于这一条还是要举一个反例,不要走到另外一个极端:如果类名或者namespace名称中已经明确带了一个前缀,在函数中就没必要再重复一遍了。毫无信息量的冗余是没有必要的。 + +* **规则16:注意封装:不暴露实现细节** + +对于面向对象编程来说,大家都知道“封装”的重要性。 + +这意味着,系统能力应当尽可能封装好实现细节,提供简洁的接口供调用者使用。 + +这就好像冰山,埋在水里的部分不管多庞大,露在水面上的部分要足够的小,足够的简洁。这才是友好的界面(Interface)。 + +封装的重要性,不仅仅是让开发者容易使用。其实也是使得开发者不容易出错。举一个生活中的例子:电子工程师将房间的电路线接好之后,只留一个开关按钮给到用户,这就是一个很好的封装。既避免了让用户理解复杂的电路结构(方便使用),也不会产生触电(出错)的风险。 + +* **规则17:单一职责** + +一个 API 应当尽量只做一件事情,尽可能保持单一核心的职责。例如: + +```js +// 不推荐 +view.fetchDataAndRender(url, templete); + +// 推荐 +let data = view.dataManager.fetchData(url); +view.render(data, templete); +``` + +这么做的目的是因为:开发者可以根据需要,按最小单位来使用接口。也可以根据多个单一职责的组合,来进一步封装自己需要的业务逻辑。 + +单一职责与注重封装性在一些情况下可能是矛盾的:如果提供了多个单一能力的接口,势必需要使用者关心多次的调用细节。 + +在这种情况下,需要从封装的“层次”来考虑决定,接口提供给开发者的,到底是哪个层级的能力?面向高层次使用者的一件事,对于低一个层次来说,可能就是多件事情。 + +### 可用性 + +* **规则18:保证可靠性** + +操作系统所提供的接口,必须是完全可靠的。 + +当然,可靠性不意味每次调用都是成功的。例如:在资源已经耗尽的情况下,应当给调用者合理的返回值或者异常。 + +每个接口必须针对所有的情况进行准确的定义,并在相应的情况下按照定义的行为完成工作。 + +没有按照预定行为返回结果,或者无故导致应用程序异常都属于不可靠行为。 + +* **规则19:功能完备** + +每个特性或者能力在规划时,需考虑到功能的完备性。不应当出现:在支持的范围内,某个流程中断,或者某个选项缺失的情况发生。API设计者应当做好足够的验证和推演。 + +即便操作系统的特性常常会伴随系统版本几年内才能完全迭代完备。但是,对于每一个特定版本,在其包含的范围内应当是闭合的,自洽的。这要求模块的设计者划分好版本迭代的边界。 + +* **规则20:注意权限和隐私保护** + +任何涉及到用户数据、用户隐私的接口都必须做好权限限制和数据保护。 + +对于权限控制,应当遵循以下几个原则: + +1. 完备性原则:一切穿透应用沙箱的行为都需考虑使用权限来管控。 +2. 最优粒度原则:一个权限只保护一类对象;一个接口只需申请最小粒度的权限。 +3. 清晰完整原则:权限定义中必须清晰说明保护对象、开放范围、敏感级别。 +4. 最小开放原则:一个权限仅对确有正当业务需求的应用开放,开放控制可通过权限来实现。 + +对于隐私包含,应当遵守以下几个原则: + +1. API调用的返回仅包含必要的内容, 避免携带额外信息。 +2. API调用不允许获取、手机用户个人数据, 除非通过用户权限管控、由用户授权同意。 +3. API涉及跨应用调用时,如涉及个人数据向被调用者的披露,由调用方在隐私声明中说明披露的数据类型、数据接收者和数据使用目的。 +4. API涉及到用户敏感数据(如电话、通讯录、媒体等)访问时,需要使用system picker的机制,禁止API通过申请敏感权限方式访问。 +5. API开放禁止捆绑与所开放能力不相关的功能。 + +* **规则21:考虑并发环境** + +保证所有的接口线程安全需要付出很大的代价(程序复杂度、性能影响),因此OpenHarmony API不必要求所有接口线程安全。只需根据需要选择即可。 + +但是,对于设计上就是为了并发环境使用的接口,必须做好相应的设计和说明。 + +当然,对于接口的内部实现中,应当尽可能避免出现线程不安全的问题发生。 + +* **规则22:注意资源管理闭合** + +在一些情况下,有些接口包含了动态资源的申请。此种情况下,这些接口也需要考虑到资源的释放。 + +如果申请的资源是直接返回开发者的,则需要提供相应的接口来释放资源。 + +如果资源没有直接返回给开发者,则接口自身要考虑到资源的生命周期,以及释放的时机。 + +对于有资源使用上限的情况,应当给开发者说明清楚。并且提供接口查询是否已经到达上限。 + +对于独占资源更加应当注意资源的释放时机。 + +* **规则23:考虑重试逻辑** + +对于可能失败的接口,应当考虑好给开发者相应的机制来重试。例如:对于相机这类独占的资源,一旦有某个进程使用了,其他进程就无法获取到。这种情况下,应当提供接口给开发者查询是否可用的接口。 + +在一些情况下,为了避免开发者反复尝试,还需要提供给开发者状态监听的机制。 + +并且,API要明确客户端调用失败后,能够发起重试的最大次数。 + +* **规则24:满足幂等要求** + +在数学中,幂等用函数表达式就是:`f(x) = f(f(x))`。例如求绝对值的函数,就是幂等的,``abs(x) = abs(abs(x))``。 + +计算机科学中,幂等表示一次和多次请求某一个资源应该具有同样的效果,或者说,多次请求所产生的影响与一次请求执行的影响效果相同。 + +具体到实际场景:文件打开,或者的硬件资源使用,打开一次和打开多次其效果应当是一样的,不应该有其他副作用。当然,关闭,也是类似。 + +* **规则25:考虑设备通用性** + +OpenHarmony是为多种不同类型设备设计的统一操作系统。 + +考虑到设备的复杂性,接口的设计应当要能面对多种设备的适用性。例如: + +* 对于用户界面的控件,要考虑到不同屏幕尺寸的大小。 +* 对于数据的存储,要考虑到不同大小的存储空间。 +* 对于用户输入事件,要考虑不同的用户交互方式:触摸、语音、按键等。 + +当然,有一些API只在某些特定设备上才有,例如: + +* 健康类传感器只在穿戴设备上有 +* 车控类接口只在车机设备上有 + +这种情况,请参考[《 SysCap使用指南》](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/syscap.md),来标定API的适用范围。 + +### 一致性 + +* **规则26:保证术语、概念的一致性** + +为了容易理解,接口在命名和说明上应当注意术语和概念的一致性,不应该出现“方言”。基于场景的业务模型抽象,形成OpenHarmony的连贯、一致、自恰的业务概念。 + + + +在这方面,应当遵循以下原则: + +1. 每个概念只应该有 **唯一** 的一个术语,同一个对象不应该有两个名称。 +2. 术语命名应该是 **贴切的** , **可解释** , **易理解** 。 +4. 术语的定义应当 **精准、无二义**。 +5. 对于业界通用术语, **不应该重新定义** ,应当遵循业内做法。 + +总体来说,要避免随意添加术语概念,尽可能以[《OpenHarmony 技术术语集》](https://gitee.com/openharmony/docs/blob/master/zh-cn/glossary.md)为准。如果需要,可以在术语集中新增词条。 + +* **规则27:保证设备间行为一致性** + +在默认情况下,同一个接口在不同的设备上应当保证行为是一致的。 + +对于因为设备形态而导致的行为不一致,应当给予开发者充分的说明,并且提供相应的检查机制。 + +* **规则28:注意版本演进一致性** + +在默认情况下,所有接口应当保证在系统版本演进的情况下,其行为是一致的。如果在新版本上出现了行为不兼容的变更,最低要求是需要对应用的目标版本做区分处理。 + +简单而言:接口的行为变更不能影响已经开发完的应用。 + +* **规则29:命名风格保持一致** + +在一些 API 设计的场景中,即使命名已经做到准确,但在有些情况下仍然可能碰到不一致的场景。比如,API 中经常会看到 picture 和 image、path 和 url 混用的情况,这两组词的意思非常接近,容易出现混乱。在指代同一内容时,应该使用相同的命名。 + +例如,下面这些接口都是为了获取媒体资源,但是命名风格不一致。 + +```js +declare function getMediaAsserts(): Array; +declare function getAudios(): Array; +declare function getVideos(): Array; +declare function getImages(): Array; +``` + +应该修改为: + +```js +function getMediaAsserts(): Array; +function getAudioAsserts(): Array; +function getVideoAsserts(): Array; +function getImageAsserts(): Array; +``` + +* **规则30:参数顺序保持一致** + +为了开发者便于理解,对于同一个命名空间或者是同一个模块来说,其成套的接口的参数顺序应当是一致的。 + +例如:`deviceId`和`missionId`在单个接口中的顺序没有强制要求,但是在同一模块接口中必须保持顺序一致。 + +```js +function getMissionInfo(deviceId: string, missionId: number): Promise; +function getMissionSnapShot(deviceId: string, missionId: number): Promise; + +// 正确 +function getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise; + +// 错误 +function getLowResolutionMissionSnapShot(missionId: number, deviceId: string): Promise; +``` + +* **规则31:同步/异步风格一致** + +异步接口应该可以通过入参和返回值判断出来,风格上要保持统一。例如: + +```javascript +// Callback形式 +function getDefaultDisplay(callback: AsyncCallback): void; +// Promise形式 +function getDefaultDisplay(): Promise; +``` + +如果同时提供了同步和异步接口,可以在同步函数名后加上后缀`Sync`加以区别,例如: + +```js +function getDefaultDisplaySync(): Display; +``` + +如果只提供了同步接口,且返回值不是`void`,可以不用加后缀,例如: + +```js +function registerMissionListener(listener: MissionListener): number; +``` + +### 兼容性 + +* **规则32:注意新旧系统版本的兼容性** + +API 变更的成本非常高,在设计之初就应该做尽可能完备的考虑。但是API变更始终是系统发展过程中不可避免的。 + +API 变更要保证向后兼容原则,API 变更后,废弃的 API 要在源码和文档中显著标识 `deprecated`,并引导开发者使用变更后 API 。 + +废弃的 API 要保证其功能仍然可用,至少保留5个版本。5个版本后,在充分告知开发者,并给与充分的时间供开发者修改后,可予以删除。 + +* **规则33:二进制向后兼容性** + +二进制兼容,指版本演进后,开发者已有程序不用重新编译可正常链接、运行。这也意味着,二进制兼容是保证在版本升级的情况下,对象实例的内存布局不会发生变化。 + +以C++接口为例,常见破坏二进制兼容的API变更包括: + +1. 任何API元素删除 +2. 添加新的虚函数 +3. 改变类的继承 +4. 改变虚函数声明时的顺序 +5. 添加新的非静态成员变量 +6. 改变非静态成员变量的声明顺序 + +由于C接口相比C++接口在二进制兼容性上有天然的优势,所以OpenHarmony的Native API推荐使用C接口定义。 + +### API资料 + +API的很多信息需要通过文档和资料进行说明,因此,配套的这些内容也应当做好质量管理。 + +* **规则34:模块、命名空间、类、函数需要包含基础说明** + +每个模块、命名空间、类和函数都需要包含基本的说明。 + +对于关键模块、复杂模块需要有详细的说明。 + +说明采用英文的形式。 + +* **规则35:使用场景说明清晰** + +所有接口应当提供示例代码,覆盖常见使用场景。 + +复杂接口需要详细说明使用场景。可以在接口的说明上增加详细教程的链接。 + +* **规则36:接口说明准确** + +接口说明的文字不应该出现拼写错误或者错别字。 + +所有代码示例应当保证能够正常运行。如果接口在不同版本上存在行为不一致,则需要针对每种情况做详细说明。 + +对于废弃接口,需做明确标记,并做好替代接口说明。 + +* **规则37:参数说明准确** + +对于API的每一个参数,都应该说明清楚。例如: + +* 如果是非简单类型,则需说明清楚是否允许参数为空 +* 如果是枚举类型,则需针对每个枚举值说明清楚使用场景 +* 如果是可选参数,则需说明清楚什么时候该传参,什么时候可省略 + +**规则38:返回值/异常定义准确** + +如果接口有返回值/异常,需要在接口说明中描述完整。例如: + +```js +/** + * Sync function of rename. + * @param {string} path - path. + * @returns {void} rmdir success. + * @throws {BusinessError} 401 - if type of path is not string. + * @throws {BusinessError} 201 - if permission denied. + * @syscap SystemCapability.FileManagement.File.FileIO + * @since 7 + */ +declare function rmdirSync(path: string): void; +``` + +* **规则39:元信息完备** + +接口的方法说明上应当包含基本的元信息,例如:`@syscap`、`@since`等。 + +元信息描述了API自身的基本信息。工具和SDK会利用这个信息进行相应的处理,例如:针对已经废弃的接口会给出警告提示。 + +* **规则40:风格一致** + +API的说明资料,在风格和样式上应当保持一致。例如,文字的加粗,资料图片的配色等。 + +### 组织方式 + +* **规则41:分层合理** + +操作系统通常是以分层的模型来进行架构的。这意味着每一层要解决不同层次上的问题。 + +因此,接口的设计也要注意相应的层次。 + +可以使用建筑行业来进行类比:所有的建筑都会包含墙体和房间的门。墙体是有砖块构成的,门是有木料构成的。在这种情况下,抽象可能会分为下面几层: + +* 第一层是基本都原材料,包括水泥、沙子、木材等 +* 第二层是用原材料构建出来的建筑元素,例如:门、窗户、墙体等 +* 第三层是房间的种类,例如:卧室、卫生间、客厅等 +* 最后,最上面一层是各种不同用途的建筑。例如:酒店、公寓等 + +这里每一层所要考虑的概念和要处理的问题都是不一样的,请仔细思考你提供的API是在哪一个层次上。 + +* **规则42:模块划分合理** + +大家不仅要关注水平层面的分层,也应该关注垂直层面的划分。因此,模块的组织也同样重要。OpenHarmony的接口是以命名空间的形式组织的。一个命名空间通常对应了一个模块。 + +从子系统的角度,一个较小的子系统应该尽可能将接口放在同一个命名空间中。较大的子系统,可以提供多个命名空间。 + +* **规则43:应用描述文件也是接口的一部分** + +接口的英文是Interface,这个词还有界面的意思。操作系统提供给开发者的接口并不仅仅是编程接口。任何公开给开发者的机制,都是API的一部分。 + +这其中,最明显的就是应用描述文件,这些文件也需要按照接口规范一样的规则来管理。 + +### 质量属性 + +* **规则44:性能满足要求** + +操作系统所提供的接口所有上层应用都可能会使用到,因此,其实现的性能应当是能够满足实际要求的。 + +下面是一些举例: + +1. 应及时响应,避免调用者等待;如果API调用执行时间过长应设计为异步方式。 +2. 接口存在大量数据传输时,应考虑使用共享内存、消息队列等。 +3. 尽可能减少新增进程实体。 +4. 对使用资源的API调用需要能及时释放资源,异常场景具备容错机制,保障资源及时释放。 + +* **规则45:功耗设计合理** + +OpenHarmony 操作系统在设计之初就需要面向多种不同类型的设备,这些设备中绝大多数是无源设备。因此,功耗的考虑是毋庸置疑的。 + +每个功能/机制在实现上应当把功耗的合理性作为最基本的要求。除此之外,对于高功耗的接口应当在说明中给开发者充足的解释,并且对于使用方式给与足够的指导。 + +同时,在使用上要避免开发者错误的使用。例如,在设备锁屏之后,或者应用切换到后台之后,就应当停止高功耗的行为。 + +另外,还应当注意在版本演进过程中,功耗不出现劣化。 + +* **规则46:需要保证可测试性** + +完备的自动化测试用例,可以带来很多好处: + +1. 开发过程中,提前快速发现问题,提高接口质量。 +2. 版本迭代时,保证代码修改不影响功能,提高代码修改的信心。 +3. 确保接口向后兼容性。 + +所以,对于一个OpenHarmony API,都要求做到以下几点: + +1. 新增API必须同步交付API自动化测试用例,用例100%覆盖API接口。 +2. 用例场景单一,单条用例覆盖接口单个功能场景,简化单条用例代码逻辑。 +3. 用例执行高效,每条用例执行时间控制在毫秒级。 +4. 用例执行全自动化:接口用例需要达成100%自动化。 +5. 用例有效性:用户要求必须存在断言,且不能仅是检查是否抛出异常,需要有功能逻辑的断言。 + + + +* **规则47:考虑环境适应性** + +考虑到用户的个性化,操作系统通常会提供一些环境自定义的能力,例如:语言国际化、浅色/深色主题、字体大小等。 + +对于这方面相关的接口,在开发者没有传递指定参数的情况下,应当能够更加当前所属的环境,自适应的返回相应环境下的结果。 + +## 发布后评价说明 + +尽管在API发布前已经做了多方面规则约束,但总可能还有一些问题在开发者使用之后才能发现。 + +即便是这样,但并不意味着在设计API之初不需要考虑这些问题。 + +相反的,大家应当时刻避免发布后问题的发生。 + +如果在接口发布后,发现了下面几条规则问题的发生,则该模块的接口质量是比较差的。 + +### 稳定性 + +* **规则48:接口废弃率/变更率越低越好** + +对于接口来说,稳定是其最重要的属性。 + +这是因为接口的废弃和行为变更将极大的影响开发者的维护效率。考虑上多种设备类型、多个系统版本,这个问题会变得更加复杂。 + +设计出能保证长期稳定,持续兼容的接口是每个API设计者应当追求的目标。 + +接口的废弃率/变更率与接口的质量在一定程度上成反比。 + +### 安全性 + +* **规则49:避免接口被滥用** + +所有接口在设计上,应当考虑到不能被过度滥用。滥用既可能是数量上的滥用,也可能是范围上的滥用。 + +例如:对于用户公共数据(相册、联系人等)的访问,对于长时间后台运行的能力,都可能被滥用。 + +对于数量滥用的防止,可以考虑“仅一次授权”这样的机制。 + +在实现上,可以根据调用者的身份进行相应的限制。 + +当然,无论是哪种限制,都应该在接口说明中说明清楚。并且在检测到过度滥用的情况下,有相应的返回值告知调用者。 + +* **规则50:避免接口被利用** + +被滥用是指接口的使用超出了原先预期的限制。而被利用是指:接口可以被用来造成负面影响,例如攻击系统。 + +无论开发者以何种方式使用OpenHarmony提供的接口,如果某个接口,或某些接口组合调用导致系统出现了问题,那么就一定接口本身存在问题。 + +特别的,如果某些接口(无论在何种情况下)一旦调用就可以使用系统崩溃,或者进入不能工作的场景,或者能够窃取用户数据,这是绝对不允许的。这就要求API的设计者从API被调用的所有可能都场景上进行考虑,避免一些极端情况的发生。 + +### 可维护性 + +* **规则51:能承载业务能力演进** + +考虑到操作系统的一些较大特性,需要经过数年才能打磨完成。因此接口在设计上应当考虑今后的可扩展性。 + +随着能力的演进,如果出现了在新版本上新起了一组新的接口,而废弃了原先旧的接口,那么就是接口的设计上存在问题。这是应当避免的。 + +* **规则52:功能扩展后不影响原先行为** + +随着OpenHarmony 操作系统版本的演进,一些接口新增了参数,或者一些参数新增了新的选项是很常见的一种行为。 + +但是,在这种情况下,一定要考虑清楚对于过往已存在行为的一致性。不应当因为新的场景的引入,而破坏了原先存在的行为。 + +这里需要遵循的原则是:如果在新版本上行为要发生变化,只允许针对目标版本是新版本的应用生效。对于目标版本是旧版本的应用应当继续保持原先的行为。 + +* **规则53:文档和资料应当配套更新** + +当大家在更新接口实现的时候,一定要记得更新接口的说明。从兼容性的角度来看,不能修改原先存在的行为。通常应当提供新的接口来完成新的功能。 + +但在下面的情况下,可以考虑修改既有接口的行为: + +1. 缺陷的修复。 +2. 性能/功耗的改进。 +3. 为接口拓展新的特性或场景,但不影响原有特性或场景逻辑。 + +第1、2种情况,通常在Release Note里面说明;第3种情况就需要在接口说明上表述清楚。 + +### 不可替代性 + +* **规则54:保证API之间正交** + +正交(Orthogonality),意味着多个接口之间不应该出现重合的功能。 + +例如:一个接口提供了创建用户账号的能力。另外一个接口包含了创建用户并登录的功能。如果是这样,就应该把第二个接口拆开,只保留单独登录的功能。 + +如果将接口的能力画成一个个图形,那么这些图形之间不应该出现重叠交错的想象。对于同一个层级的接口,不应该出现某个接口提供了1、2、3功能,另外一个接口又提供了2、3、4功能这种情况发生。 + +当然,为了便于调用,允许将一些接口组合成一个更高阶的接口。这通常是抽象层次的不一样,并非是同一个层次的重叠。 + +### 开发者反馈 + +* **规则55:关注开发者反馈** + +尽管API在正式发布之前,会经过试用阶段,但考虑到试用时间和试用范围是有限的,实际上无法保证能避免所有问题。 + +因此,在接口正式发布之后,也应该继续关注开发者的反馈。 + +开发者反馈可能分为以下几种情况: + +* 希望提供更多API来满足目前不能实现的功能,这种情况可以将需求导入到下个版本的规划中。 +* 反馈API的行为与文档描述不一致,这通常是缺陷,应当尽快修复。如果是文档的问题,也应当尽快修改。 +* 反馈接口设计不合理,可能是命名或者参数设置存在问题,这种情况就需要考虑API废弃同时用新API代替。 + +在一些情况下,可能要变更已经发布的API行为。这种情况下,应当要注意:行为变化只能发生在新开发的应用上,对于已经发布的应用,不能产生行为变化。API提供者可以根据应用的目标API版本来进行判断。 + +在最坏的情况下,需要将既存API废弃,提供新的API代替。 diff --git a/zh-cn/device-dev/Readme-CN.md b/zh-cn/device-dev/Readme-CN.md index 4d91198caa68f0429f228338a0943d074ae4b1b3..677035cc831d7956b4a79354aaf2a9139775bde1 100644 --- a/zh-cn/device-dev/Readme-CN.md +++ b/zh-cn/device-dev/Readme-CN.md @@ -25,7 +25,8 @@ - 小型系统芯片移植案例 - [小型设备STM32MP1芯片移植案例](porting/porting-stm32mp15xx-on-smallsystem.md) - 标准系统芯片移植案例 - - [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md) - 子系统开发 - 内核 - [轻量系统内核](kernel/kernel-mini-overview.md) @@ -53,10 +54,8 @@ - [轻量和小型系统设备开发示例](guide/device-wlan-led-control.md) - [标准系统设备开发示例](guide/device-clock-guide.md) - 调测 - - [测试用例开发](subsystems/subsys-testguide-test.md) + - [设备测试](device-test/Readme-CN.md) - [调测工具](subsystems/subsys-toolchain-hdc-guide.md) -- XTS认证 - - [XTS认证](subsystems/subsys-xts-guide.md) - 工具 - [Docker编译环境](get-code/gettools-acquire.md) - [IDE集成开发环境](get-code/gettools-ide.md) diff --git a/zh-cn/device-dev/dev-board-on-the-master.md b/zh-cn/device-dev/dev-board-on-the-master.md index 20237f39f24e9563bbe0210a2a23b5b9af766d4a..7572a1f05386011b9bd6031d807aaa4288e57055 100644 --- a/zh-cn/device-dev/dev-board-on-the-master.md +++ b/zh-cn/device-dev/dev-board-on-the-master.md @@ -1,6 +1,6 @@ # OpenHarmony开发板列表 -当前社区共支持17款开发板,详见下表。 +当前社区共支持22款开发板,详见下表。 更详细的开发板信息展示,请参考:http://ci.openharmony.cn/developBoard/list ## 标准系统开发板 @@ -13,6 +13,7 @@ |MILOS_Standard0|NXP i.MX8M Mini|主要能力:
基于 NXP i.MX8M Mini处理器,1.8G Hz主频。接⼝外设丰富:LVDS显⽰、MIPI-DSI信号引出、 MIPI-CSI摄像头接⼝、⽀持⾳频输⼊输出、千兆⽹、多路USB、多串⼝、等多种通信接⼝|⾼性能仪器仪表(⼯业及医疗)、⼯业控制及⼈机互动装置、智能交通、智慧消防、智慧楼宇等。|代码仓:
[device_soc_nxp](https://gitee.com/openharmony/device_soc_nxp)
[device_board_osware](https://gitee.com/openharmony/device_board_osware)
[vendor_osware](https://gitee.com/openharmony/vendor_osware)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds| |扬帆开发板|RK3399|主要能力:
扬帆开发板基于RK3399芯片平台;RK3399的CPU采用big.LITTLE核心架构,采用双核Cortex-A72大核+四核Cortex-A53小核结构。在整数,浮点数,内存,整体性能,功耗和核心面积方面都进行了重大改进。RK3399的GPU采用四核ARM的新一代高端图像处理器Mali-T860,集成了更多的带宽压缩技术(如智能叠加,ASTC和本地像素存储),并支持更多的图形和计算接口。|互动广告机、互动数字标牌、智能自助终端、智能零售终端、工控主机、机器人设备等。|代码仓:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_isoftstone](https://gitee.com/openharmony/device_board_isoftstone)
[vendor_isoftstone](https://gitee.com/openharmony/vendor_isoftstone)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds| |致远开发板|T507|主要能力:
致远开发板搭载了全志工业级T507芯片,该芯片集成四核CortexTM – A53 CPU、G31 MP2 GPU、多路视频输出接口(RGB/2*LVDS/HDMI/CVBS OUT)、多路视频输入接口(MIPI CSI/BT656/BT1120),支持4K@60fps H.265解码,4K@25fps H.264解码,DI,3D降噪,自动调色系统和梯形校正模块可以提供提供流畅的用户体验和专业的视觉效果|工业控制、智能驾舱、智慧家居、智慧电力、在线教育等。|代码仓:
[device_soc_allwinner](https://gitee.com/openharmony/device_soc_allwinner)
[device_board_isoftstone](https://gitee.com/openharmony/device_board_isoftstone)
[vendor_isoftstone](https://gitee.com/openharmony/vendor_isoftstone)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds| +|金星系列智慧屏khdvk_3566b开发板|RK3566|主要能力:
采用ROCKCHIP RK3566 Cortex-A55 四核处理器,提供多路通用显示屏接口,接口类型丰富,支持外设拓展,满足多种人机交互场景的需求。|适用于平板电脑,学习机,人脸别相关,主要产品有匝机通道,刷脸支付,工业机器人,医疗检测设备,车牌识别,广告机、数字标牌、智能自助终端、智能零售终端等相关产品。|代码仓:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_kaihong](https://gitee.com/openharmony/device_board_kaihong)
[vendor_kaihong](https://gitee.com/openharmony/vendor_kaihong)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds| ## 小型系统开发板 @@ -33,4 +34,7 @@ |B91 Generic Starter Kit|TLSR9x|主要能力:
泰凌微公司的B91 Generic Starter Kit是一个可用于评估TLSR9系列芯片组的硬件平台,BLE,BLE Mesh,Zigbee 3.0, Thread和2.4GHz私有协议等多种适用于2.4GHz接口标准的应用程序都可以用它来进行开发。|智能家居、连接类模组。|代码仓:
[device_soc_telink](https://gitee.com/openharmony/device_soc_telink)
[device_board_telink](https://gitee.com/openharmony/device_board_telink)
[vendor_telink](https://gitee.com/openharmony/vendor_telink)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds| |cst85_wblink|cst85f01|主要能力:
cst85_wblink开发板是基于芯海科技cst85f01芯片,由芯海科技出品的一款高性能、多功能、高性价比AIoT SoC开发板。cst85_wblink开发板,集成双频WiFi + 双模蓝牙,支持标准的802.11 a/b/g/n/协议,支持BT/BLE 5.0协议,内建多种容量的RAM(最大992KB)和Flash(最大16MB),支持MIPI DSI及CSI,适用于快速开发物联网(IOT)及智能设备的Wi-Fi、蓝牙的应用。
适配案例:
[cst85_wblink适配案例](porting/porting-cst85f01-combo-demo.md)|物联网、智能家居等。|代码仓:
[device_soc_chipsea](https://gitee.com/openharmony/device_soc_chipsea)
[device_board_chipsea](https://gitee.com/openharmony/device_board_chipsea)
[vendor_chipsea](https://gitee.com/openharmony/vendor_chipsea)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | |Neptune100| W800 |主要能力:
润和 Neptune100开发板基于联盛德W800芯片,是一款Wi-Fi &蓝牙双模SoC开发板,支持标准的802.11 b/g/n协议,内置完整的TCP/IP协议栈,集成蓝牙基带处理器,支持BT/BLE4.2协议;具备丰富的数字接口,内置QFlash、SPI、UART、GPIO、I2C、I2S、7816等;具备强大的安全特性,支持多种硬件加解密算法,内置DSP、浮点运算单元与安全引擎,支持代码安全权限设置,内置2MBFlash存储器,支持固件加密存储、固件签名、安全调试、安全升级等多项安全措施。
适配案例:
[Neptune100适配案例](porting/porting-w800-combo-demo.md)|物联网、智能家居、连接类产品。|代码仓:
[device_soc_winnermicro](https://gitee.com/openharmony/device_soc_winnermicro)
[device_board_hihope](https://gitee.com/openharmony/device_board_hihope)
[vendor_hihope](https://gitee.com/openharmony/vendor_hihope)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | -|小凌派-RK2206| RK2206 |主要能力:
小凌派-RK2206开发板主控器为瑞芯微高性能、高性价比的RK2206芯片,搭载OpenHarmony轻量级操作系统,内置WiFi/AP功能、NFC功能、液晶显示接口以及E53接口,E53接口兼容各类传感器模块,便于多样化的IoT物联网应用;目前小凌派-RK2006开发板已经拥有20+个成熟的应用案例,以及完善的教学课程。|智慧城市、智能家居、智慧教学、智慧车载以及智慧医疗等。|代码仓:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_lockzhiner](https://gitee.com/openharmony/device_board_lockzhiner)
[vendor_lockzhiner](https://gitee.com/openharmony/vendor-lockzhiner)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | \ No newline at end of file +|小凌派-RK2206| RK2206 |主要能力:
小凌派-RK2206开发板主控器为瑞芯微高性能、高性价比的RK2206芯片,搭载OpenHarmony轻量级操作系统,内置WiFi/AP功能、NFC功能、液晶显示接口以及E53接口,E53接口兼容各类传感器模块,便于多样化的IoT物联网应用;目前小凌派-RK2006开发板已经拥有20+个成熟的应用案例,以及完善的教学课程。|智慧城市、智能家居、智慧教学、智慧车载以及智慧医疗等。|代码仓:
[device_soc_rockchip](https://gitee.com/openharmony/device_soc_rockchip)
[device_board_lockzhiner](https://gitee.com/openharmony/device_board_lockzhiner)
[vendor_lockzhiner](https://gitee.com/openharmony/vendor-lockzhiner)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | +|HPM6750EVK2开发板| HPM6700 |主要能力:
HPM6700/6400 系列 MCU 是来自上海先楫半导体科技有限公司的高性能实时 RISC-V 微控制器,为工业自动化及边缘计算应用提供了极大的算力、高效的控制能力及丰富的多媒体功能。|工业控制、边缘计算等。|代码仓:
[device_soc_hpmicro](https://gitee.com/openharmony/device_soc_hpmicro)
[device_board_hpmicro](https://gitee.com/openharmony/device_board_hpmicro)
[vendor_hpmicro](https://gitee.com/openharmony/vendor_hpmicro)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | +|NiobeU4| ESP32U4WDH |主要能力:
NiobeU4是基于ESP32U4WDH推出的物联网设备开发套件,集成2.4GHz Wifi和蓝牙双模,具有超高的射频性能、稳定性、通用性和可靠性,以及超低的功耗,适用于各种应用场景;NiobeU4开发套件支持NFC非接触式通讯功能,工作频率13.56MHz。|适用于低功耗、低电压和低成本要求的非接触读写器应用;支持锂电池供电和充放电管理;开发套件提供一个开箱即用的智能硬件解决方案,方便开发者验证和开发自己的软件和功能。|代码仓:
[device_soc_esp](https://gitee.com/openharmony/device_soc_esp)
[device_board_openvalley ](https://gitee.com/openharmony/device_board_openvalley)
[vendor_openvalley](https://gitee.com/openharmony/vendor_openvalley)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | +|BK7235开发板| BK7235 |主要能力:
本仓用于放置BK7235开发板相关内容,BK7235是博通集成(BEKEN)研发的一款针对IoT应用、高度集成的WiFi6+BLE 5.2 combo SoC,具有资源丰富、性能强大、更高的安全性等特点。|物联网、智能家居、连接类产品。|代码仓:
[device_soc_beken](https://gitee.com/openharmony/device_soc_beken)
[device_board_beken](https://gitee.com/openharmony/device_board_beken)
[vendor_beken](https://gitee.com/openharmony/vendor_beken)
社区每日构建版本获取地址:
http://ci.openharmony.cn/dailys/dailybuilds | \ No newline at end of file diff --git a/zh-cn/device-dev/device-dev-guide.md b/zh-cn/device-dev/device-dev-guide.md index 29273529556c779558fa807f53c64d14704ced30..597e90485906b086f9b319758a50eebf7bf71edf 100644 --- a/zh-cn/device-dev/device-dev-guide.md +++ b/zh-cn/device-dev/device-dev-guide.md @@ -51,6 +51,6 @@ OpenHarmony也提供了一系列可选的系统组件,方便设备开发者按 | 快速入门 | 快速熟悉OpenHarmony环境搭建、编译、烧录、调测、运行 | - [快速入门](quick-start/Readme-CN.md)| | 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [内核开发指南](kernel/kernel-standard-overview.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-all.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | | 进阶开发 | 结合系统能力开发智能设备 | - [时钟应用开发指导](guide/device-clock-guide.md)
- [平台驱动开发示例](guide/device-driver-demo.md)
- [外设驱动开发示例](guide/device-outerdriver-demo.md) | -| 移植适配 | - 针对特定芯片做移植适配
- 快速移植OpenHarmony Linux内核的方法| - [标准系统芯片移植指导](porting/standard-system-porting-guide.md)
- [一种快速移植OpenHarmony Linux内核的方法](porting/porting-linux-kernel.md)
- [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md)| +| 移植适配 | - 针对特定芯片做移植适配
- 快速移植OpenHarmony Linux内核的方法| - [标准系统芯片移植指导](porting/standard-system-porting-guide.md)
- [一种快速移植OpenHarmony Linux内核的方法](porting/porting-linux-kernel.md)
- [标准系统方案之瑞芯微RK3568移植案例](porting/porting-dayu200-on_standard-demo.md)
- [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md)| | 贡献组件 | 为OpenHarmony贡献功能组件 | - [HPM Part 介绍](hpm-part/hpm-part-about.md)
- [HPM Part 开发指导](hpm-part/hpm-part-development.md)
- [HPM Part 参考](hpm-part/hpm-part-reference.md) | | 参考 | 为开发者提供常见的问题解答和HDI接口参考 | - [常见问题](faqs/faqs-overview.md)
- [HDI接口参考](reference/hdi-apis/Readme-CN.md) | diff --git a/zh-cn/device-dev/device-test/Readme-CN.md b/zh-cn/device-dev/device-test/Readme-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..cb28b27227a24f2fec3d7fe7422ed3b2f354e8af --- /dev/null +++ b/zh-cn/device-dev/device-test/Readme-CN.md @@ -0,0 +1,5 @@ +# 设备测试 + +- [developer_test开发者自测试执行框架使用指导](developer_test.md) +- [xdevice测试调度框架使用指导](xdevice.md) +- [XTS用例开发指导](xts.md) diff --git a/zh-cn/device-dev/device-test/developer_test.md b/zh-cn/device-dev/device-test/developer_test.md index 05f860d7e9dc7420a75d0f9daa8fb378979fe9ee..e7bbd639df1de2da2b155e6ac147ce3e55d0125f 100644 --- a/zh-cn/device-dev/device-test/developer_test.md +++ b/zh-cn/device-dev/device-test/developer_test.md @@ -20,10 +20,104 @@ OpenHarmony系统开发人员在新增或修改代码之后,希望可以快速 ## 环境准备 -开发自测试框架依赖于python运行环境,python版本为3.8.X,在使用测试框架之前可参阅以下方式进行配置。 +开发自测试框架依赖于python运行环境,python版本为3.7.5及以上版本,在使用测试框架之前可参阅以下方式进行配置。 - - [环境配置](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-testguide-test.md#%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE) - - [源码获取](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md) +源码获取可[参考](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/sourcecode-acquire.md)。 + +### 自测试框架基础环境依赖 + +| 环境依赖 | 版本型号 | 详细说明 | +| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| 操作系统 | Ubuntu18.04及以上 | 代码编译环境 | +| Linux系统扩展组件 | libreadline-dev | 命令行读取插件 | +| python | 3.7.5版本及以上 | 测试框架语言 | +| python插件 | pyserial 3.3及以上、paramiko2.7.1及以上、setuptools40.8.0及以上、rsa4.0及以上 | pserial:支持python的串口通信;paramiko:支持python使用SSH协议;setuptools:支持python方便创建和分发python包;rsa:支持python rsa加密 | +| NFS Server | haneWIN NFS Server 1.2.50及以上或者 NFS v4及以上 | 支持设备通过串口连接,使用轻量、小型设备 | +| HDC | 1.1.0 | 支持设备通过HDC连接 | + + + +1. 安装Linux扩展组件readline,安装命令如下: + + ```bash + sudo apt-get install libreadline-dev + ``` + 安装成功提示如下: + ``` + Reading package lists... Done + Building dependency tree + Reading state information... Done + libreadline-dev is already the newest version (7.0-3). + 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. + ``` + +2. 安装setuptools插件,安装命令如下: + ```bash + pip3 install setuptools + ``` + 安装成功提示如下: + ``` + Requirement already satisfied: setuptools in d:\programs\python37\lib\site-packages (41.2.0) + ``` + +3. 安装paramiko插件,安装命令如下: + ```bash + pip3 install paramiko + ``` + 安装成功提示如下: + ``` + Installing collected packages: pycparser, cffi, pynacl, bcrypt, cryptography, paramiko + Successfully installed bcrypt-3.2.0 cffi-1.14.4 cryptography-3.3.1 paramiko-2.7.2 pycparser-2.20 pynacl-1.4.0 + ``` + +4. 安装python的rsa插件,安装命令如下: + ```bash + pip3 install rsa + ``` + 安装成功提示如下: + ``` + Installing collected packages: pyasn1, rsa + Successfully installed pyasn1-0.4.8 rsa-4.7 + ``` + +5. 安装串口插件pyserial,安装命令如下: + ```bash + pip3 install pyserial + ``` + 安装成功提示如下: + ``` + Requirement already satisfied: pyserial in d:\programs\python37\lib\site-packages\pyserial-3.4-py3.7.egg (3.4) + ``` + +6. 如果设备仅支持串口输出测试结果,则需要安装NFS Server + + > 针对小型或轻量设备 + + - Windows环境下安装,安装haneWIN NFS Server1.2.50软件包。 + - Linux环境下安装,安装命令如下: + ```bash + sudo apt install nfs-kernel-server + ``` + 安装成功提示如下: + ``` + Reading package lists... Done + Building dependency tree + Reading state information... Done + nfs-kernel-server is already the newest version (1:1.3.4-2.1ubuntu5.3). + 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. + ``` + +7. 如果设备支持HDC连接,则需要安装HDC工具,安装流程请参考[HDC-OpenHarmony设备连接器](https://gitee.com/openharmony/developtools_hdc_standard/blob/master/README_zh.md)。 + + +### 环境依赖检查 + +| 检查项 | 操作 | 满足环境 | +| -------------------------------------------------- | --------------------------------------------------- | ------------------------- | +| 检查python安装成功 | 命令行窗口执行命令:python --version | 版本不小于3.7.5即可 | +| 检查python扩展插件安装成功 | 打开test/developertest目录,执行start.bat或start.sh | 可进入提示符“>>>”界面即可 | +| 检查NFS Server启动状态(被测设备仅支持串口时检测) | 通过串口登录开发板,执行mount命令挂载NFS | 可正常挂载文件目录即可 | +| 检查HDC安装成功 | 命令行窗口执行命令:hdc_std -v | 版本不小于1.1.0即可 | ## 编写测试用例 @@ -41,7 +135,7 @@ calculator_sub_test.cpp ``` 用例示例 -``` +```c++ /* * Copyright (c) 2021 XXXX Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -128,7 +222,7 @@ HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) 2.引用测试框架头文件和命名空间 -``` +```c++ #include using namespace testing::ext; @@ -136,13 +230,13 @@ using namespace testing::ext; 3.添加被测试类的头文件 -``` +```c++ #include "calculator.h" ``` 4.定义测试套(测试类) -``` +```c++ class CalculatorSubTest : public testing::Test { public: static void SetUpTestCase(void); @@ -169,13 +263,13 @@ void CalculatorSubTest::SetUp(void) void CalculatorSubTest::TearDown(void) { // input testcase teardown step,teardown invoked after each testcases -} +}== ``` > **注意:** 在定义测试套时,测试套名称应与编译目标保持一致,采用大驼峰风格。 5.测试用例实现,包含用例注释和逻辑实现 -``` +```c++ /** * @tc.name: integer_sub_001 * @tc.desc: Verify the sub function. @@ -242,7 +336,7 @@ AppInfoTest.js - 用例示例 -``` +```js /* * Copyright (C) 2021 XXXX Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); @@ -316,13 +410,13 @@ describe("AppInfoTest", function () { */ ``` 2. 导入被测api和jsunit测试库 - ``` + ```js import app from '@system.app' import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' ``` 3. 定义测试套(测试类) - ``` + ```js describe("AppInfoTest", function () { beforeAll(function() { // input testsuit setup step,setup invoked before all testcases @@ -345,7 +439,7 @@ describe("AppInfoTest", function () { }) ``` 4. 测试用例实现 - ``` + ```JS /* * @tc.name:appInfoTest001 * @tc.desc:verify app info is not null @@ -360,7 +454,7 @@ describe("AppInfoTest", function () { expect(info != null).assertEqual(true) }) ``` - > **注意:** @tc.require: 格式必须以AR/SR或issue开头: 如:issueI56WJ7 + > **注意:** @tc.require: 格式必须以issue开头: 如:issueI56WJ7 **Fuzz测试** @@ -546,7 +640,7 @@ ohos_js_unittest("GetAppInfoJsTest") { ``` config.json为hap编译所需配置文件,需要开发者根据被测sdk版本配置“target”项,其余项可默认,具体如下所示: -``` +```json { "app": { "bundleName": "com.example.myapplication", @@ -659,7 +753,7 @@ group("unittest") { 2.在resource目录下对应的模块目录中创建一个ohos_test.xml文件,文件内容格式如下: -``` +```xml @@ -689,7 +783,7 @@ ohos_unittest("CalculatorSubTest") { 在执行测试用例之前,针对用例使用设备的不同,需要对相应配置进行修改,修改完成即可执行测试用例。 #### user_config.xml配置 -``` +```xml @@ -788,7 +882,7 @@ ohos_unittest("CalculatorSubTest") { >**说明:** 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 3. 修改user_config.xml - ``` + ```xml false diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001154351160.jpg b/zh-cn/device-dev/device-test/figures/zh-cn_image_0000001154351160.jpg similarity index 100% rename from zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001154351160.jpg rename to zh-cn/device-dev/device-test/figures/zh-cn_image_0000001154351160.jpg diff --git a/zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001200230833.gif b/zh-cn/device-dev/device-test/figures/zh-cn_image_0000001200230833.gif similarity index 100% rename from zh-cn/device-dev/subsystems/figures/zh-cn_image_0000001200230833.gif rename to zh-cn/device-dev/device-test/figures/zh-cn_image_0000001200230833.gif diff --git a/zh-cn/device-dev/subsystems/subsys-xts-guide.md b/zh-cn/device-dev/device-test/xts.md similarity index 99% rename from zh-cn/device-dev/subsystems/subsys-xts-guide.md rename to zh-cn/device-dev/device-test/xts.md index 36f1f7ab87265f684f24487de5b107332ef05c15..dbe852a1830d6def4f1630d31d12f6689a568b79 100644 --- a/zh-cn/device-dev/subsystems/subsys-xts-guide.md +++ b/zh-cn/device-dev/device-test/xts.md @@ -28,7 +28,7 @@ XTS子系统当前包括acts与tools软件包: ## 目录 - + ``` /test/xts ├── acts # 测试代码存放目录 @@ -102,7 +102,7 @@ XTS子系统当前包括acts与tools软件包: 当前使用的测试框架是hctest,hctest测试框架支持使用C语言编写测试用例,是在开源测试框架unity的基础上进行增强和适配。 1. 用例目录规范:测试用例存储到test/xts/acts仓中。 - + ``` ├── acts │ └──subsystem_lite @@ -116,14 +116,14 @@ XTS子系统当前包括acts与tools软件包: 2. src目录下用例编写样例。 1.引用测试框架 - + ``` #include "hctest.h" ``` 2. 使用宏定义LITE_TEST_SUIT定义子系统、模块、测试套件名称 - + ``` /** * @brief register a test suite named "IntTestSuite" @@ -159,7 +159,7 @@ XTS子系统当前包括acts与tools软件包: 3. 测试模块的配置文件(BUILD.gn)样例: 在每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后静态库的名称、依赖的头文件、依赖的库等;具体写法如下: - + ``` import("//test/xts/tools/lite/build/suite_lite.gni") hctest_suite("ActsDemoTest") { @@ -175,7 +175,7 @@ XTS子系统当前包括acts与tools软件包: 4. acts下BUILD.gn增加编译选项。 需要将测试模块加入到acts目录下的编译脚本中,编译脚本路径:test/xts/acts/build_lite/BUILD.gn。 - + ``` lite_component("acts") { ... @@ -220,7 +220,7 @@ XTS子系统当前包括acts与tools软件包: 当前使用的测试框架是hcpptest,hcpptest测试框架是在开源的googletest测试框架的基础上进行的增强和适配。 1. 规范用例目录:测试用例存储到test/xts/acts仓中。 - + ``` ├── acts │ └──subsystem_lite @@ -236,14 +236,14 @@ XTS子系统当前包括acts与tools软件包: 需要引用gtest.h 如:\#include "gtest/gtest.h" - + ``` #include "gtest/gtest.h" ``` 2. 定义Setup与TearDown - + ``` using namespace std; using namespace testing::ext; @@ -271,10 +271,10 @@ XTS子系统当前包括acts与tools软件包: 普通测试用例的定义:HWTEST(测试套名称, 测试用例名称, 用例标注)。 包含SetUp和TearDown的测试用例的定义 :HWTEST_F(测试套名称, 测试用例名称,用例标注)。 - + 宏定义包括三个参数:测试套件名称,测试用例名称,用例属性(测试类型、用例粒度、用例级别)。 - + ``` HWTEST_F(TestSuite, TestCase_0001, Function | MediumTest | Level1) { // do something @@ -285,7 +285,7 @@ XTS子系统当前包括acts与tools软件包: 每个测试模块目录下新建BUILD.gn编译文件,用于指定编译后可执行文件的名称、依赖的头文件、依赖的库等;具体写法如下。每个测试模块将独立编译成.bin可执行文件, 该文件可直接push到单板上进行测试。 举例: - + ``` import("//test/xts/tools/lite/build/suite_lite.gni") hcpptest_suite("ActsDemoTest") { @@ -309,7 +309,7 @@ XTS子系统当前包括acts与tools软件包: 4. acts目录下增加编译选项(BUILD.gn)样例: 将测试模块加入到acts目录下的编译脚本中,编译脚本为:test/xts/acts/build_lite/BUILD.gn。 - + ``` lite_component("acts") { ... @@ -346,7 +346,7 @@ XTS子系统当前包括acts与tools软件包: 格式:mount [nfs服务器IP]:[/nfs共享目录] [/开发板目录] nfs 举例: - + ``` mount 192.168.1.10:/nfs /nfs nfs ``` @@ -377,7 +377,7 @@ XTS子系统当前包括acts与tools软件包: 用例编写语法采用 jasmine 的标准语法,格式支持ES6格式。 1. 规范用例目录:测试用例存储到entry/src/main/js/test目录。 - + ``` ├── BUILD.gn │ └──entry @@ -394,7 +394,7 @@ XTS子系统当前包括acts与tools软件包: ``` 2. index.js示例 - + ``` // 拉起js测试框架,加载测试用例 import {Core, ExpectExtend} from 'deccjsunit/index' @@ -425,7 +425,7 @@ XTS子系统当前包括acts与tools软件包: ``` 3. 单元测试用例示例 - + ``` // Example1: 使用HJSUnit进行单元测试 describe('appInfoTest', function () { @@ -447,7 +447,7 @@ hap包编译请参考[标准系统js应用开发指导](https://developer.harmon 1. 全量编译 **命令**: - + ``` ./build.sh suite=acts system_size=standard ``` @@ -464,7 +464,7 @@ hap包编译请参考[标准系统js应用开发指导](https://developer.harmon Windows工作台下安装python3.7及以上版本,确保工作台和测试设备正常连接。 **测试执行目录**(对应编译生成的out/release/suites/acts目录) - + ``` ├── testcase # 测试套文件存放目录 │ └──xxx.hap # 测试套可执行hap文件 @@ -480,7 +480,7 @@ Windows工作台下安装python3.7及以上版本,确保工作台和测试设 2. 界面启动后,输入用例执行指令。 - 全量执行 - + ``` run acts ``` @@ -490,7 +490,7 @@ Windows工作台下安装python3.7及以上版本,确保工作台和测试设 ![zh-cn_image_0000001200230833](figures/zh-cn_image_0000001200230833.gif) - 模块执行(具体模块可以查看\acts\testcases\) - + ``` run –l ActsSamgrTest ``` diff --git a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md index 8fddafeda91cdbea167912c57ad3a991b1d6b980..d817ef48a6a1796bdf5dd9e33743d23d84d2a6d6 100755 --- a/zh-cn/device-dev/driver/driver-peripherals-camera-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-camera-des.md @@ -47,7 +47,8 @@ Camera模块主要针对相机预览、拍照、视频流等场景,对这些 ### 接口说明
-注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/camera/v1_0/)。 +注:以下接口列举的为IDL接口描述生成的对应C++语言函数接口,接口声明见idl文件(/drivers/interface/camera/v1_0/)。 +在HDI使用中下发的配置参数不能超出GetCameraAbility上报的能力范围。即使通过UpdateSettings、CommitStreams、Capture等接口可以下发超出该范围的配置参数,且接口调用不会返回失败,但设置后的行为是不确定的。 - icamera_device.h | 功能描述 | 接口名称 | @@ -634,7 +635,7 @@ Camera驱动的开发过程主要包含以下步骤: 在/drivers/peripheral/camera/hal/init目录下有一个关于Camera的demo,开机后会在/vendor/bin下生成可执行文件ohos_camera_demo,该demo可以完成Camera的预览,拍照等基础功能。下面我们就以此demo为例讲述怎样用HDI接口去编写预览PreviewOn()和拍照CaptureON()的用例,可参考[ohos_camera_demo](https://gitee.com/openharmony/drivers_peripheral/tree/master/camera/hal/init)。 -1. 在main函数中构造一个CameraDemo 对象,该对象中有对Camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。 +1. 在main函数中构造一个CameraDemo 对象,该对象中有对Camera初始化、启停流、释放等控制的方法。下面mainDemo->InitSensors()函数为初始化CameraHost,mainDemo->InitCameraDevice()函数为初始化CameraDevice。 ```c++ int main(int argc, char** argv) @@ -849,7 +850,7 @@ Camera驱动的开发过程主要包含以下步骤: } ``` - CaptureON()接口调用streamOperator的Capture()方法获取Camera数据并轮转buffer,拉起一个线程接收相应类型的数据。 + CaptureON()接口调用streamOperator的Capture()方法获取Camera数据并轮转buffer,拉起一个线程接收相应类型的数据。 ```c++ RetCode OhosCameraDemo::CaptureON(const int streamId, diff --git a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md index 04dfe33a0f2735bd355b6dea4b3c24da14410310..8167cb3617097d6a990324989389d902cb741778 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-lcd-des.md @@ -1,18 +1,24 @@ # LCD - ## 概述 -LCD(Liquid Crystal Display)显示器的驱动,通过对显示器上电、初始化显示器驱动IC(Integrated Circuit)内部寄存器等操作,使其可以正常工作。 +### 功能简介 + +LCD(Liquid Crystal Display)驱动编程,通过对显示器上电、初始化显示器驱动IC(Integrated Circuit)内部寄存器等操作,使其可以正常工作。 + +基于HDF(Hardware Driver Foundation)[驱动框架](../driver/driver-hdf-overview.md)构建的Display驱动模型作用如下: + +- 为LCD器件驱动开发提供了基础驱动框架,提升驱动开发效率。 -基于HDF(Hardware Driver Foundation)[驱动框架](../driver/driver-hdf-overview.md)构建的Display驱动模型,为LCD器件驱动开发提供了基础驱动框架,提升驱动开发效率。同时,便于开发的器件驱动实现跨OS、跨芯片平台迁移。基于HDF驱动框架的Display驱动模型如下所示。 +- 便于开发的器件驱动实现跨OS、跨芯片平台迁移。 + +基于HDF驱动框架的Display驱动模型如下所示: **图1** 基于HDF驱动框架的Display驱动模型 ![image](figures/基于HDF驱动框架的Display驱动模型.png "基于HDF驱动框架的Display驱动模型") - Display驱动模型主要由平台驱动层、芯片平台适配层、LCD器件驱动层三部分组成。驱动模型基于HDF驱动框架开发,通过Platform层和OSAL层提供的接口,屏蔽内核形态的差异,使得器件驱动可以便利的迁移到不同OS及芯片平台。模型向上对接Display公共HAL层,支撑HDI(Hardware Device Interface)接口的实现,通过Display-HDI对图形服务提供各类驱动能力接口。 - Display平台驱动层:通过HDF提供的IOService数据通道,与公共HAL层对接,集中接收并处理各类上层调用指令。 @@ -23,8 +29,7 @@ Display驱动模型主要由平台驱动层、芯片平台适配层、LCD器件 基于Display驱动模型开发LCD驱动,可以借助平台提供的各种能力及接口,较大程度的降低器件驱动的开发周期和难度,提升开发效率。 - -## 接口说明 +### 基本概念 LCD接口通常可分为MIPI DSI接口、TTL接口和LVDS接口,常用的是MIPI DSI接口和TTL接口,下面对常用的MIPI DSI接口和TTL接口作简要介绍。 @@ -34,7 +39,7 @@ LCD接口通常可分为MIPI DSI接口、TTL接口和LVDS接口,常用的是MI ![image](figures/MIPI-DSI接口.png "MIPI-DSI接口") - MIPI DSI接口是MIPI(Mobile Industry Processor Interface)联盟定义的显示接口,主要用于移动终端显示屏接口,接口数据传输遵循MIPI协议,MIPI DSI接口为数据接口,传输图像数据,通常情况下MIPI DSI接口的控制信息以MIPI包形式通过MIPI DSI接口发送到对端IC,不需要额外的外设接口。 + MIPI DSI接口是MIPI(Mobile Industry Processor Interface)联盟定义的显示接口,主要用于移动终端显示屏接口,接口数据传输遵循MIPI协议,MIPI DSI接口为数据接口,传输图像数据,通常情况下MIPI DSI接口的控制信息以MIPI包形式通过MIPI DSI接口发送到对端IC,不需要额外的外设接口。 - TTL接口 @@ -42,14 +47,31 @@ LCD接口通常可分为MIPI DSI接口、TTL接口和LVDS接口,常用的是MI ![image](figures/TTL接口.png "TTL接口") - TTL(Transistor Transistor Logic)即晶体管-晶体管逻辑,TTL电平信号由TTL器件产生,TTL器件是数字集成电路的一大门类,它采用双极型工艺制造,具有高速度、低功耗和品种多等特点。 + ​ TTL(Transistor Transistor Logic)即晶体管-晶体管逻辑,TTL电平信号由TTL器件产生,TTL器件是数字集成电路的一大门类,它采用双极型工艺制造,具有高速度、低功耗和品种多等特点。 + + TTL接口是并行方式传输数据的接口,有数据信号、时钟信号和控制信号(行同步、帧同步、数据有效信号等),在控制信号控制下完成数据传输。通常TTL接口的LCD,内部寄存器读写需要额外的外设接口,比如SPI接口、I2C接口等。 - TTL接口是并行方式传输数据的接口,有数据信号、时钟信号和控制信号(行同步、帧同步、数据有效信号等),在控制信号控制下完成数据传输。通常TTL接口的LCD,内部寄存器读写需要额外的外设接口,比如SPI接口、I2C接口等。 +### 约束与限制 +开发者在进行LCD驱动编程过程中,除了要关注IC的型号,还要关注LCD外围电路设计、基带芯片的LCD接口单元、背光IC的控制等多个方面,同时包括软件的上层程序。这些都是影响开发者在调试LCD驱动的影响因素。 -## 开发步骤 +## 开发指导 -Display驱动模型基于HDF驱动框架、Platform接口及OSAL接口开发,可以做到不区分OS(LiteOS、Linux)和芯片平台(Hi35xx、Hi38xx、V3S等),为LCD器件提供统一的驱动模型。开发步骤如下: +### 场景介绍 + +LCD驱动模型属于驱动基础适配模块,第三方需要适配OpenHarmony系统时,需要进行LCD驱动适配。LCD驱动适配基于HDF驱动框架、Platform接口及OSAL接口开发,可以做到不区分OS(LiteOS、Linux)和芯片平台(Hi35xx、Hi38xx、V3S等),为LCD器件提供统一的驱动模型。 + +### 接口说明 + +表1 LCD驱动适配所需接口 + +| 接口名 | 描述 | +| :------------------------------------------------------ | ------------------- | +| display :: host | 设备描述配置 | +| static int32_t LcdResetOn(void) | 设置Reset Pin脚状态 | +| int32_t SampleEntryInit(struct HdfDeviceObject *object) | 器件驱动入口函数 | + +### 开发步骤 1. 添加LCD驱动相关的设备描述配置。 @@ -58,305 +80,228 @@ Display驱动模型基于HDF驱动框架、Platform接口及OSAL接口开发, 3. 添加器件驱动,并在驱动入口函数Init中注册Panel驱动数据,驱动数据接口主要包括如下接口: - LCD上下电 + 根据LCD硬件连接,使用Platform接口层提供的GPIO操作接口操作对应LCD管脚,例如复位管脚、IOVCC管脚,上电时序参考LCD供应商提供的SPEC。 + - 发送初始化序列 + 根据LCD硬件接口,使用Platform接口层提供的I2C、SPI、MIPI等接口,下载LCD初始化序列,初始化参数序列可以参考LCD供应商提供的SPEC。 -4. 根据需求实现HDF框架其他接口,比如Release接口。 - -5. 根据需求使用HDF框架可创建其他设备节点,用于业务逻辑或者调试功能。 - - -## 开发实例 - -添加设备描述配置: - - -``` -/* Display驱动相关的设备描述配置 */ -display :: host { - hostName = "display_host"; - /* Display平台驱动设备描述 */ - device_hdf_disp :: device { - device0 :: deviceNode { - policy = 2; - priority = 200; - permission = 0660; - moduleName = "HDF_DISP"; - serviceName = "hdf_disp"; - } - } - /* SoC适配层驱动设备描述 */ - device_hi35xx_disp :: device { - device0 :: deviceNode { - policy = 0; - priority = 199; - moduleName = "HI351XX_DISP"; - } - } - /* LCD器件驱动设备描述 */ - device_lcd :: device { - device0 :: deviceNode { - policy = 0; - priority = 100; - preload = 0; - moduleName = "LCD_Sample"; - } - device1 :: deviceNode { - policy = 0; - priority = 100; - preload = 2; - moduleName = "LCD_SampleXX"; - } - } -} -``` - -SOC适配层驱动,以Hi35xx系列芯片为例,需要在本层驱动中适配MIPI等和芯片平台相关的配置,示例如下: - - -``` -static int32_t MipiDsiInit(struct PanelInfo *info) -{ - int32_t ret; - struct DevHandle *mipiHandle = NULL; - struct MipiCfg cfg; - - mipiHandle = MipiDsiOpen(0); - if (mipiHandle == NULL) { - HDF_LOGE("%s: MipiDsiOpen failure", __func__); - return HDF_FAILURE; - } - cfg.lane = info->mipi.lane; - cfg.mode = info->mipi.mode; - cfg.format = info->mipi.format; - cfg.burstMode = info->mipi.burstMode; - cfg.timing.xPixels = info->width; - cfg.timing.hsaPixels = info->hsw; - cfg.timing.hbpPixels = info->hbp; - cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; - cfg.timing.vsaLines = info->vsw; - cfg.timing.vbpLines = info->vbp; - cfg.timing.vfpLines = info->vfp; - cfg.timing.ylines = info->height; - /* 0 : no care */ - cfg.timing.edpiCmdSize = 0; - cfg.pixelClk = CalcPixelClk(info); - cfg.phyDataRate = CalcDataRate(info); - /* config mipi device */ - ret = MipiDsiSetCfg(mipiHandle, &cfg); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:MipiDsiSetCfg failure", __func__); - } - MipiDsiClose(mipiHandle); - HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__, - cfg.pixelClk, cfg.phyDataRate); - return ret; -} -``` - -LCD器件驱动示例如下: - - -``` -#define RESET_GPIO 5 -#define MIPI_DSI0 0 -#define BLK_PWM1 1 -#define PWM_MAX_PERIOD 100000 -/* backlight setting */ -#define MIN_LEVEL 0 -#define MAX_LEVEL 255 -#define DEFAULT_LEVEL 100 - -#define WIDTH 480 -#define HEIGHT 960 -#define HORIZONTAL_BACK_PORCH 20 -#define HORIZONTAL_FRONT_PORCH 20 -#define HORIZONTAL_SYNC_WIDTH 10 -#define VERTICAL_BACK_PORCH 14 -#define VERTICAL_FRONT_PORCH 16 -#define VERTICAL_SYNC_WIDTH 2 -#define FRAME_RATE 60 - -/* PanelInfo结构体结构体 */ -struct PanelInfo { - uint32_t width; - uint32_t height; - uint32_t hbp; - uint32_t hfp; - uint32_t hsw; - uint32_t vbp; - uint32_t vfp; - uint32_t vsw; - uint32_t frameRate; - enum LcdIntfType intfType; - enum IntfSync intfSync; - struct MipiDsiDesc mipi; - struct BlkDesc blk; - struct PwmCfg pwm; -}; - -/* LCD屏的初始化序列 */ -static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A }; -static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 }; -static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B }; -static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A }; -static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C }; -static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C }; -static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; -static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; -static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; -static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; -static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; -static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; -static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; -static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; -static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; -static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; -static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; -static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; -static uint8_t g_payLoad18[] = { - 0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, - 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, - 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 -}; -static uint8_t g_payLoad19[] = { 0x11 }; -static uint8_t g_payLoad20[] = { 0x29 }; - -struct DsiCmdDesc g_OnCmd[] = { - { 0x29, 0, sizeof(g_payLoad0), g_payLoad0 }, - { 0x29, 0, sizeof(g_payLoad1), g_payLoad1 }, - { 0x29, 0, sizeof(g_payLoad2), g_payLoad2 }, - { 0x29, 0, sizeof(g_payLoad3), g_payLoad3 }, - { 0x29, 0, sizeof(g_payLoad4), g_payLoad4 }, - { 0x29, 0, sizeof(g_payLoad5), g_payLoad5 }, - { 0x29, 0, sizeof(g_payLoad6), g_payLoad6 }, - { 0x29, 0, sizeof(g_payLoad7), g_payLoad7 }, - { 0x29, 0, sizeof(g_payLoad8), g_payLoad8 }, - { 0x29, 0, sizeof(g_payLoad9), g_payLoad9 }, - { 0x23, 0, sizeof(g_payLoad10), g_payLoad10 }, - { 0x29, 0, sizeof(g_payLoad11), g_payLoad11 }, - { 0x29, 0, sizeof(g_payLoad12), g_payLoad12 }, - { 0x29, 0, sizeof(g_payLoad13), g_payLoad13 }, - { 0x29, 0, sizeof(g_payLoad14), g_payLoad14 }, - { 0x29, 0, sizeof(g_payLoad15), g_payLoad15 }, - { 0x29, 0, sizeof(g_payLoad16), g_payLoad16 }, - { 0x23, 0, sizeof(g_payLoad17), g_payLoad17 }, - { 0x29, 1, sizeof(g_payLoad18), g_payLoad18 }, - { 0x05, 120, sizeof(g_payLoad19), g_payLoad19 }, - { 0x05, 120, sizeof(g_payLoad20), g_payLoad20 }, -}; -static DevHandle g_mipiHandle = NULL; -static DevHandle g_pwmHandle = NULL; - -/* 设置Reset Pin脚状态 */ -static int32_t LcdResetOn(void) -{ - int32_t ret; - ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); - if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioSetDir failure, ret:%d", ret); - return HDF_FAILURE; - } - ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); - if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioWrite failure, ret:%d", ret); - return HDF_FAILURE; - } - /* delay 20ms */ - OsalMSleep(20); - return HDF_SUCCESS; -} - -static int32_t SampleInit(void) -{ - /* 获取MIPI DSI设备操作句柄 */ - g_mipiHandle = MipiDsiOpen(MIPI_DSI0); - if (g_mipiHandle == NULL) { - HDF_LOGE("%s: MipiDsiOpen failure", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t SampleOn(void) -{ - int32_t ret; - /* LCD上电序列 */ - ret = LcdResetOn(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: LcdResetOn failure", __func__); - return HDF_FAILURE; - } - if (g_mipiHandle == NULL) { - HDF_LOGE("%s: g_mipiHandle is null", __func__); - return HDF_FAILURE; - } - /* 使用mipi下发初始化序列 */ - int32_t count = sizeof(g_OnCmd) / sizeof(g_OnCmd[0]); - int32_t i; - for (i = 0; i < count; i++) { - ret = MipiDsiTx(g_mipiHandle, &(g_OnCmd[i])); - if (ret != HDF_SUCCESS) { - HDF_LOGE("MipiDsiTx failure"); - return HDF_FAILURE; - } - } - /* 将mipi切换到HS模式 */ - MipiDsiSetHsMode(g_mipiHandle); - return HDF_SUCCESS; -} - -/* PanelInfo结构体变量 */ -static struct PanelInfo g_panelInfo = { - .width = WIDTH, /* width */ - .height = HEIGHT, /* height */ - .hbp = HORIZONTAL_BACK_PORCH, /* horizontal back porch */ - .hfp = HORIZONTAL_FRONT_PORCH, /* horizontal front porch */ - .hsw = HORIZONTAL_SYNC_WIDTH, /* horizontal sync width */ - .vbp = VERTICAL_BACK_PORCH, /* vertical back porch */ - .vfp = VERTICAL_FRONT_PORCH, /* vertical front porch */ - .vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */ - .frameRate = FRAME_RATE, /* frame rate */ - .intfType = MIPI_DSI, /* panel interface type */ - .intfSync = OUTPUT_USER, /* output timing type */ - /* mipi config info */ - .mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT }, - /* backlight config info */ - .blk = { BLK_PWM, MIN_LEVEL, MAX_LEVEL, DEFAULT_LEVEL }, - .pwm = { BLK_PWM1, PWM_MAX_PERIOD }, -}; - -/* 器件驱动需要适配的基础接口 */ -static struct PanelData g_panelData = { - .info = &g_panelInfo, - .init = SampleInit, - .on = SampleOn, - .off = SampleOff, - .setBacklight = SampleSetBacklight, -}; - -/* 器件驱动入口函数 */ -int32_t SampleEntryInit(struct HdfDeviceObject *object) -{ - HDF_LOGI("%s: enter", __func__); - if (object == NULL) { - HDF_LOGE("%s: param is null!", __func__); - return HDF_FAILURE; - } - /* 器件驱动接口注册,ops提供给平台驱动调用 */ - if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { - HDF_LOGE("%s: PanelDataRegister error!", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -struct HdfDriverEntry g_sampleDevEntry = { - .moduleVersion = 1, - .moduleName = "LCD_SAMPLE", - .Init = SampleEntryInit, -}; - -HDF_INIT(g_sampleDevEntry); -``` +4. (可选)根据需求实现HDF框架其他接口,比如Release接口。 + +5. (可选)根据需求使用HDF框架可创建其他设备节点,用于业务逻辑或者调试功能。 + +### 开发实例 + +以Hi35xx系列芯片为例,根据开发步骤所述,介绍LCD驱动的详细适配过程。 + +1. 添加设备描述配置(vendor/bearpi/bearpi_hm_micro/hdf_config/device_info/device_info.hcs) + + ```c++ + /* Display驱动相关的设备描述配置 */ + display :: host { + hostName = "display_host"; + /* Display平台驱动设备描述 */ + device_hdf_disp :: device { + device0 :: deviceNode { + policy = 2; + priority = 200; + permission = 0660; + moduleName = "HDF_DISP"; + serviceName = "hdf_disp"; + } + } + /* SoC适配层驱动设备描述 */ + device_hi35xx_disp :: device { + device0 :: deviceNode { + policy = 0; + priority = 199; + moduleName = "HI351XX_DISP"; + } + } + /* LCD器件驱动设备描述 */ + device_lcd :: device { + device0 :: deviceNode { + policy = 0; + priority = 100; + preload = 0; + moduleName = "LCD_Sample"; + } + device1 :: deviceNode { + policy = 0; + priority = 100; + preload = 2; + moduleName = "LCD_SampleXX"; + } + } + } + ``` + +2. SoC平台驱动适配层中适配对应的芯片平台驱动(drivers/hdf_core/framework/model/display/driver/adapter_soc/hi35xx_disp.c) + + ```c++ + /* Display驱动适配MIPI等和芯片平台相关的配置 */ + static int32_t MipiDsiInit(struct PanelInfo *info) + { + int32_t ret; + struct DevHandle *mipiHandle = NULL; + struct MipiCfg cfg; + + mipiHandle = MipiDsiOpen(0); + if (mipiHandle == NULL) { + HDF_LOGE("%s: MipiDsiOpen failure", __func__); + return HDF_FAILURE; + } + cfg.lane = info->mipi.lane; + cfg.mode = info->mipi.mode; + cfg.format = info->mipi.format; + cfg.burstMode = info->mipi.burstMode; + cfg.timing.xPixels = info->width; + cfg.timing.hsaPixels = info->hsw; + cfg.timing.hbpPixels = info->hbp; + cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; + cfg.timing.vsaLines = info->vsw; + cfg.timing.vbpLines = info->vbp; + cfg.timing.vfpLines = info->vfp; + cfg.timing.ylines = info->height; + /* 0 : no care */ + cfg.timing.edpiCmdSize = 0; + cfg.pixelClk = CalcPixelClk(info); + cfg.phyDataRate = CalcDataRate(info); + /* config mipi device */ + ret = MipiDsiSetCfg(mipiHandle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiSetCfg failure", __func__); + } + MipiDsiClose(mipiHandle); + HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__, + cfg.pixelClk, cfg.phyDataRate); + return ret; + } + ``` + +3. 添加器件(drivers/hdf_core/framework/model/display/driver/panel/mipi_icn9700.c) + + - 驱动定义相关接口信息 + + ```c++ + #define RESET_GPIO 5 + #define MIPI_DSI0 0 + #define BLK_PWM1 1 + #define PWM_MAX_PERIOD 100000 + /* backlight setting */ + #define MIN_LEVEL 0 + #define MAX_LEVEL 255 + #define DEFAULT_LEVEL 100 + #define WIDTH 480 + #define HEIGHT 960 + #define HORIZONTAL_BACK_PORCH 20 + #define HORIZONTAL_FRONT_PORCH 20 + #define HORIZONTAL_SYNC_WIDTH 10 + #define VERTICAL_BACK_PORCH 14 + #define VERTICAL_FRONT_PORCH 16 + #define VERTICAL_SYNC_WIDTH 2 + #define FRAME_RATE 60 + ``` + + - 定义PanelInfo结构体 + + ```c++ + struct PanelInfo { + uint32_t width; + uint32_t height; + uint32_t hbp; + uint32_t hfp; + uint32_t hsw; + uint32_t vbp; + uint32_t vfp; + uint32_t vsw; + uint32_t frameRate; + enum LcdIntfType intfType; + enum IntfSync intfSync; + struct MipiDsiDesc mipi; + struct BlkDesc blk; + struct PwmCfg pwm; + }; + ``` + + - 初始化LCD屏 + + ```c++ + static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A }; + static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 }; + static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B }; + static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A }; + static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C }; + static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C }; + static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; + static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; + static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; + static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; + static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; + static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; + static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; + static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; + static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; + static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; + static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; + static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; + static uint8_t g_payLoad18[] = { + 0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, + 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, + 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 + }; + static uint8_t g_payLoad19[] = { 0x11 }; + static uint8_t g_payLoad20[] = { 0x29 }; + static DevHandle g_mipiHandle = NULL; + static DevHandle g_pwmHandle = NULL; + ``` + + - 设置Reset Pin脚状态 + + ```c++ + static int32_t LcdResetOn(void) + { + int32_t ret; + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir failure, ret:%d", ret); + return HDF_FAILURE; + } + ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioWrite failure, ret:%d", ret); + return HDF_FAILURE; + } + /* delay 20ms */ + OsalMSleep(20); + return HDF_SUCCESS; + } + ``` + + - 器件驱动入口函数 + + ```c++ + int32_t SampleEntryInit(struct HdfDeviceObject *object) + { + HDF_LOGI("%s: enter", __func__); + if (object == NULL) { + HDF_LOGE("%s: param is null!", __func__); + return HDF_FAILURE; + } + /* 器件驱动接口注册,ops提供给平台驱动调用 */ + if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { + HDF_LOGE("%s: PanelDataRegister error!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + struct HdfDriverEntry g_sampleDevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_SAMPLE", + .Init = SampleEntryInit, + }; + + HDF_INIT(g_sampleDevEntry); + ``` \ No newline at end of file diff --git a/zh-cn/device-dev/guide/device-camera-control-example.md b/zh-cn/device-dev/guide/device-camera-control-example.md index bca04953d80f8c642b5d2ed062075a15fe61282e..248c80a80ccc0bd498626784465e9d1f935d0296 100644 --- a/zh-cn/device-dev/guide/device-camera-control-example.md +++ b/zh-cn/device-dev/guide/device-camera-control-example.md @@ -3,7 +3,7 @@ 本示例将运行源码中的camera示例代码,通过本示例可以实现使用开发板进行拍照、录像及预览等功能。 - 本示例源码路径为“applications/sample/camera/media/camera\_sample.cpp”。 -- 在运行本示例前需先完成编译烧录、运行镜像等步骤,相关操作请参考[小型系统快速入门](../quick-start/Readme-CN.md)。 +- 在运行本示例前需先完成编译烧录、运行镜像等步骤,相关操作请参考[小型系统快速入门](../quick-start/quickstart-overview.md)。 >![](../public_sys-resources/icon-note.gif) **说明:** >开发板启动后默认会加载launcher应用,应用的图形界面默认显示在媒体图层上方,会影响camera\_sample的演示结果,因此需要在编译或是打包时去掉launcher应用。 diff --git a/zh-cn/device-dev/guide/device-camera-visual-run.md b/zh-cn/device-dev/guide/device-camera-visual-run.md index 7eb2de2d3794931d7cf31c037f8f4b4c3ed47ecc..568daf93ad342fc2aab77d09d94aee1bb5314dc6 100644 --- a/zh-cn/device-dev/guide/device-camera-visual-run.md +++ b/zh-cn/device-dev/guide/device-camera-visual-run.md @@ -1,6 +1,6 @@ # 真机运行 -应用编译打包后即可安装到开发板。安装应用前需要先完成[DevEco Device Tool的安装配置](https://device.harmonyos.com/cn/docs/ide/user-guides/service_introduction-0000001050166905),然后将OpenHarmony烧录到开发板并运行。编译烧录、运行镜像的基本操作请参考快速入门手册:[小型系统快速入门](../quick-start/Readme-CN.md)。完成镜像运行,系统正常启动后,执行如下步骤安装或卸载三方应用。 +应用编译打包后即可安装到开发板。安装应用前需要先完成[DevEco Device Tool的安装配置](https://device.harmonyos.com/cn/docs/ide/user-guides/service_introduction-0000001050166905),然后将OpenHarmony烧录到开发板并运行。编译烧录、运行镜像的基本操作请参考快速入门手册:[小型系统快速入门](../quick-start/quickstart-overview.md)。完成镜像运行,系统正常启动后,执行如下步骤安装或卸载三方应用。 1. 将IDE编译的未签名应用安装包和安装工具(镜像文件生成目录中的dev\_tools)放在sdcard中,将sdcard插入开发板卡槽。 2. 应用安装默认要校验签名,需要执行以下命令,关闭签名校验。 diff --git a/zh-cn/device-dev/guide/device-outerdriver-demo.md b/zh-cn/device-dev/guide/device-outerdriver-demo.md index 38fe3a47a2a23eb8380f711e7ef4d9324060916a..fd46b29cf824963008e11effb17e4ccf544b76c9 100644 --- a/zh-cn/device-dev/guide/device-outerdriver-demo.md +++ b/zh-cn/device-dev/guide/device-outerdriver-demo.md @@ -25,7 +25,7 @@ Input驱动模型核心部分由设备管理层、公共驱动层、器件驱动 ## 环境搭建 -环境准备具体操作请参考[快速入门环境搭建章节](../quick-start/Readme-CN.md)。 +环境准备具体操作请参考[快速入门环境搭建章节](../quick-start/quickstart-overview.md)。 >![](../public_sys-resources/icon-notice.gif) **须知:** >本示例针对OpenHarmony轻量系统、小型系统、标准系统都适用,本文以标准系统为例。其他系统的开发者可参考对应系统的指导文档进行环境搭建。 @@ -316,7 +316,7 @@ Input模型由三层驱动组成,开发者适配一款全新触摸屏驱动只 其中touch\_gt911.o为本示例中追加的内容。 -2. 具体编译及烧录操作请参考[标准系统快速入门的编译及烧录章节](../quick-start/Readme-CN.md)。 +2. 具体编译及烧录操作请参考[标准系统快速入门的编译及烧录章节](../quick-start/quickstart-overview.md)。 ## 调试验证 diff --git a/zh-cn/device-dev/guide/device-wlan-led-control.md b/zh-cn/device-dev/guide/device-wlan-led-control.md index f5c5aa15d37ca16a1c2a3c9ea959cbd0fa15e83f..d5fe17254f18645276d9cb133e5805bd75d592cf 100644 --- a/zh-cn/device-dev/guide/device-wlan-led-control.md +++ b/zh-cn/device-dev/guide/device-wlan-led-control.md @@ -1,8 +1,5 @@ # LED外设控制 -- [概述](#section14639174516337) -- [开发](#section13857170163412) -- [验证](#section1949121910344) ## 概述 @@ -10,7 +7,7 @@ OpenHarmony WLAN模组基于Hi3861平台提供了丰富的外设操作能力, ## 开发 -1. 请先完成[轻量系统快速入门](../quick-start/Readme-CN.md)。 +1. 请先完成[轻量系统快速入门](../quick-start/quickstart-overview.md)。 LED控制参考示例存放于applications/sample/wifi-iot/app/iothardware/led\_example.c文件中。 diff --git a/zh-cn/device-dev/kernel/kernel-mini-overview.md b/zh-cn/device-dev/kernel/kernel-mini-overview.md index 4f8c132c2dcd4b8c99f7a7355208f5345b3bdf9b..7cb5cb28c7b870af88ed3ed7829599a9b8908c40 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-overview.md +++ b/zh-cn/device-dev/kernel/kernel-mini-overview.md @@ -98,7 +98,7 @@ LiteOS-M内核的编译构建系统是一个基于gn和ninja的组件化构建 ### 搭建系统基础环境 -在搭建各个开发板环境前,需要完成OpenHarmony系统基础环境搭建。系统基础环境主要是指OpenHarmony的编译环境和开发环境,详细介绍请参考官方站点[快速入门环境搭建部分](../quick-start/Readme-CN.md)。开发者需要根据环境搭建文档完成环境搭建。 +在搭建各个开发板环境前,需要完成OpenHarmony系统基础环境搭建。系统基础环境主要是指OpenHarmony的编译环境和开发环境,详细介绍请参考官方站点[快速入门环境搭建部分](../quick-start/quickstart-overview.md)。开发者需要根据环境搭建文档完成环境搭建。 ### 获取OpenHarmony源码 diff --git a/zh-cn/device-dev/porting/Readme-CN.md b/zh-cn/device-dev/porting/Readme-CN.md index 6881fa3d3f4952992005b1399383af66b7bc9498..ce5b474e48144b84d7b14854c3920359c1141ea0 100644 --- a/zh-cn/device-dev/porting/Readme-CN.md +++ b/zh-cn/device-dev/porting/Readme-CN.md @@ -66,3 +66,5 @@ repo init -u https://gitee.com/openharmony-sig/manifest.git -b master -m devboar - [小型设备STM32MP1芯片移植案例](porting-stm32mp15xx-on-smallsystem.md) - 标准系统芯片移植案例 - [标准系统方案之瑞芯微RK3568移植案例](porting-dayu200-on_standard-demo.md) + - [标准系统方案之瑞芯微RK3566移植案例](https://gitee.com/openharmony/vendor_kaihong/blob/master/khdvk_3566b/porting-khdvk_3566b-on_standard-demo.md) + - [标准系统方案之扬帆移植案例](porting-yangfan-on_standard-demo.md) diff --git a/zh-cn/device-dev/porting/figures/isoftstone/yangfan-camera-01.png b/zh-cn/device-dev/porting/figures/isoftstone/yangfan-camera-01.png deleted file mode 100644 index 444898b86792d8ee4ebcbd61b1223c44faa2bee6..0000000000000000000000000000000000000000 Binary files a/zh-cn/device-dev/porting/figures/isoftstone/yangfan-camera-01.png and /dev/null differ diff --git a/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md b/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md index 5806ea15a5a72d3b363573fdebcbe0a57388b65b..3f2930abbdb933d16d32022117ab4986c9e961ca 100644 --- a/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md +++ b/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md @@ -2,7 +2,7 @@ ## 编译环境搭建 -首先请搭建OpenHarmony基础环境,相关操作请参考[快速入门环境搭建章节](../quick-start/Readme-CN.md)。用户态和LiteOS-A的内核态编译均使用llvm编译器编译,安装方法在搭建基础环境中已提供。若选择移植linux内核,请执行如下命令安装gcc-arm-linux-gnueabi交叉编译工具链,用于编译linux内核态镜像: +首先请搭建OpenHarmony基础环境,相关操作请参考[快速入门环境搭建章节](../quick-start/quickstart-overview.md)。用户态和LiteOS-A的内核态编译均使用llvm编译器编译,安装方法在搭建基础环境中已提供。若选择移植linux内核,请执行如下命令安装gcc-arm-linux-gnueabi交叉编译工具链,用于编译linux内核态镜像: ``` diff --git a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md index 2c737a460b35f81ad954e496a21467a42c8f53da..6324fd3087ba4ca5b0fa9973c6edaac7bc2ea939 100644 --- a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md +++ b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md @@ -1185,7 +1185,7 @@ _hdf_drivers_end = .; #### 添加XTS子系统 -`XTS`测试参考资料见[xts参考资料](../subsystems/subsys-xts-guide.md),进行`XTS`子系统适配需要添加`xts_acts`与`xts_tools`组件,直接在`config.json`配置即可,配置如下: +`XTS`测试参考资料见[xts参考资料](../device-test/xts.md),进行`XTS`子系统适配需要添加`xts_acts`与`xts_tools`组件,直接在`config.json`配置即可,配置如下: { "subsystem": "xts", diff --git a/zh-cn/device-dev/porting/porting-thirdparty-cmake.md b/zh-cn/device-dev/porting/porting-thirdparty-cmake.md index 72b327ff5ed244779d6fea182041418c01ec2a84..5c39c8d40d8437ef048b41fdb73c0df947d129ac 100644 --- a/zh-cn/device-dev/porting/porting-thirdparty-cmake.md +++ b/zh-cn/device-dev/porting/porting-thirdparty-cmake.md @@ -107,7 +107,7 @@ CMake方式可通过指定工具链进行交叉编译,修改并编译该库, ## 测试 1. 搭建OpenHarmony环境 - 以Hi3516DV300为例,编译出OpenHarmony镜像,烧写到开发板,相关操作可参考[快速入门小型系统部分](../quick-start/Readme-CN.md)。 + 以Hi3516DV300为例,编译出OpenHarmony镜像,烧写到开发板,相关操作可参考[快速入门小型系统部分](../quick-start/quickstart-overview.md)。 进入系统如下所示: diff --git a/zh-cn/device-dev/quick-start/figures/Phoenix-upload.png b/zh-cn/device-dev/quick-start/figures/Phoenix-upload.png index 5702f209752edc74d687e5e8ce7e210428f4551e..d5762ecd3ed51a29bf1645808626b64bc4d747a1 100644 Binary files a/zh-cn/device-dev/quick-start/figures/Phoenix-upload.png and b/zh-cn/device-dev/quick-start/figures/Phoenix-upload.png differ diff --git a/zh-cn/device-dev/quick-start/figures/install-fail.png b/zh-cn/device-dev/quick-start/figures/install-fail.png new file mode 100644 index 0000000000000000000000000000000000000000..75f5419935587ad23d01f637830594ce0535bb3a Binary files /dev/null and b/zh-cn/device-dev/quick-start/figures/install-fail.png differ diff --git a/zh-cn/device-dev/quick-start/figures/select-vscode-path.png b/zh-cn/device-dev/quick-start/figures/select-vscode-path.png new file mode 100644 index 0000000000000000000000000000000000000000..66500f56ddcdd48695b9abe22bdc56241e9bef85 Binary files /dev/null and b/zh-cn/device-dev/quick-start/figures/select-vscode-path.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001265516901.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001265516901.png index 93be7d7b91882bc5d372fe465a0d3a8b2972371f..e6818fac6fb62329dbced2c523cda71d60590ce0 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001265516901.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001265516901.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276281922.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276281922.png index db92b0181a48b56990633058e3a4efce7ca5be82..b85eaee5ce796ab0741943933fcb657033e2a6f7 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276281922.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276281922.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276354454.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276354454.png index 2419d79327a7a13df83fe637916b9abeb180a2b0..db62f3f7def3c12b5b5d14d6eb44b9043d4de327 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276354454.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001276354454.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001280147358.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001280147358.png index 560240a18a081d50201d6185d25da46cc1c7a0eb..8f61b550a1131f3f5520a7db84c5e11376551ed9 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001280147358.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001280147358.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281221352.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281221352.png index da90fa7c0cd0da44ab6aff877eb8e11550dc7871..7b9807183c09f952bc2ce2874d1cc358f47e568b 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281221352.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281221352.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281378224.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281378224.png index 86501f030f57eea30b724f8b7d32736a8ddc7f21..d3a70a4e845cd0943d71601b73d9a730a86008e0 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281378224.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001281378224.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531806.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531806.png index 6d567bf69106c8bb266c7f7f445a317b5405c6a5..c5790475513c9927892b047a750f5beb45295302 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531806.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531806.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531862.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531862.png index df66ac7a87d293ae8500eae978fbe5bcbc23e214..3a1a8b113d000bbc3684882505b9daa43a86bef9 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531862.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292531862.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292849062.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292849062.png index d430a7534a65f96de3f90fc37e279ba116fdf43c..106109e14e08bebcd4423af2966786f6a59d3f5e 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292849062.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001292849062.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001296270098.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001296270098.png index dea8677bfd7c9ba3f7b82f00c8422d695f85b86b..61486549943cf0badf606b6379c256dacdba1e31 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001296270098.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001296270098.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001307160958.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001307160958.png index d1992b49a9805cd0823c98c2d6f1500a10c5f249..c0d61708ad9cb2db0c1336a73e9ce6fcc2f364fe 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001307160958.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001307160958.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001325269477.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001325269477.png index d1992b49a9805cd0823c98c2d6f1500a10c5f249..4633dadcbc9365d9873505d91b8fcfefd9f1b66b 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001325269477.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001325269477.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001326234609.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001326234609.png index e17047264d181b73e48e96a54c60517b57f42fb5..13afaeecab462d7c6efe1c4ba5e38467bfb2e9e0 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001326234609.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001326234609.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001327429541.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001327429541.png index cc19b0a8e8f97ec07b29eab8b01f387c5c81903c..2c29e7a69d2a87f9c2f888949457ba98374ec9ee 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001327429541.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001327429541.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333256741.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333256741.png index f0d3cfc874effae73aad01dd26961ef4946c8f81..1ccaa6d5225520181903e86a88907a53a89094d2 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333256741.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333256741.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333581089.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333581089.png index d6dbd5d63c55c135dd8121d4ca1b4d11d5438897..d607ced0b457e1899bf2b67fa7bac7d5fcd067f7 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333581089.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001333581089.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338012765.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338012765.png index 61536a53597991971c997481624f1aedbc232c6d..7848b0336d1c8fb4e9b8f38e94b8308453b2b464 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338012765.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338012765.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338622229.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338622229.png index e83dad0b26392f009564d2e4014e374187ac1d7f..bfa493ec2ea2c43f5dea668079d23169696443ee 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338622229.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001338622229.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001349388493.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001349388493.png index f467c1b45f84730fd3fc45158004d9a03dec2551..41fa3ad3a958d3acf43fc68946f8bd7897e1c8af 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001349388493.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001349388493.png differ diff --git a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001360439881.png b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001360439881.png index ab85672164a7efca486295641c5ec15e40eda432..bc10279c9de8e1f380a368593a5f0b7b97fd772c 100644 Binary files a/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001360439881.png and b/zh-cn/device-dev/quick-start/figures/zh-cn_image_0000001360439881.png differ diff --git a/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-ide.md b/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-ide.md index de97f5472490b9078fc78b4868b679e567d4f9ab..2c9334c0823392f9944e3ad07df1a024c5b8e85c 100644 --- a/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-ide.md +++ b/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-ide.md @@ -1,5 +1,10 @@ # Hi3516标准系统入门(IDE方式) +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> +> 从3.2版本起,标准系统不再针对Hi3516DV300进行适配验证,建议您使用RK3568进行标准系统的设备开发。 +> +> 如您仍然需要使用Hi3516DV300进行标准系统相关开发操作,则可能会出现无法适配的现象,此时请联系芯片供应商获取相关适配指导,或自行完成适配。 除小型系统外,Hi3516DV300开发板还支持标准系统。此章节简要介绍如何使用IDE在Hi3516DV300开发板上进行标准系统的开发。 @@ -157,7 +162,7 @@ applications/sample/hello 在productdefine/common/products/Hi3516DV300.json中添加对应的hello部件,直接添加到原有部件后即可。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 本章节操作是以OpenHarmony-v3.1-Release版本为例进行操作的,该版本中,Hi3516的配置文件为productdefine/common/products/Hi3516DV300.json;若源码版本大于OpenHarmony-v3.1-Release时,Hi3516的配置文件为vendor/hisilicon/Hi3516DV300/config.json。 + > 本章节操作是以OpenHarmony-v3.1-Release版本为例进行操作的,该版本中,Hi3516的配置文件为productdefine/common/products/Hi3516DV300.json;从OpenHarmony-v3.2-Beta2版本开始,Hi3516的配置文件为vendor/hisilicon/Hi3516DV300/config.json。 ``` @@ -184,8 +189,11 @@ DevEco Device Tool支持Hi3516DV300开发板的源码一键编译功能,提供 ![zh-cn_image_0000001292531862](figures/zh-cn_image_0000001292531862.png) 3. 安装Hi3516DV300相关工具链,部分工具安装需要使用root权限,请在**TERMINAL**窗口输入用户密码进行安装。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > + > - 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > - 若出现安装apt组件失败,可参考[修改apt源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/faq-toolchain-install-0000001301623822)进行修改,完成后尝试重新安装。 ![zh-cn_image_0000001274748606](figures/zh-cn_image_0000001274748606.png) @@ -193,7 +201,7 @@ DevEco Device Tool支持Hi3516DV300开发板的源码一键编译功能,提供 ![zh-cn_image_0000001296270098](figures/zh-cn_image_0000001296270098.png) -4. 在**hi3516dv300**配置页签中,设置源码的编译类型**build_type**,默认为“debug”类型,请根据需要进行修改。修改完成后,点击**Save**进行保存。 +4. 在**hispark_taurus_standard**配置页签中,设置源码的编译类型**build_type**,默认为“debug”类型,请根据需要进行修改。 ![zh-cn_image_0000001325269477](figures/zh-cn_image_0000001325269477.png) @@ -242,9 +250,11 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 ![Phoenix-upload](figures/Phoenix-upload.png) -5. 在“hi3516dv300”页签,设置烧录选项,包括upload_partitions_profile、upload_port和upload_protocol。 +5. 在“hispark_taurus_standard”页签,设置烧录选项,包括upload_partitions_profile、upload_port和upload_protocol。配置完成后工程将自动保存。 + - upload_partitions_profile:选择待烧录程序的配置文件(已预置默认的配置文件),该配置文件会指定烧录文件名称、起始烧录地址、地址长度等信息;同时请勾选**Enable to use upload_partitions_profile for upload**选项。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > > 如需修改烧录profile文件,在设置烧录分区起始地址和分区长度时,应根据实际待烧录文件的大小进行设置,要求设置的烧录分区大小,要大于待烧录文件的大小;同时,各烧录文件的分区地址设置不能出现重叠。 > > 首次烧录,请勾选**Enable to use upload_partitions_profile for upload**选项,会自动生成upload_partitions文件。再次烧录时,可根据实际情况选择生成upload_partitions文件进行自定义烧录,也可以再勾选**Enable to use upload_partitions_profile for upload**选项,使用upload_partitions_profile重新生成upload_partitions文件用于烧录。 @@ -253,9 +263,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001338622229](figures/zh-cn_image_0000001338622229.png) -6. 所有的配置都修改完成后,在工程配置页签的顶部,点击**Save**进行保存。 - -7. 点击hi3516dv300下的**Upload**按钮。 +6. 单击hispark_taurus_standard下的**Upload**按钮。 ![zh-cn_image_0000001276281922](figures/zh-cn_image_0000001276281922.png) @@ -263,7 +271,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001326201857](figures/zh-cn_image_0000001326201857.png) -8. 在终端窗口显示如下提示信息时,请在15秒内,按住Update键,插拔USB线,最后松开Update键启动烧录。 +7. 在终端窗口显示如下提示信息时,请在15秒内,按住Update键,插拔USB线,最后松开Update键启动烧录。 ![zh-cn_image_0000001276122010](figures/zh-cn_image_0000001276122010.png) @@ -271,7 +279,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001275802150](figures/zh-cn_image_0000001275802150.png) -9. 烧录成功后,请根据运行章节进行操作,启动系统。 +8. 烧录成功后,请根据运行章节进行操作,启动系统。 ## 运行 @@ -294,12 +302,12 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 3. 通过以下两条命令设置启动参数。 - ``` + ```shell setenv bootargs 'mem=640M console=ttyAMA0,115200 mmz=anonymous,0,0xA8000000,384M clk_ignore_unused rootdelay=10 hardware=Hi3516DV300 init=/init root=/dev/ram0 rw blkdevparts=mmcblk0:1M(boot),15M(kernel),20M(updater),2M(misc),3307M(system),256M(vendor),-(userdata)'; ``` - ``` + ```shell setenv bootcmd 'mmc read 0x0 0x82000000 0x800 0x4800; bootm 0x82000000' ``` @@ -307,7 +315,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 4. 保存参数设置。 - ``` + ```shell save ``` @@ -315,7 +323,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 5. 重启开发板,完成系统启动。 - ``` + ```shell reset ``` diff --git a/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-pkg.md b/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-pkg.md index 838d824279bd88f0c3e33a1284dba93a3a18c74e..421632d684ea5db1f682f54e49ca711877ddb7fc 100644 --- a/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-pkg.md +++ b/zh-cn/device-dev/quick-start/quickstart-appendix-hi3516-pkg.md @@ -1,5 +1,12 @@ # Hi3516标准系统入门(命令行方式) +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> +> 从3.2版本起,标准系统不再针对Hi3516DV300进行适配验证,建议您使用RK3568进行标准系统的设备开发。 +> +> 如您仍然需要使用Hi3516DV300进行标准系统相关开发操作,则可能会出现无法适配的现象,此时请联系芯片供应商获取相关适配指导,或自行完成适配。 + + 除小型系统外,Hi3516DV300开发板还支持标准系统。此章节简要介绍如何使用命令行在Hi3516DV300开发板上进行标准系统的开发。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3516-build.md b/zh-cn/device-dev/quick-start/quickstart-ide-3516-build.md index 58f0db0f1884e541ae936562633e125cbf460172..472be7bd3efa0ea241356892aa91c64044dd7c0f 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3516-build.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3516-build.md @@ -17,8 +17,11 @@ DevEco Device Tool支持Hi3516DV300开发板的源码一键编译功能,提供 ![zh-cn_image_0000001307480750](figures/zh-cn_image_0000001307480750.png) 3. 安装Hi3516DV300相关工具链,部分工具安装需要使用root权限,请在“TERMINAL”窗口输入用户密码进行安装。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > + > - 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > - 若出现安装apt组件失败,可参考[修改apt源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/faq-toolchain-install-0000001301623822)进行修改,完成后尝试重新安装。 ![zh-cn_image_0000001360080305](figures/zh-cn_image_0000001360080305.png) @@ -26,7 +29,7 @@ DevEco Device Tool支持Hi3516DV300开发板的源码一键编译功能,提供 ![zh-cn_image_0000001307320918](figures/zh-cn_image_0000001307320918.png) -4. 在“hi3516dv300”配置页签中,设置源码的编译类型**build_type**,默认为“debug”类型,请根据需要进行修改。修改完成后,单击**Save**进行保存。 +4. 在**ipcamera_hispark_taurus**配置页签中,设置源码的编译类型**build_type**,默认为“debug”类型,请根据需要进行修改。 ![zh-cn_image_0000001307160958](figures/zh-cn_image_0000001307160958.png) diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3516-burn.md b/zh-cn/device-dev/quick-start/quickstart-ide-3516-burn.md index 75eb1d896ca2158da0a636055841bdd8f7d5dbb4..3ded9acf977fbabb7e9f4984b959c3fc83f72afb 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3516-burn.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3516-burn.md @@ -37,7 +37,7 @@ Hi3516DV300开发板小型系统的烧录方式包括USB烧录、网口烧录两 ![Phoenix-upload](figures/Phoenix-upload.png) -5. 在“hi3516dv300”页签,设置烧录选项,包括upload_partitions、upload_port和upload_protocol。 +5. 在“hi3516dv300”页签,设置烧录选项,包括upload_partitions、upload_port和upload_protocol。配置完成后工程将自动保存。 - upload_partitions:选择待烧录的文件,默认情况下会同时烧录fastboot、kernel、rootfs和userfs。DevEco Device Tool已预置默认的烧录文件信息,包括起始地址、分区大小、待烧录文件地址等,开发者可根据实际情况进行调整,点击每个待烧录文件后的![zh-cn_image_0000001275592884](figures/zh-cn_image_0000001275592884.png)按钮进行修改。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 在设置烧录分区起始地址和分区长度时,应根据实际待烧录文件的大小进行设置,要求设置的烧录分区大小,要大于待烧录文件的大小;同时,各烧录文件的分区地址设置不能出现重叠。 @@ -49,9 +49,7 @@ Hi3516DV300开发板小型系统的烧录方式包括USB烧录、网口烧录两 ![3516-small-usb](figures/3516-small-usb.png) -6. 所有的配置都修改完成后,在工程配置页签的顶部,点击**Save**进行保存。 - -7. 点击hi3516dv300下的**Upload**按钮。 +6. 点击hi3516dv300下的**Upload**按钮。 ![zh-cn_image_0000001326234609](figures/zh-cn_image_0000001326234609.png) @@ -59,7 +57,7 @@ Hi3516DV300开发板小型系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001275835836](figures/zh-cn_image_0000001275835836.png) -8. 在终端窗口显示如下提示信息时,请在15秒内,按住Update键,插拔USB线,最后松开Update键启动烧录。 +7. 在终端窗口显示如下提示信息时,请在15秒内,按住Update键,插拔USB线,最后松开Update键启动烧录。 ![zh-cn_image_0000001326412233](figures/zh-cn_image_0000001326412233.png) @@ -67,4 +65,4 @@ Hi3516DV300开发板小型系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001276317464](figures/zh-cn_image_0000001276317464.png) -9. 烧录成功后,请根据运行章节进行操作,启动系统。 +8. 烧录成功后,请根据运行章节进行操作,启动系统。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3516-running.md b/zh-cn/device-dev/quick-start/quickstart-ide-3516-running.md index de3a6b16bbd43a75f31f6688cf742ac5e28f8185..7641917305337e206d4dd3046348686ed63afac0 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3516-running.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3516-running.md @@ -30,13 +30,13 @@ 1. 在启动界面进入bin目录。 - ``` + ```shell cd bin ``` 2. 进入bin目录后可以看到helloworld文件,通过以下命令运行helloworld程序。 - ``` + ```shell ./helloworld ``` diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3568-build.md b/zh-cn/device-dev/quick-start/quickstart-ide-3568-build.md index 923fe7bbaf0ee4ebcd696de0e14a21cc020fe7d1..a7065bb9355f2ea1463f49dc41f7b7626c9b48b7 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3568-build.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3568-build.md @@ -13,8 +13,11 @@ DevEco Device Tool支持Rockchip RK3568开发板的源码一键编译功能, ![zh-cn_image_0000001327669509](figures/zh-cn_image_0000001327669509.png) 2. 在**Tool Chain**页签中,DevEco Device Tool会自动检测依赖的编译工具链是否完备,如果提示部分工具缺失,可点击**Install**,自动安装所需工具链。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > + > - 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > - 若出现安装apt组件失败,可参考[修改apt源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/faq-toolchain-install-0000001301623822)进行修改,完成后尝试重新安装。 ![zh-cn_image_0000001292531806](figures/zh-cn_image_0000001292531806.png) @@ -26,7 +29,7 @@ DevEco Device Tool支持Rockchip RK3568开发板的源码一键编译功能, ![zh-cn_image_0000001349388493](figures/zh-cn_image_0000001349388493.png) -3. 在**hh_scdy200**配置页签中,设置源码的编译类型**build_type**,默认为"debug"类型,请根据需要进行修改。然后点击**Save**进行保存。 +3. 在**rk3568**配置页签中,设置源码的编译类型**build_type**,默认为"debug"类型,请根据需要进行修改。 ![zh-cn_image_0000001276354454](figures/zh-cn_image_0000001276354454.png) diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3568-burn.md b/zh-cn/device-dev/quick-start/quickstart-ide-3568-burn.md index a8a3a5267de371fbe6189fdd0a7f215554edbaaf..dd249431214ac91d52aa9622418bd771f4fb1323 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3568-burn.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3568-burn.md @@ -20,6 +20,7 @@ RK3568的镜像烧录通过Windows环境进行烧录,开发者启动烧录操 1. 请连接好电脑和待烧录开发板,连接USB接口,具体可参考[RK3568开发板介绍](quickstart-appendix-rk3568.md)。 2. 在DevEco Device Tool中,选择**REMOTE DEVELOPMENT > Local PC**,查看远程计算机(Ubuntu开发环境)与本地计算机(Windows开发环境)的连接状态。 + - 如果Local PC右边连接按钮为![zh-cn_image_0000001326512673](figures/zh-cn_image_0000001326512673.png),则远程计算机与本地计算机为已连接状态,不需要执行其他操作。 - 如果Local PC右边连接按钮为![zh-cn_image_0000001275432904](figures/zh-cn_image_0000001275432904.png),则点击绿色按钮进行连接。连接时DevEco Device Tool会重启服务,因此请不要在下载源码或源码编译过程中进行连接,否则会中断任务。 @@ -33,9 +34,11 @@ RK3568的镜像烧录通过Windows环境进行烧录,开发者启动烧录操 ![3865-uploader](figures/3865-uploader.png) -5. 在**hh_scdy200**页签,设置烧录选项,包括upload_partitions和upload_protocol。 +5. 在**rk3568**页签,设置烧录选项,包括upload_partitions和upload_protocol。配置完成后工程将自动保存。 + - **upload_partitions_profile**:选择待烧录程序的配置文件,该配置文件会指定烧录文件名称、起始烧录地址、地址长度等信息;同时请勾选**Enable to use upload_partitions_profile for upload**选项。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > > 如需修改烧录profile文件,在设置烧录分区起始地址和分区长度时,应根据实际待烧录文件的大小进行设置,要求设置的烧录分区大小,要大于待烧录文件的大小;同时,各烧录文件的分区地址设置不能出现重叠。 > > 首次烧录,请勾选**Enable to use upload_partitions_profile for upload**选项,会自动生成upload_partitions文件。再次烧录时,可根据实际情况选择生成upload_partitions文件进行自定义烧录,也可以再勾选**Enable to use upload_partitions_profile for upload**选项,使用upload_partitions_profile重新生成upload_partitions文件用于烧录。 @@ -43,13 +46,11 @@ RK3568的镜像烧录通过Windows环境进行烧录,开发者启动烧录操 ![zh-cn_image_0000001338663697](figures/zh-cn_image_0000001338663697.png) -6. 所有的配置都修改完成后,在工程配置页签的顶部,点击**Save**进行保存。 - -7. 在**PROJECT TASKS**中,点击hh_scdy200下的**Upload**按钮启动烧录。 +6. 在**PROJECT TASKS**中,点击rk3568下的**Upload**按钮启动烧录。 ![zh-cn_image_0000001280147358](figures/zh-cn_image_0000001280147358.png) -8. 当屏幕提示“Operation paused,Please press Enter key to continue”,请按**回车键**继续。 +7. 当屏幕提示“Operation paused,Please press Enter key to continue”,请按**回车键**继续。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 如果开发板未处于烧录模式,屏幕会提示“The board is not in Loader mode.Please Hold on the VOL+key...”,此时,请长按音量+键,3秒后点击**RESET**键,然后再过3秒放开音量+键,使开发板进入烧录模式。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3568-helloworld.md b/zh-cn/device-dev/quick-start/quickstart-ide-3568-helloworld.md index cbd93e684bfcff79a1e518114b4d21af9e6cdd18..518228c24abd54f22ecb318ed117c903b33b6bee 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3568-helloworld.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3568-helloworld.md @@ -156,7 +156,7 @@ productdefine/common 在productdefine/common/products/rk3568.json中添加对应的hello部件,直接添加到原有部件后即可。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 本章节操作是以OpenHarmony-v3.1-Release版本为例进行操作的,该版本中,RK3568的配置文件为productdefine/common/products/rk3568.json;若源码版本大于OpenHarmony-v3.1-Release时,RK3568的配置文件为vendor/hihope/rk3568/config.json。 + > 本章节操作是以OpenHarmony-v3.1-Release版本为例进行操作的,该版本中,RK3568的配置文件为productdefine/common/products/rk3568.json;从OpenHarmony-v3.2-Beta2版本开始,RK3568的配置文件为vendor/hihope/rk3568/config.json。 ``` diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3861-build.md b/zh-cn/device-dev/quick-start/quickstart-ide-3861-build.md index fe688893ece0b4c486cb58c4fe08ea9cb5234d89..2e03e588f52cecfc1855950c0d1f9affdfd73ee0 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3861-build.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3861-build.md @@ -18,7 +18,9 @@ DevEco Device Tool支持Hi3861V100开发板的源码一键编译功能,提供 3. 安装Hi3861V100相关工具链,部分工具安装需要使用root权限,请在**TERMINAL**窗口输入用户密码进行安装。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > + > - 如果出现安装pip组件失败,可参考[修改Python源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/ide-set-python-source-0000001227639986)进行修改,完成尝试重新安装。 + > - 若出现安装apt组件失败,可参考[修改apt源的方法](https://device.harmonyos.com/cn/docs/documentation/guide/faq-toolchain-install-0000001301623822)进行修改,完成后尝试重新安装。 ![zh-cn_image_0000001280938208](figures/zh-cn_image_0000001280938208.png) @@ -26,7 +28,7 @@ DevEco Device Tool支持Hi3861V100开发板的源码一键编译功能,提供 ![zh-cn_image_0000001281378224](figures/zh-cn_image_0000001281378224.png) -4. 在**hi3861**配置页签中,设置源码的编译类型**build_type**,默认为"debug"类型,请根据需要进行修改。然后点击**Save**进行保存。 +4. 在**wifiiot_hispark_pegasus**配置页签中,设置源码的编译类型**build_type**,默认为"debug"类型,请根据需要进行修改。 ![zh-cn_image_0000001333581089](figures/zh-cn_image_0000001333581089.png) diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-3861-burn.md b/zh-cn/device-dev/quick-start/quickstart-ide-3861-burn.md index 607463264e079110e64934138b7a805dabcc5d67..672de391335f484d975367393c2b393458651269 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-3861-burn.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-3861-burn.md @@ -30,22 +30,23 @@ Hi3861V100的镜像烧录通过Windows环境进行烧录,开发者启动烧录 4. 在“Tool Chain”页签,设置Uploader烧录器工具,可以通过Tool Chain页签中的Install按钮在线安装。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > 若烧录器存在新版本或需要使用其它烧录器,您可以在**Uploader > Use Custom Burn Tool**指定本地的烧录器。 + ![Phoenix-upload](figures/Phoenix-upload.png) -5. 在“hi3861”页签,设置烧录选项,包括upload_port、upload_protocol和upload_partitions。 +5. 在“hi3861”页签,设置烧录选项,包括upload_port、upload_protocol和upload_partitions。配置完成后工程将自动保存。 - upload_port:选择已查询的串口号。 - upload_protocol:选择烧录协议,选择“hiburn-serial”。 - upload_partitions:选择待烧录的文件名称。DevEco Device Tool已预置默认的烧录文件信息,如果需要修改待烧录文件地址,可点击每个待烧录文件后的![zh-cn_image_0000001333642545](figures/zh-cn_image_0000001333642545.png)按钮进行修改。 ![zh-cn_image_0000001345770181](figures/zh-cn_image_0000001345770181.png) -6. 所有的配置都修改完成后,在工程配置页签的顶部,点击**Save**进行保存。 - -7. 在“PROJECT TASKS”中,点击hi3861下的**Upload**按钮,启动烧录。 +6. 在“PROJECT TASKS”中,点击hi3861下的**Upload**按钮,启动烧录。 ![zh-cn_image_0000001333322693](figures/zh-cn_image_0000001333322693.png) -8. 启动烧录后,显示如下提示信息时,请在15秒内,按下开发板上的RST按钮重启开发板。 +7. 启动烧录后,显示如下提示信息时,请在15秒内,按下开发板上的RST按钮重启开发板。 ![hi3861-upload-restart](figures/hi3861-upload-restart.png) diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env--win.md b/zh-cn/device-dev/quick-start/quickstart-ide-env--win.md index 055d303163bd564fdc49e6f66765bda88de1eef8..e408e6d3b38ed718132517c284ad5a07cedf9c24 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env--win.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-env--win.md @@ -10,27 +10,31 @@ - Windows 10 64位系统。 -- Windows系统上安装的DevEco Device Tool为3.0 Release版本。 +- Windows系统上安装的DevEco Device Tool为3.1 Beta1版本。 ## 操作步骤 -1. 下载[DevEco Device Tool 3.0 Release](https://device.harmonyos.com/cn/ide#download) Windows版。 +1. 下载[DevEco Device Tool 3.1 Beta1](https://device.harmonyos.com/cn/ide#download) Windows版。 2. 解压DevEco Device Tool压缩包,双击安装包程序,单击**Next**进行安装。 3. 设置DevEco Device Tool的安装路径,请注意安装路径不能包含中文字符,**不建议安装到C盘目录**,单击**Next**。 - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 如果您已安装DevEco Device Tool 3.0 Beta2及以前的版本,则在安装新版本时,会先卸载旧版本,卸载过程中出现错误提示“Error during uninstallation process: Cannot remove directory...”时,请单击**Ignore**继续安装,该错误不影响新版本的安装。 ![zh-cn_image_0000001326386753](figures/zh-cn_image_0000001326386753.png) 4. 根据安装向导提示,勾选要自动安装的软件。 - 1. 在弹出**VS Code installation confirm**页面,勾选“Install VS Code 1.62.2automatically”,单击**Next**。 + + 1. 在弹出**VSCode installation confirm**页面,勾选“Install VS Code 1.62.2 automatically”,单击**Next**。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 如果检测到Visual Studio Code已安装,且版本为1.62及以上,则会跳过该步骤。 ![zh-cn_image_0000001285965546](figures/zh-cn_image_0000001285965546.png) + + 2. 选择Visual Studio Code的安装路径,单击**Next**。 + + ![select-vscode-path](figures/select-vscode-path.png) + 2. 在弹出的**Python select page**选择“Download from Huawei mirror”,单击**Next**。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 如果系统已安装可兼容的Python版本(Python 3.8~3.9版本),可选择“Use one of compatible on your PC”。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env-remote.md b/zh-cn/device-dev/quick-start/quickstart-ide-env-remote.md index a6c260e917f5b49cb1f04cd4b7f9ae3bd78d9e50..1c82b6759dc6040c34802bdc23c8fe49ed54b5eb 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env-remote.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-env-remote.md @@ -11,19 +11,19 @@ > 如果执行该命令失败,提示openssh-server和openssh-client依赖版本不同,请根据CLI界面提示信息,安装openssh-client相应版本后(例如:sudo apt-get install openssh-client=1:8.2p1-4),再重新执行该命令安装openssh-server。 - ``` + ```shell sudo apt-get install openssh-server ``` 2. 执行如下命令,启动SSH服务。 - ``` + ```shell sudo systemctl start ssh ``` 3. 执行如下命令,获取当前用户的IP地址,用于Windows系统远程访问Ubuntu环境。 - ``` + ```shell ifconfig ``` @@ -62,12 +62,19 @@ ![zh-cn_image_0000001215720398](figures/zh-cn_image_0000001215720398.png) -5. 在弹出的输入框中,选择**Linux**,然后在选择**Continue**,然后输入登录远程计算机的密码,连接远程计算机 。 +5. 在弹出的输入框中,选择**Linux**,然后在选择**Continue**,然后输入登录远程计算机的密码,连接远程计算机。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 在Windows系统远程访问Ubuntu过程中,需要频繁的输入密码进行连接,为解决该问题,您可以使用SSH公钥来进行设置,设置方法请参考[注册远程访问Ubuntu环境的公钥](https://device.harmonyos.com/cn/docs/documentation/guide/ide-registering-public-key-0000001247162706)。 ![zh-cn_image_0000001215897530](figures/zh-cn_image_0000001215897530.png) - 连接成功后,等待在远程计算机用户目录下的.vscode-server文件夹下自动安装插件,安装完成后,根据界面提示在Windows系统下重新加载Visual Studio Code,便可以在Windows的DevEco Device Tool界面进行源码开发、编译、烧录等操作。至此,环境搭建完成,如下图所示,左下角显示远程连接计算机的IP地址。 + 连接成功后,等待在远程计算机用户目录下的.vscode-server文件夹下自动安装插件,安装完成后,根据界面提示在Windows系统下重新加载Visual Studio Code,便可以在Windows的DevEco Device Tool界面进行源码开发、编译、烧录等操作。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > 如果您之前安装过DevEco Device Tool 3.0 Release及以前的版本,可能出现插件安装失败的情况,Visual Studio Code右下角一直处于如下界面,请参考[DevEco Device Tool插件安装失败处理办法](https://device.harmonyos.com/cn/docs/documentation/guide/faq-device-tool-install-failed-0000001437806813)进行处理。 + + ![install-fail](figures/install-fail.png) + + 至此,环境搭建完成,如下图所示,左下角显示远程连接计算机的IP地址。 ![zh-cn_image_0000001338102621](figures/zh-cn_image_0000001338102621.png) diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md index bfda5a1b0d8e37bf4252ba381c4fa3f2943be04e..f79c4b7b14c8e95de76d147333c295ea236cdec0 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-env-ubuntu.md @@ -12,7 +12,7 @@ ## 系统要求 -- Ubuntu系统要求:Ubuntu18.04~21.10版本,内存推荐16 GB及以上。 +- Ubuntu系统要求:Ubuntu18.04~21.10版本。推荐使用20.04版本,内存16 GB及以上。 - Ubuntu系统的用户名不能包含中文字符。 @@ -22,37 +22,37 @@ 1. 将Ubuntu Shell环境修改为bash。 1. 执行如下命令,确认输出结果为bash。如果输出结果不是bash,请根据子步骤2,将Ubuntu shell修改为bash。 - ``` + ```shell ls -l /bin/sh ``` ![zh-cn_image_0000001226764302](figures/zh-cn_image_0000001226764302.png) 2. 打开终端工具,执行如下命令,输入密码,然后选择**No**,将Ubuntu shell由dash修改为bash。 - ``` + ```shell sudo dpkg-reconfigure dash ``` ![ubuntu-dash-to-bash](figures/ubuntu-dash-to-bash.png) -2. 下载[DevEco Device Tool 3.0 Release](https://device.harmonyos.com/cn/ide#download) Linux版本。 +2. 下载[DevEco Device Tool 3.1 Beta1](https://device.harmonyos.com/cn/ide#download) Linux版本。 3. 解压DevEco Device Tool软件包并对解压后的文件夹进行赋权。 - 1. 进入DevEco Device Tool软件包目录,执行如下命令解压软件包,其中devicetool-linux-tool-3.1.0.200.zip为软件包名称,请根据实际进行修改。 + 1. 进入DevEco Device Tool软件包目录,执行如下命令解压软件包,其中devicetool-linux-tool-3.1.0.300.zip为软件包名称,请根据实际进行修改。 + ```shell + unzip devicetool-linux-tool-3.1.0.300.zip ``` - unzip devicetool-linux-tool-3.1.0.200.zip - ``` - 2. 进入解压后的文件夹,执行如下命令,赋予安装文件可执行权限,其中devicetool-linux-tool-3.1.0.200.sh请根据实际进行修改。 + 2. 进入解压后的文件夹,执行如下命令,赋予安装文件可执行权限,其中devicetool-linux-tool-3.1.0.300.sh请根据实际进行修改。 - ``` - chmod u+x devicetool-linux-tool-3.1.0.200.sh + ```shell + chmod u+x devicetool-linux-tool-3.1.0.300.sh ``` -4. 执行如下命令,安装DevEco Device Tool,其中devicetool-linux-tool-3.1.0.200.sh请根据实际进行修改。 +4. 执行如下命令,安装DevEco Device Tool,其中devicetool-linux-tool-3.1.0.300.sh请根据实际进行修改。 - ``` - sudo ./devicetool-linux-tool-3.1.0.200.sh + ```shell + sudo ./devicetool-linux-tool-3.1.0.300.sh ``` 5. 在用户协议和隐私声明签署界面,请详细阅读用户协议和隐私声明,需签署同意用户协议和隐私声明才能进行下一步的安装,可通过键盘的上下按键进行选择。 @@ -62,3 +62,18 @@ 安装完成后,当界面输出“DevEco Device Tool successfully installed.”时,表示DevEco Device Tool安装成功。 ![zh-cn_image_0000001338201457](figures/zh-cn_image_0000001338201457.png) + + +6. 使用如下apt-get命令安装后续操作所需的库和工具。 + + ```shell + sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** + > + > 以上安装命令适用于Ubuntu18.04,其他版本请根据安装包名称采用对应的安装命令。其中: + > + > - Python要求安装Python 3.8及以上版本,此处以Python 3.8为例。 + > + > - Java要求java8及以上版本,此处以java8为例。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-env.md b/zh-cn/device-dev/quick-start/quickstart-ide-env.md deleted file mode 100644 index 3cb3ffb46bf738617f74bbc0a651a3d641db4d2a..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-ide-env.md +++ /dev/null @@ -1,7 +0,0 @@ -# 搭建开发环境 - - -在嵌入式开发中,很多开发者习惯于使用Windows进行代码的编辑,比如使用Windows的Visual Studio Code进行OpenHarmony代码的开发。但当前阶段,大部分的开发板源码还不支持在Windows环境下进行编译,如Hi3861、Hi3516系列开发板。因此,建议使用Ubuntu的编译环境对源码进行编译。 - - -在以上的设备开发场景中,可以搭建一套Windows+Ubuntu混合开发的环境,其中使用Windows平台的DevEco Device Tool可视化界面进行相关操作,通过远程连接的方式对接Ubuntu下的DevEco Device Tool(可以不安装Visual Studio Code),然后对Ubuntu下的源码进行开发、编译、烧录等操作。 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md index 4692ddf4862e7397586a9abd19f00caed050a1f0..443f44e9196a79f9b3af07017702336ba51a93ae 100644 --- a/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md +++ b/zh-cn/device-dev/quick-start/quickstart-ide-import-project.md @@ -15,7 +15,10 @@ OpenHarmony Stable Version源码为OpenHarmony稳定版本源码,通过镜像 ## 前提条件 -只有在Windows环境通过Remote SSH远程连接上Ubuntu环境的情况下,才可以创建OpenHarmony新工程,具体请参考[搭建开发环境](quickstart-ide-env--win.md)。否则,在DevEco Device Tool的Home界面没有“**New Project**”按钮。 +只有在Windows环境通过Remote SSH远程连接上Ubuntu环境的情况下,才可以创建OpenHarmony新工程,具体请参考[搭建开发环境](quickstart-ide-env--win.md)。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 若Windows环境未远程连接Ubuntu环境,New Project功能仅针对海思企业用户,不支持创建OpenHarmony工程。 ## 操作步骤 diff --git a/zh-cn/device-dev/quick-start/quickstart-ide-lite-appendix.md b/zh-cn/device-dev/quick-start/quickstart-ide-lite-appendix.md deleted file mode 100644 index 37735011da2235266fe5a6397df0cca595609111..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-ide-lite-appendix.md +++ /dev/null @@ -1,11 +0,0 @@ -# 附录 - - - -- **[Hi3516开发板介绍](quickstart-appendix-hi3516.md)** - -- **[Hi3861开发板介绍](quickstart-appendix-hi3861.md)** - -- **[RK3568开发板介绍](quickstart-appendix-rk3568.md)** - -- **[编译形态整体说明](quickstart-appendix-compiledform.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/quick-start/quickstart-ide.md b/zh-cn/device-dev/quick-start/quickstart-ide.md deleted file mode 100644 index 71922baa6fda1c56abffed4f57542990f2ac6701..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-ide.md +++ /dev/null @@ -1,25 +0,0 @@ -# 使用IDE快速入门 - - -- 基于IDE入门 - - 搭建开发环境 - - [搭建Windows环境](quickstart-ide-env--win.md) - - [搭建Ubuntu环境](quickstart-ide-env-ubuntu.md) - - [配置远程访问环境](quickstart-ide-env-remote.md) - - [创建工程并获取源码](quickstart-ide-import-project.md) - - 轻量系统(基于Hi3861开发板) - - [编写“Hello World”程序](quickstart-ide-3861-helloworld.md) - - [编译](quickstart-ide-3861-build.md) - - [烧录](quickstart-ide-3861-burn.md) - - [运行](quickstart-ide-3861-running.md) - - 小型系统(基于Hi3516开发板) - - [编写“Hello World”程序](quickstart-ide-3516-helloworld.md) - - [编译](quickstart-ide-3516-build.md) - - [烧录](quickstart-ide-3516-burn.md) - - [运行](quickstart-ide-3516-running.md) - - 标准系统(基于RK3568开发板) - - [编写“Hello World”程序](quickstart-ide-3568-helloworld.md) - - [编译](quickstart-ide-3568-build.md) - - [烧录](quickstart-ide-3568-burn.md) - - [运行](quickstart-ide-3568-running.md) - diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg-env.md b/zh-cn/device-dev/quick-start/quickstart-pkg-env.md deleted file mode 100644 index 313c291e3e917767472787f90f4b74cb68de948f..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-pkg-env.md +++ /dev/null @@ -1,4 +0,0 @@ -# 搭建开发环境 - - -在嵌入式开发中,很多开发者习惯于使用Windows进行代码的编辑,比如使用Windows的Visual Studio Code进行OpenHarmony代码的开发。但当前阶段,大部分的开发板源码还不支持在Windows环境下进行编译,如Hi3861、Hi3516系列开发板。因此,建议使用Ubuntu的编译环境对源码进行编译。同时,开发板的烧录需要在Windows环境中进行。 diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg-info.md b/zh-cn/device-dev/quick-start/quickstart-pkg-info.md deleted file mode 100644 index aa2bd522a5e6f8487e5bf0b38a881d6069f2286f..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-pkg-info.md +++ /dev/null @@ -1,13 +0,0 @@ -# 常用信息 - - - -- **[配置代理](quickstart-pkg-common-proxy.md)** - -- **[使用build.sh脚本编译源码](quickstart-pkg-common-build.md)** - -- **[hb安装异常处理](quickstart-pkg-common-hberr.md)** - -- **[编译异常处理](quickstart-pkg-common-builderr.md)** - -- **[烧录异常处理](quickstart-pkg-common-burnerr.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/quick-start/quickstart-pkg.md b/zh-cn/device-dev/quick-start/quickstart-pkg.md deleted file mode 100644 index b13f806e0f01e594a5393aeb13a7dd60c59a36a8..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/quick-start/quickstart-pkg.md +++ /dev/null @@ -1,31 +0,0 @@ -# 使用命令行快速入门 - - -- 基于命令行入门 - - 搭建开发环境 - - [准备开发环境](quickstart-pkg-prepare.md) - - [安装库和工具集](quickstart-pkg-install_package.md) - - [获取源码](quickstart-pkg-sourcecode.md) - - [安装编译工具](quickstart-pkg-install_tool.md) - - 轻量系统(基于Hi3861开发板) - - [安装Hi3861开发板特有环境](quickstart-pkg-3861-tool.md) - - [编写“Hello World”程序](quickstart-pkg-3861-helloworld.md) - - [编译](quickstart-pkg-3861-build.md) - - [烧录](quickstart-pkg-3861-burn.md) - - [运行](quickstart-pkg-3861-running.md) - - 小型系统(基于Hi3516开发板) - - [编写“Hello World”程序](quickstart-pkg-3516-helloworld.md) - - [编译](quickstart-pkg-3516-build.md) - - [烧录](quickstart-pkg-3516-burn.md) - - [运行](quickstart-pkg-3516-running.md) - - 标准系统(基于RK3568开发板) - - [编写“Hello World”程序](quickstart-pkg-3568-helloworld.md) - - [编译](quickstart-pkg-3568-build.md) - - [烧录](quickstart-pkg-3568-burn.md) - - [运行](quickstart-pkg-3568-running.md) - - 常用信息 - - [配置代理](quickstart-pkg-common-proxy.md) - - [使用build.sh脚本编译源码](quickstart-pkg-common-build.md) - - [hb安装异常处理](quickstart-pkg-common-hberr.md) - - [编译异常处理](quickstart-pkg-common-builderr.md) - - [烧录异常处理](quickstart-pkg-common-burnerr.md) \ No newline at end of file diff --git a/zh-cn/device-dev/reference/hdi-apis/annotated.md b/zh-cn/device-dev/reference/hdi-apis/annotated.md deleted file mode 100644 index e415acf8378b78b8e569253222748e5404e3f36b..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/reference/hdi-apis/annotated.md +++ /dev/null @@ -1,365 +0,0 @@ -# 结构体 - - - -- **[YUVDescInfo](_yun_desc_info_.md)** - -- **[ExtDataHandle](_ext_data_handle.md)** - -- **[ActRecognitionEvent](_act_recognition_event.md)** - -- **[AllocInfo](_alloc_info.md)** - -- **[Alignment](_alignment.md)** - -- **[AudioAdapter](_audio_adapter.md)** - -- **[AudioAdapterDescriptor](_audio_adapter_descriptor.md)** - -- **[AudioAttribute](_audio_attribute.md)** - -- **[AudioCapture](_audio_capture.md)** - -- **[AudioControl](_audio_control.md)** - -- **[AudioDevExtInfo](_audio_dev_ext_info.md)** - -- **[AudioDeviceDescriptor](_audio_device_descriptor.md)** - -- **[AudioManager](_audio_manager.md)** - -- **[AudioMixExtInfo](_audio_mix_ext_info.md)** - -- **[AudioMmapBufferDescriptor](_audio_mmap_buffer_descriptor.md)** - -- **[AudioPort](_audio_port.md)** - -- **[AudioPortCap](audio_portcap.md)** - -- **[AudioPortCapability](_audio_port_capability.md)** - -- **[AudioRender](_audio_render.md)** - -- **[AudioRoute](_audio_route.md)** - -- **[AudioRouteNode](_audio_route_node.md)** - -- **[AudioSampleAttributes](_audio_sample_attributes.md)** - -- **[AudioScene](_audio_scene.md)** - -- **[AudioSceneDescriptor](_audio_scene_descriptor.md)** - -- **[AudioSceneDescriptor::SceneDesc](union_audio_scene_descriptor_1_1_scene_desc.md)** - -- **[AudioSessionExtInfo](_audio_session_ext_info.md)** - -- **[AudioSubPortCapability](_audio_sub_port_capability.md)** - -- **[AudioTimeStamp](_audio_time_stamp.md)** - -- **[AudioVolume](_audio_volume.md)** - -- **[AuthResultInfo](_auth_result_info.md)** - -- **[AuthSolution](_auth_solution.md)** - -- **[BufferData](_buffer_data.md)** - -- **[BatteryInfo](_battery_info.md)** - -- **[CaptureEndedInfo](_capture_ended_info.md)** - -- **[CaptureErrorInfo](_capture_error_info.md)** - -- **[CaptureInfo](_capture_info.md)** - -- **[CodecCallbackType](_codec_callback_type.md)** - -- **[CodecCompCapability](_codec_comp_capability.md)** - -- **[CodecComponentManager](_codec_component_manager.md)** - -- **[CodecComponentType](_codec_component_type.md)** - -- **[ColorValue](union_color_value.md)** - -- **[CompVerInfo](_comp_ver_info.md)** - -- **[CredentialInfo](_credential_info.md)** - -- **[DeviceFuncs](_device_funcs.md)** - -- **[DisplayCapability](_display_capability.md)** - -- **[DisplayInfo](_display_info.md)** - -- **[DisplayModeInfo](_display_mode_info.md)** - -- **[EnrolledInfo](_enrolled_info.md)** - -- **[EnrollParam](_enroll_param.md)** - -- **[EnrollResultInfo](_enroll_resultinfo.md)** - -- **[EventInfo](_event_info.md)** - -- **[ExecutorInfo](_executor_info.md)** - -- **[ExecutorInfo](_user_executor_info.md)** - -- **[ExecutorRegisterInfo](_executor_register_info.md)** - -- **[ExecutorSendMsg](_executor_send_msg.md)** - -- **[GetBufferHandleUsageParams](_get_buffer_handle_usage_params.md)** - -- **[GfxFuncs](_gfx_funcs.md)** - -- **[GfxOpt](_gfx_opt.md)** - -- **[GrallocFuncs](_gralloc_funcs.md)** - -- **[HdfFeatureInfo](_hdf_feature_info.md)** - -- **[HdfLightColor](_hdf_light_color.md)** - -- **[HdfLightEffect](_hdf_light_effect.md)** - -- **[HdfLightFlashEffect](_hdf_light_flash_effect.md)** - -- **[HdfLightInfo](_hdf_light_info.md)** - -- **[HdfMotionEvent](_hdf_motion_event.md)** - -- **[HdfNetDeviceInfo](_hdf_net_device_info.md)** - -- **[HdfNetDeviceInfoResult](_hdf_net_device_info_result.md)** - -- **[HdfSensorEvents](_hdf_sensor_events.md)** - -- **[HdfSensorInformation](_hdf_sensor_information.md)** - -- **[HdfStaInfo](_hdf_sta_info.md)** - -- **[HdfThermalCallbackInfo](_hdf_thermal_callback_info.md)** - -- **[HdfVibratorInfo](_hdf_vibrator_info.md)** - -- **[HdfWifiDriverScanSsid](_hdf_wifi_driver_scan_ssid.md)** - -- **[HdfWifiInfo](_hdf_wifi_info.md)** - -- **[HdfWifiScan](_hdf_wifi_scan.md)** - -- **[HdfWifiScanResult](_hdf_wifi_scan_result.md)** - -- **[HDRCapability](_h_d_r_capability.md)** - -- **[HDRMetaData](_h_d_r_meta_data.md)** - -- **[IActivityChangedCallback](interface_i_activity_changed_callback.md)** - -- **[IActivityInterface](interface_i_activity_interface.md)** - -- **[IBatteryCallback](interface_i_battery_callback.md)** - -- **[IBatteryInterface](interface_i_battery_interface.md)** - -- **[ICameraDevice](interface_i_camera_device.md)** - -- **[ICameraDeviceCallback](interface_i_camera_device_callback.md)** - -- **[ICameraHost](interface_i_camera_host.md)** - -- **[ICameraHostCallback](interface_i_camera_host_callback.md)** - -- **[ICircle](_i_circle.md)** - -- **[IdentifyResultInfo](_identify_result_info.md)** - -- **[IExecutor](interface_i_executor.md)** - -- **[IExecutor](interface_pin_i_executor.md)** - -- **[IExecutorCallback](interface_i_executor_callback.md)** - -- **[IExecutorCallback](interface_pin_i_executor_callback.md)** - -- **[IFaceAuthInterface](interface_i_face_auth_interface.md)** - -- **[ILine](_i_line.md)** - -- **[IInputInterface](_i_input_interface.md)** - -- **[ILightInterface](interface_i_light_interface.md)** - -- **[IMotionCallback](interface_i_motion_callback.md)** - -- **[IMotionInterface](interface_i_motion_interface.md)** - -- **[InputController](_input_controller.md)** - -- **[InputDevAbility](_input_dev_ability.md)** - -- **[InputDevAttr](_input_dev_attr.md)** - -- **[InputDevDesc](_input_dev_desc.md)** - -- **[InputDeviceInfo](_input_device_info.md)** - -- **[InputDevIdentify](_input_dev_identify.md)** - -- **[InputDimensionInfo](_input_dimension_info.md)** - -- **[InputEventCb](_input_event_cb.md)** - -- **[InputEventPackage](_input_event_package.md)** - -- **[IPowerHdiCallback](interface_i_power_hdi_callback.md)** - -- **[InputExtraCmd](_input_extra_cmd.md)** - -- **[InputHostCb](_input_host_cb.md)** - -- **[InputHotPlugEvent](_input_hot_plug_event.md)** - -- **[InputManager](_input_manager.md)** - -- **[InputReporter](_input_reporter.md)** - -- **[IOfflineStreamOperator](interface_i_offline_stream_operator.md)** - -- **[IPinAuthInterface](interface_i_pin_auth_interface.md)** - -- **[IPowerInterface](interface_i_power_interface.md)** - -- **[IRect](_i_rect.md)** - -- **[ISensorCallback](interface_i_sensor_callback.md)** - -- **[ISensorInterface](interface_i_sensor_interface.md)** - -- **[IStreamOperator](interface_i_stream_operator.md)** - -- **[IStreamOperatorCallback](interface_i_stream_operator_callback.md)** - -- **[ISurface](_i_surface.md)** - -- **[IThermalCallback](interface_i_thermal_callback.md)** - -- **[IThermalInterface](interface_i_thermal_interface.md)** - -- **[IUsbdBulkCallback](interface_i_usbd_bulk_callback.md)** - -- **[IUsbdSubscriber](interface_i_usbd_subscriber.md)** - -- **[IUsbInterface](interface_i_usb_interface.md)** - -- **[IUserAuthInterface](interface_i_user_auth_interface.md)** - -- **[IVibratorInterface](interface_i_vibrator_interface.md)** - -- **[IWlanCallback](interface_i_wlan_callback.md)** - -- **[IWlanInterface](interface_i_wlan_interface.md)** - -- **[LayerAlpha](_layer_alpha.md)** - -- **[LayerBuffer](_layer_buffer.md)** - -- **[LayerFuncs](_layer_funcs.md)** - -- **[LayerInfo](_layer_info.md)** - -- **[MeasChannelParam](_meas_channel_param.md)** - -- **[MeasChannelResult](_meas_channel_result.md)** - -- **[OmxCodecBuffer](_omx_codec_buffer.md)** - -- **[PortCap](union_port_cap.md)** - -- **[PortInfo](_port_info.md)** - -- **[PresentTimestamp](_present_timestamp.md)** - -- **[PropertyObject](_property_object.md)** - -- **[ProjectionScreenCmdParam](_projection_screen_cmd_param.md)** - -- **[RangeValue](_range_value.md)** - -- **[Rect](_rect.md)** - -- **[Rectangle](_rectangle.md)** - -- **[RGBColor](_r_g_b_color.md)** - -- **[ScheduleInfo](_schedule_info.md)** - -- **[StreamAttribute](_stream_attribute.md)** - -- **[StreamInfo](_stream_info.md)** - -- **[SupportBufferType](_support_buffer_type.md)** - -- **[TemplateInfo](_template_info.md)** - -- **[ThermalZoneInfo](_thermal_zone_info.md)** - -- **[UsbCtrlTransfer](_usb_ctrl_transfer.md)** - -- **[UsbDev](_usb_dev.md)** - -- **[USBDeviceInfo](_u_s_b_device_info.md)** - -- **[UsbPipe](_usb_pipe.md)** - -- **[UseBufferType](_use_buffer_type.md)** - -- **[VerifyAllocInfo](_verify_alloc_info.md)** - -- **[VGUBuffer](_v_g_u_buffer.md)** - -- **[VGUColorStop](_v_g_u_color_stop.md)** - -- **[VGUConic](_v_g_u_conic.md)** - -- **[VGUFillAttr](_v_g_u_fill_attr.md)** - -- **[VGUFuncs](_v_g_u_funcs.md)** - -- **[VGUGradient](_v_g_u_gradient.md)** - -- **[VGUImage](_v_g_u_image.md)** - -- **[VGULinear](_v_g_u_linear.md)** - -- **[VGUMaskLayer](_v_g_u_mask_layer.md)** - -- **[VGUMatrix3](_v_g_u_matrix3.md)** - -- **[VGUPaintStyle](_v_g_u_paint_style.md)** - -- **[VGUPath](_v_g_u_path.md)** - -- **[VGUPattern](_v_g_u_pattern.md)** - -- **[VGUPoint](_v_g_u_point.md)** - -- **[VGURadial](_v_g_u_radial.md)** - -- **[VGURect](_v_g_u_rect.md)** - -- **[VGUSolid](_v_g_u_solid.md)** - -- **[VGUStrokeAttr](_v_g_u_stroke_attr.md)** - -- **[VGUSurface](_v_g_u_surface.md)** - -- **[VideoPortCap](_video_port_cap.md)** - -- **[WifiStationInfo](_wifi_station_info.md)** - -- **[WRGBColor](_w_r_g_b_color.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/reference/hdi-apis/files.md b/zh-cn/device-dev/reference/hdi-apis/files.md deleted file mode 100644 index c4c4f5171e25975eb0c0e29c0c73ed189c29a62d..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/reference/hdi-apis/files.md +++ /dev/null @@ -1,145 +0,0 @@ -# 头文件 - - - -- **[audio_adapter.h](audio__adapter_8h.md)** - -- **[audio_attribute.h](audio__attribute_8h.md)** - -- **[audio_capture.h](audio__capture_8h.md)** - -- **[audio_control.h](audio__control_8h.md)** - -- **[audio_manager.h](audio__manager_8h.md)** - -- **[audio_render.h](audio__render_8h.md)** - -- **[audio_scene.h](audio__scene_8h.md)** - -- **[audio_types.h](audio__types_8h.md)** - -- **[audio_volume.h](audio__volume_8h.md)** - -- **[codec_callback_if.h](codec_callback_if_h.md)** - -- **[codec_common_type.h](codec_common_type_h.md)** - -- **[codec_component_if.h](codec_component_if_h.md)** - -- **[codec_component_manager.h](codec__component__manager_h.md)** - -- **[codec_component_type.h](codec__component__type_h.md)** - -- **[display_device.h](display__device_8h.md)** - -- **[display_gfx.h](display__gfx_8h.md)** - -- **[display_gralloc.h](display__gralloc_8h.md)** - -- **[display_layer.h](display__layer_8h.md)** - -- **[display_type.h](display__type_8h.md)** - -- **[display_vgu.h](display__vgu_8h.md)** - -- **[input_controller.h](input__controller_8h.md)** - -- **[input_manager.h](input__manager_8h.md)** - -- **[input_reporter.h](input__reporter_8h.md)** - -- **[input_type.h](input__type_8h.md)** - -- **[ActivityRecognitionTypes.idl](activity_recognition_types_idl.md)** - -- **[Types.idl](battery_types_idl.md)** - -- **[IExecutor.idl](face__auth_2_i_executor_8idl.md)** - -- **[IExecutorCallback.idl](face__auth_2_i_executor_callback_8idl.md)** - -- **[FaceAuthTypes.idl](_face_auth_types_8idl.md)** - -- **[PinAuthTypes.idl](_pin_auth_types_8idl.md)** - -- **[IExecutor.idl](pin__auth_2_i_executor_8idl.md)** - -- **[IExecutorCallback.idl](pin__auth_2_i_executor_callback_8idl.md)** - -- **[IFaceAuthInterface.idl](_i_face_auth_interface_8idl.md)** - -- **[IPinAuthInterface.idl](_i_pin_auth_interface_8idl.md)** - -- **[IUserAuthInterface.idl](_i_user_auth_interface_8idl.md)** - -- **[UserAuthTypes.idl](_user_auth_types_8idl.md)** - -- **[IActivityChangedCallback.idl](_i_activity_changed_callback_8idl.md)** - -- **[IActivityInterface.idl](_i_activity_interface_8idl.md)** - -- **[IBatteryCallback.idl](_i_battery_callback_8idl.md)** - -- **[IBatteryInterface.idl](_i_battery_interface_8idl.md)** - -- **[ICameraDevice.idl](_i_camera_device_8idl.md)** - -- **[ICameraDeviceCallback.idl](_i_camera_device_callback_8idl.md)** - -- **[ICameraHostCallback.idl](_i_camera_host_callback_8idl.md)** - -- **[ICameraHost.idl](_i_camera_host_8idl.md)** - -- **[ILightInterface.idl](_i_light_interface_8idl.md)** - -- **[IMotionCallback.idl](_i_motion_callback_8idl.md)** - -- **[IMotionInterface.idl](_i_motion_interface_8idl.md)** - -- **[IOfflineStreamOperator.idl](_i_offline_stream_operator_8idl.md)** - -- **[IPowerHdiCallback.idl](_i_power_hdi_callback_8idl.md)** - -- **[IPowerInterface.idl](_i_power_interface_8idl.md)** - -- **[ISensorCallback.idl](_i_sensor_callback_8idl.md)** - -- **[ISensorInterface.idl](_i_sensor_interface_8idl.md)** - -- **[IStreamOperator.idl](_i_stream_operator_8idl.md)** - -- **[IStreamOperatorCallback.idl](_i_stream_operator_callback_8idl.md)** - -- **[IThermalCallback.idl](_i_thermal_callback_8idl.md)** - -- **[IThermalInterface.idl](_i_thermal_interface_8idl.md)** - -- **[IUsbdBulkCallback.idl](_i_usbd_bulk_callback_8idl.md)** - -- **[IUsbInterface.idl](_i_usb_interface_8idl.md)** - -- **[IUsbdSubscriber.idl](_i_usbd_subscriber_8idl.md)** - -- **[IVibratorInterface.idl](_i_vibrator_interface_8idl.md)** - -- **[IWlanCallback.idl](_i_wlan_callback_8idl.md)** - -- **[IWlanInterface.idl](_i_wlan_interface_8idl.md)** - -- **[LightTypes.idl](_light_types_8idl.md)** - -- **[MotionTypes.idl](_motion_types_8idl.md)** - -- **[PowerTypes.idl](_power_types_8idl.md)** - -- **[SensorTypes.idl](_sensor_types_8idl.md)** - -- **[ThermalTypes.idl](_thermal_types_8idl.md)** - -- **[Types.idl](camera_2v1__0_2_types_8idl.md)** - -- **[UsbTypes.idl](_usb_types_8idl.md)** - -- **[VibratorTypes.idl](_vibrator_types_8idl.md)** - -- **[WlanTypes.idl](_wlan_types_8idl.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/reference/hdi-apis/modulelist.md b/zh-cn/device-dev/reference/hdi-apis/modulelist.md deleted file mode 100644 index a0969df08272de3d04f006ea7643d30eec42deed..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/reference/hdi-apis/modulelist.md +++ /dev/null @@ -1,39 +0,0 @@ -# 模块 - - - -- **[Audio](_audio.md)** - -- **[Battery](battery.md)** - -- **[Camera](camera.md)** - -- **[Codec](codec.md)** - -- **[Display](_display.md)** - -- **[HdfFaceAuth](_hdf_face_auth.md)** - -- **[HdfPinAuth](_hdf_pin_auth.md)** - -- **[HdfUserAuth](_hdf_user_auth.md)** - -- **[HdiActivityRecognition](activity_recognition.md)** - -- **[Input](input.md)** - -- **[Light](light.md)** - -- **[Motion](motion.md)** - -- **[Power](power.md)** - -- **[Sensor](sensor.md)** - -- **[Thermal](thermal.md)** - -- **[USB](usb.md)** - -- **[Vibrator](vibrator.md)** - -- **[WLAN](wlan.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/reference/hdi-apis/total.md b/zh-cn/device-dev/reference/hdi-apis/total.md deleted file mode 100644 index bac50766065bf942c00fe3d98e89e1772b2b5087..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/reference/hdi-apis/total.md +++ /dev/null @@ -1,7 +0,0 @@ -# 头文件和结构体 - - - -- **[头文件](files.md)** - -- **[结构体](annotated.md)** \ No newline at end of file diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 55484af986e76860b2bfa24072e8b689a45f2ff7..9f7d8e47a86f06a2ec8df38a2142c70614251a1c 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -5,17 +5,18 @@ - [构建系统编码规范与最佳实践](subsys-build-gn-coding-style-and-best-practice.md) - [编译构建Kconfig可视化配置指导](subsys-build-gn-kconfig-visual-config-guide.md) - 编译构建相关操作 - - [产品配置规则](subsys-build-product.md#产品配置规则) - - [子系统配置规则](subsys-build-subsystem.md#子系统配置规则) - - [部件配置规则](subsys-build-component.md#部件配置规则) - - [模块配置规则](subsys-build-module.md#模块配置规则) - - [芯片解决方案配置规则](subsys-build-chip_solution.md#芯片解决方案配置规则) - - [特性配置规则](subsys-build-feature.md#特性配置规则) - - [系统能力配置规则](subsys-build-syscap.md#如何按需配置部件的系统能力) - - [关于deps、external_deps的使用](subsys-build-reference.md#关于deps、external_deps的使用) - - [开源软件Notice收集策略说明](subsys-build-reference.md#开源软件notice收集策略说明) - - [加快本地编译的一些参数](subsys-build-reference.md#加快本地编译的一些参数) - - [查看NinjaTrace](subsys-build-reference.md#查看ninjatrace) + - [产品配置规则](subsys-build-product.md) + - [子系统配置规则](subsys-build-subsystem.md) + - [部件配置规则](subsys-build-component.md) + - [部件编译构建规范](subsys-build-component-building-rules.md) + - [模块配置规则](subsys-build-module.md) + - [芯片解决方案配置规则](subsys-build-chip_solution.md) + - [特性配置规则](subsys-build-feature.md) + - [系统能力配置规则](subsys-build-syscap.md) + - [关于deps、external_deps的使用](subsys-build-reference.md) + - [开源软件Notice收集策略说明](subsys-build-reference.md) + - [加快本地编译的一些参数](subsys-build-reference.md) + - [查看NinjaTrace](subsys-build-reference.md) - [HAP编译构建指导](subsys-build-gn-hap-compilation-guide.md) - [ 常见问题](subsys-build-FAQ.md) - [ArkCompiler](subsys-arkcompiler-guide.md) @@ -89,12 +90,12 @@ - [bootstrap服务启动组件](subsys-boot-bootstrap.md) - [常见问题](subsys-boot-faqs.md) - [参考](subsys-boot-ref.md) -- [测试用例开发指导](subsys-testguide-test.md) - DFX - [DFX概述](subsys-dfx-overview.md) - [HiLog开发指导](subsys-dfx-hilog-rich.md) - [HiLog_Lite开发指导](subsys-dfx-hilog-lite.md) - [HiTraceChain开发指导](subsys-dfx-hitracechain.md) + - [HiTraceMeter开发指导](subsys-dfx-hitracemeter.md) - [HiCollie开发指导](subsys-dfx-hicollie.md) - HiSysEvent开发指导 - [HiSysEvent概述](subsys-dfx-hisysevent-overview.md) @@ -111,4 +112,3 @@ - [bytrace使用指导](subsys-toolchain-bytrace-guide.md) - [hdc_std使用指导](subsys-toolchain-hdc-guide.md) - [hiperf使用指导](subsys-toolchain-hiperf.md) -- [XTS测试用例开发指导](subsys-xts-guide.md) diff --git a/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md index 020e0a82a397b846a769a4fc48d245a07b0a1520..513de0dc06f003d0eb327850d4c65dd37fbb42f5 100644 --- a/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-arkcompiler-guide.md @@ -32,14 +32,14 @@ ArkCompiler是一种统一编程平台,包含编译器、工具链、运行时 ## 开发步骤 -1. 生成编译产物ark_js_vm及js2abc。 +1. 生成编译产物ark_js_vm及ts2panda。 ```shell python ark.py x64.release ``` - ark_js_vm:运行abc文件的可执行程序。 - - js2abc:将ArkTS文件转换生成ArkCompiler字节码文件的工具。 + - ts2panda:将ArkTS文件转换生成ArkCompiler字节码文件的工具。 -2. 将TypeScript文件转换为abc文件。 +2. 使用ts2panda将TypeScript文件转换为abc文件。 ```shell prebuilts/build-tools/common/nodejs/node-v12.18.4-linux-x64/bin/node --expose-gc out/x64.release/clang_x64/obj/arkcompiler/ets_frontend/ts2panda/build/src/index.js helloworld.ts --opt-level 0 ``` diff --git a/zh-cn/device-dev/subsystems/subsys-build-all.md b/zh-cn/device-dev/subsystems/subsys-build-all.md index 602e4e7f22a9f27c59250b2830b3be3be47abd0a..0479d4a589fcf3d0321697e1dc4ebb9bc01776e3 100644 --- a/zh-cn/device-dev/subsystems/subsys-build-all.md +++ b/zh-cn/device-dev/subsystems/subsys-build-all.md @@ -329,7 +329,7 @@ optional arguments: ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> - 设备开发过程中详细的编译环境搭建及编译步骤请参考[快速入门中的环境搭建及编译章节。](../quick-start/Readme-CN.md) +> - 设备开发过程中详细的编译环境搭建及编译步骤请参考[快速入门中的环境搭建及编译章节。](../quick-start/quickstart-overview.md) > - OpenHarmony还为开发者提供了Docker编译环境,可以省略编译工具的安装,具体使用请参考[Docker编译指导。](../get-code/gettools-acquire.md) ### 新增并编译不同配置 diff --git a/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md new file mode 100644 index 0000000000000000000000000000000000000000..c256505552d4f8a3e741853516e1049adcef97ca --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-build-component-building-rules.md @@ -0,0 +1,279 @@ +# 部件编译构建规范 + +## 前言 + +### 目的 + +编译构建是部件化设计落地的切入点,一个优秀的部件在编译态应该具备可维护、可移植、低耦合的特征。本规范用于引导部件开发人员编写符合部件化设计的编译脚本,使得部件在编译态依赖合理、可配置、可复用、可裁剪。 + +### 基本概念 + +**部件** + +部件是OpenHarmony系统能力的基本单元,以源码为划分依据,具有独立的仓和目录,在不同的设备上可实例化为不同的库或二进制文件。 + +**特性** + +部件特性为编译态可配置的编译选项,可供产品在编译时按需配置。不同的特性配置,编译出部件的不同形态,使得部件可以适应不同形态产品的差异化需求。部件特性的配置只影响部件内部功能的实现差异,不能影响部件的Public API(部件对应用提供的接口)以及inner api(部件间的接口)。 + +**依赖** + +在编译态,部件的依赖分为: + +- 有条件依赖:在特定场景下可裁剪的依赖,有条件的依赖裁剪后不影响部件的Public API 和inner api。比如音频对蓝牙的依赖。 +- 强依赖:部件间合理的必要的依赖,不可裁剪。比如syscap部件对安全库函数的依赖。 + +### 总体原则 + +部件编译构建应遵循以下几个原则: + +**独立自治** + +部件编译态应内聚,新增外部依赖时应慎重,尽量减少编译时的静态依赖。 + +**合理依赖** + +部件间的依赖都应基于部件间的接口,禁止依赖其他部件内部的模块和头文件。 + +**产品无关** + +部件在编译态应是多产品通用的,禁止在编译脚本中使用产品名称。 + +### 约定 + +**规则:** 必须遵守的约定。 + +**建议:** 必须加以考虑的约定。 + +### 看护手段 + +为了维护部件编译构建规范,门禁会对构建配置文件做一些检查。 + +预编译检查:指在预编译阶段进行检查,检测到错误将报错并停止编译。 + +静态检查:指检查工具对配置文件进行扫描检查,非编译手段。 + +### 例外 + +在不违背总体原则,经过充分考虑,有充足的理由的前提下,可以适当违背规范中约定。 + +例外破坏了代码的一致性,请尽量避免。“规则”的例外应该是极少的。 + +## 命名 + +编译脚本中的变量、编译目标(target)、模板,gni文件,以及部件描述文件中的对象和数据的命名都应采用内核风格(unix_like),单词全小写,用下划线分割。如:"startup_init"。 + +### 规则1.1 部件名格式须统一 +- 名词形式,需体现部件的功能。 +- 在系统内全局唯一。 +- 不超过63个有效英文字符。 +- 使用小写加下划线的内核风格命名,例如:unix_like。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 三方开源软件的使用对应社区的原生命名方式,比如:cJson。 + +### 规则1.2 特性名为部件名前缀+特性名称 + +特性是部件声明的可配置的编译选项,加上部件名前缀可避免系统内特性重名。示例: + +```py +declare_args() { + dsoftbus_conn_p2p = true # dsoftbus 为部件名, conn_p2p 为特性名称 + dsoftbus_conn_ble = false # dsoftbus 为部件名, conn_ble 为特性名称 +} +``` + +看护手段:预编译检查 + +### 建议1.1 编译目标名以部件名为前缀+模块名称 + +一个部件可能有多个编译目标(即模块),以“{部件名}_{模块名}”的方式命名可以根据编译产物(库、可执行文件)快速定位归属部件和避免重名。 + +反例: +```py +ohos_shared_library("data") # Bad: 不精确,过于通用,系统内易重名 +``` +正例: +```py +ohos_shared_library("cellular_data_napi") # Good +``` + +## 描述文件 + +bundle.json是定义部件的描述文件,包含了部件的根目录、名称、功能描述、版本号、接口定义和编译入口等信息,须保证其准确性。 + +### 规则2.1 部件描述文件中字段须准确 + +| 字段 | 类型 | 看护手段 | +|---|---|---| +|name|string。部件的HPM(鸿蒙包管理器)包名称,必填。命名规则:@{organization}/{component_name}。"component_name"为部件的名称,须满足规则1.1。|静态检查| +|version|string。部件版本号,必填,命名和升级跟随OpenHarmony版本号。|静态检查| +|destPath|string。部件源码的根目录,必填。部件的根目录须独立唯一,不允许存在多个根目录。|静态检查| +|component:name|string。部件名,必填。须满足规则1.1。|静态检查| +|component:subsystem|string。部件归属的子系统名称,必填,子系统名为小写英文字母组合、不使用下划线。|静态检查| +|component:syscap|string list。系统能力的描述,可选。命名规则:大驼峰,"SystemCapability.Subsystem.部件能力.子能力(可选)",如`SystemCapability.Media.Camera`,`SystemCapability.Media.Camera.Front`。|静态检查| +|component:features|string list,部件可配置的特性,可选,命名须满足规则1.2。|静态检查| +|component:adapted_system_type|string list。部件适用的系统类型,必填,值为`mini`、`small`和`standard`,可同时支持多种。|静态检查| +|component:rom|string。ROM基线值,必填,单位默认为KByte。|静态检查| +|component:ram|string。RAM基线值,必填,单位默认为KByte。|静态检查| +|component:deps|string list。deps对象描述了部件的外部依赖,必填,包括其他部件和三方开源软件,应该与部件编译脚本中依赖一致。|预编译检查| + + +### 建议2.1 部件的描述文件应存放在部件根目录下 + +部件目录是独立的,应将bundle.json文件存放到部件根目录下。 + +## 变量 + +编译目标(target)的内置变量赋值决定了编译内容、依赖和打包等信息,与实现部件化设计强相关。 + +### 规则3.1 部件编译脚本中只允许引用本部件的路径,禁止引用其他部件的绝对或相对路径 + +部件间的依赖都必须使用"externel_deps",部件编译目标的变量sources、include_dirs、configs、public_configs、deps、public_deps引用其他部件的相对和绝对路径属于非法引入依赖: + +- sources + + sources只允许包含本部件的源码,包含其他部件的源码破坏了部件源码目录独立的原则。 + +- include_dirs + + include_dirs只允许引用本部件的头文件搜索路径,编译单元对其他部件的接口的依赖都通过externel_deps自动导入。 + +- configs + + configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- pulic_configs + + pulic_configs只允许引用本部件的配置路径,引用其他部件的configs可能会引入接口依赖。 + +- deps + + deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + 例: + + base/foos/foo_a/BUILD.gn + + ```py + deps = [ "//base/foo/foo_b:b" ] # Bad, 绝对路径依赖其他部件 + deps = [ "../../foo_b:b" ] # Bad, 相对路径依赖其他部件 + deps = [ "a" ] # Good, 依赖当前部件内的其他模块 + ``` + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + +- public_deps + + public_deps只允许用于部件内模块的依赖,直接引用其他部件的模块可能会导致依赖其他部件的内部模块和接口。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **例外:** 对三方开源软件的引用除外。 + + +看护手段:静态检查 + +### 规则3.2 部件编译目标必须指定部件和子系统名 + +部件的编译单元ohos_shared_library、ohos_static_library、ohos_executable_library、ohos_source_set都必须指定"part_name"和"subsystem_name"。 + +以developtools/syscap_codec/BUILD.gn的ohos_shared_library编译单元为例: + +```py +ohos_shared_library("syscap_interface_shared") { + include_dirs = [ + "include", + "src", + ] + public_configs = [ ":syscap_interface_public_config" ] + sources = [ + "./interfaces/inner_api/syscap_interface.c", + "./src/endian_internal.c", + "./src/syscap_tool.c", + ] + deps = [ + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + subsystem_name = "developtools" # 必须指定subsystem_name + part_name = "syscap_codec" # 必须指定part_name +} +``` + +看护手段:静态检查 + +### 建议3.1 部件内部的引用使用相对路径 + +部件内的引用使用相对路径的优点: + +- 脚本更简洁 + +- 部件的编译脚本与部件的根目录解耦。 + +例: + +base/foos/foo_a/BUILD.gn + +```py +include_dirs = [ + "./include", # Good, 相对路径引用 + "//base/foo/foo_a/include" # Bad, 绝对路径引用 +] + +deps = [ + "sub_module:foo", # Good, 相对路径引用 + "base/foo/foo_a/sub_moudule:foo" # Bad, 绝对路径引用 +] +``` + +看护手段:静态检查 + +### 建议3.2 部件内部模块的可见度设置为部件内可见 + +部件内部的模块应使用`"visibility"`字段标识,防止被其他部件依赖。示例: + +base/foos/foo_a/BUILD.gn + +```py +ohos_shared_library("foo_a") { + visibility = [ "./*" ] # foo_a只在base/foo/foo_a及其子目录下可见 +} + +ohos_shared_library("foo_a") { + visibility = [ ":*" ] # foo_a只在本BUILD.gn可见 +} +``` + +## 其他 + +### 规则4.1 部件编译脚本中禁止使用产品名称变量 + +部件是通用的系统能力,与特定产品无关。编译脚本中使用产品名称,将导致部件功能与产品绑定,不具备通用性。部件不同产品形态上的差异应抽象为特性或者运行时的插件。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** vendor和device目录下三方厂商部件的编译脚本例外。 + +看护手段:静态检查 + +### 建议4.1 避免import其他部件目录下的gni文件 + +部件内的gni文件用于声明部件内部编译变量和模板,import其他部件的gni文件等同于使用其他部件内部的变量和模板,即引入对其他部件的依赖。影响多个部件的变量、args和模板应定义在编译框架的gni文件中。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**例外:** build目录下编译框架定义全局的编译选项的gni可以被所有部件import。 + +看护手段:静态检查 + +### 建议4.2 部件使用统一的编译单元模板 + +轻量、小型和标准的系统的编译单元都应使用ohos定义的模板,比如`ohos_shared_library`、`ohos_static_library`、`ohos_executable`、`ohos_source_set`等以"ohos_"为前缀的模板。 + +例如: + +```py + executable("foundation") { # Bad, 不推荐使用内置的模板 + ... + } + + ohos_executable("foundation") { # Good, 推荐使用ohos定制模板 + ... + } +``` + diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md index 4c8ed67988e5d30c5adcc5532fef02e2b376c0ea..8c871f3957bc0bb8f8ba3c962b7c7e63f5711050 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging.md @@ -4,82 +4,191 @@ ### 功能简介 -HiSysEvent打点提供了事件埋点功能,开发者可以通过在关键路径埋点来记录系统在运行过程中的重要信息。同时,HiSysEvent打点也提供了以事件领域为单位的HiSysEvent打点屏蔽机制,方便开发者评估及调试HiSysEvent打点操作的影响。 +HiSysEvent打点提供了事件打点功能,开发者可以通过在关键路径打点来记录系统在运行过程中的重要信息。同时,HiSysEvent打点也提供了以事件领域为单位的HiSysEvent打点屏蔽机制,方便开发者评估及调试HiSysEvent打点操作的影响。 ### 运作机制 -在进行HiSysEvent事件埋点之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[HiSysEvent打点配置指导](subsys-dfx-hisysevent-logging-config.md)。 +在进行HiSysEvent事件打点之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[HiSysEvent打点配置指导](subsys-dfx-hisysevent-logging-config.md)。 ## 开发指导 ### 场景介绍 -事件埋点的主要工作是将打点数据进行落盘。 +事件打点的主要工作是将打点数据进行落盘。 ### 接口说明 #### C++接口说明 -C++事件埋点开发能力如下:HiSysEvent类,具体的API详见接口文档 。 +C++事件打点开发能力如下:HiSysEvent类,具体API详见接口目录(/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include/)。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > -> 在OpenHarmony-3.2-Beta3版本中,为避免打点风暴事件引发性能问题,对HiSysEvent打点进行了管控。表1中的HiSysEvent::Write打点API接口被表2中的HiSysEventWrite宏接口取代。HiSysEvent::Write接口已废弃,请使用HiSysEventWrite宏完成HiSysEvent事件打点。 +> 从OpenHarmony-3.2-Beta3版本开始,为避免打点风暴事件引发性能问题,对HiSysEvent打点进行了管控。表1中的HiSysEvent::Write打点接口被表2中的HiSysEventWrite宏接口取代。HiSysEvent::Write接口已废弃,请使用HiSysEventWrite宏接口完成HiSysEvent事件打点。 -**表1** C++事件埋点API接口功能介绍(已废弃) +**表1** 事件打点接口(已废弃) | 接口名 | 描述 | | ------------------------------------------------------------ | --------------------- | -| template<typename... Types> 
static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | 将打点事件数据进行落盘 | +| template<typename... Types> 
static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues) | 将打点事件数据进行落盘。 | + +**表2** 事件打点宏接口 -**表2** C++事件埋点API接口功能介绍 | 接口名 | 描述 | | ------------------------------------------------------------ | --------------------- | -| HiSysEventWrite(domain, eventName, type, ...) | 将打点事件数据进行落盘 | +| HiSysEventWrite(domain, eventName, type, ...) | 将打点事件数据进行落盘。 | - **表3** C++事件类型介绍 + **表3** EventType事件类型枚举 | 事件类型 | 描述 | | --------- | ----------- | -| FAULT | 故障类型事件 | -| STATISTIC | 统计类型事件 | -| SECURITY | 安全类型事件 | -| BEHAVIOR | 行为类型事件 | +| FAULT | 故障类型事件。 | +| STATISTIC | 统计类型事件。 | +| SECURITY | 安全类型事件。 | +| BEHAVIOR | 行为类型事件。 | + +#### C接口说明 + +C事件打点开发能力如下:具体API详见接口目录(/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent/include/)。 + +**表4** 事件打点接口 + +| 接口名 | 描述 | +| ------------------------------------------------------------ | ------------------------ | +| int OH_HiSysEvent_Write(const char\* domain, const char\* name, HiSysEventEventType type, HiSysEventParam params[], size_t size); | 将打点事件数据进行落盘。 | + +**表5** HiSysEventEventType事件类型枚举 + +| 事件类型 | 描述 | +| -------------------- | -------------- | +| HISYSEVENT_FAULT | 故障类型事件。 | +| HISYSEVENT_STATISTIC | 统计类型事件。 | +| HISYSEVENT_SECURITY | 安全类型事件。 | +| HISYSEVENT_BEHAVIOR | 行为类型事件。 | + +**表6** HiSysEventParam事件参数结构体 + +| 属性名称 | 属性类型 | 描述 | +| --------- | -------------------- | ---------------------------------- | +| name | char name[] | 事件参数名称。 | +| t | HiSysEventParamType | 事件参数类型。 | +| v | HiSysEventParamValue | 事件参数值。 | +| arraySize | size_t | 事件参数值为数组类型时的数组长度。 | + +**表7** HiSysEventParamType事件参数类型枚举 + +| 参数类型 | 描述 | +| ----------------------- | -------------------------- | +| HISYSEVENT_INVALID | 无效类型事件参数。 | +| HISYSEVENT_BOOL | bool类型事件参数。 | +| HISYSEVENT_INT8 | int8_t类型事件参数。 | +| HISYSEVENT_UINT8 | uint8_t类型事件参数。 | +| HISYSEVENT_INT16 | int16_t类型事件参数。 | +| HISYSEVENT_UINT16 | uint16_t类型事件参数。 | +| HISYSEVENT_INT32 | int32_t类型事件参数。 | +| HISYSEVENT_UINT32 | uint32_t类型事件参数。 | +| HISYSEVENT_INT64 | int64_t类型事件参数。 | +| HISYSEVENT_UINT64 | uint64_t类型事件参数。 | +| HISYSEVENT_FLOAT | float类型事件参数。 | +| HISYSEVENT_DOUBLE | double类型事件参数。 | +| HISYSEVENT_STRING | char*类型事件参数。 | +| HISYSEVENT_BOOL_ARRAY | bool数组类型事件参数。 | +| HISYSEVENT_INT8_ARRAY | int8_t数组类型事件参数。 | +| HISYSEVENT_UINT8_ARRAY | uint8_t数组类型事件参数。 | +| HISYSEVENT_INT16_ARRAY | int16_t数组类型事件参数。 | +| HISYSEVENT_UINT16_ARRAY | uint16_t数组类型事件参数。 | +| HISYSEVENT_INT32_ARRAY | int32_t数组类型事件参数。 | +| HISYSEVENT_UINT32_ARRAY | uint32_t数组类型事件参数。 | +| HISYSEVENT_INT64_ARRAY | int64_t数组类型事件参数。 | +| HISYSEVENT_UINT64_ARRAY | uint64_t数组类型事件参数。 | +| HISYSEVENT_FLOAT_ARRAY | float数组类型事件参数。 | +| HISYSEVENT_DOUBLE_ARRAY | double数组类型事件参数。 | +| HISYSEVENT_STRING_ARRAY | char*数组类型事件参数。 | + +**表8** HiSysEventParamValue事件参数值联合体 + +| 属性名称 | 属性类型 | 描述 | +| -------- | -------- | ------------------------ | +| b | bool | bool类型事件参数值。 | +| i8 | int8_t | int8_t类型事件参数值。 | +| ui8 | uint8_t | uint8_t类型事件参数值。 | +| i16 | int16_t | int16_t类型事件参数值。 | +| ui16 | uint16_t | uint16_t类型事件参数值。 | +| i32 | int32_t | int32_t类型事件参数值。 | +| ui32 | uint32_t | uint32_t类型事件参数值。 | +| i64 | int64_t | int64_t类型事件参数值。 | +| ui64 | uint64_t | uint64_t类型事件参数值。 | +| f | float | float类型事件参数值。 | +| d | double | double类型事件参数值。 | +| s | char* | char*类型事件参数值。 | +| array | void* | 数组类型事件参数值。 | #### kernel接口说明 -kernel事件埋点开发能力如下: +kernel事件打点开发能力如下:具体API详见接口文件(/kernel/linux/linux-5.10/include/dfx/hiview_hisysevent.h)。 -**表4** kernel事件埋点API接口功能介绍 +**表9** 事件打点接口 | 接口名 | 描述 | | ------------------------------------------------------------ | ----------------------------------- | -| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | 创建一个事件对象 | -| void hisysevent_destroy(struct hiview_hisysevent *event); | 销毁一个事件对象 | -| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | 将整数类型的事件参数添加到事件对象 | -| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | 将字符串类型的事件参数添加到事件对象 | -| int hisysevent_write(struct hiview_hisysevent *event); | 将事件对象数据进行落盘 | +| struct hiview_hisysevent *hisysevent_create(const char *domain, const char *name, enum hisysevent_type type); | 创建一个事件对象。 | +| void hisysevent_destroy(struct hiview_hisysevent *event); | 销毁一个事件对象。 | +| int hisysevent_put_integer(struct hiview_hisysevent *event, const char *key, long long value); | 将整数类型的事件参数添加到事件对象。 | +| int hisysevent_put_string(struct hiview_hisysevent *event, const char *key, const char *value); | 将字符串类型的事件参数添加到事件对象。 | +| int hisysevent_write(struct hiview_hisysevent *event); | 将事件对象数据进行落盘。 | -**表5** kernel事件类型介绍 +**表10** hisysevent_type事件类型枚举 | 事件类型 | 描述 | | --------- | ----------- | -| FAULT | 故障类型事件 | -| STATISTIC | 统计类型事件 | -| SECURITY | 安全类型事件 | -| BEHAVIOR | 行为类型事件 | +| FAULT | 故障类型事件。 | +| STATISTIC | 统计类型事件。 | +| SECURITY | 安全类型事件。 | +| BEHAVIOR | 行为类型事件。 | ### 开发步骤 -#### C++埋点开发步骤 +#### C++打点开发步骤 -1. 在需要埋点的地方直接调用埋点接口,并传入相应事件参数。 +在需要打点的地方直接调用打点接口,并传入相应事件参数。 ```c++ HiSysEventWrite(HiSysEvent::Domain::AAFWK, "START_APP", HiSysEvent::EventType::BEHAVIOR, "APP_NAME", "com.ohos.demo"); ``` -#### kernel埋点开发步骤 +#### C打点开发步骤 + +1. 如果需要在打点时传入自定义事件参数,先要根据事件参数类型创建对应的事件参数对象,再将其放入到事件参数数组中。 + + ```c + // 创建一个int32_t类型的事件参数 + HiSysEventParam param1 = { + .name = "KEY_INT32", + .t = HISYSEVENT_INT32, + .v = { .i32 = 1 }, + .arraySize = 0, + }; + + // 创建一个int32_t数组类型的事件参数 + int32_t int32Arr[] = { 1, 2, 3 }; + HiSysEventParam param2 = { + .name = "KEY_INT32_ARR", + .t = HISYSEVENT_INT32_ARRAY, + .v = { .array = int32Arr }, + .arraySize = sizeof(int32Arr) / sizeof(int32Arr[0]), + }; + + // 将事件参数对象放入创建的事件参数数组中 + HiSysEventParam params[] = { param1, param2 }; + ``` + +2. 在需要打点的地方调用打点接口,并传入相应事件参数。 + + ```c + OH_HiSysEvent_Write("TEST_DOMAIN", "TEST_NAME", HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0])); + ``` + +#### kernel打点开发步骤 1. 根据事件领域、事件名称、事件类型参数,创建一个基础的事件对象。 @@ -141,9 +250,9 @@ kernel事件埋点开发能力如下: ### 开发实例 -#### C++埋点开发实例 +#### C++打点开发实例 -假设业务模块需要在应用启动时进行埋点来记录应用启动事件,且需要记录应用的包名信息,完整使用示例如下所示: +假设业务模块需要在应用启动时进行打点来记录应用启动事件,且需要记录应用的包名信息,完整使用示例如下所示: 1. 首先,需要在业务模块的在BUILD.gn里增加HiSysEvent部件依赖。 @@ -151,7 +260,7 @@ kernel事件埋点开发能力如下: external_deps = [ "hisysevent_native:libhisysevent" ] ``` -2. 在业务模块的应用启动函数StartAbility()中,调用埋点接口并传入对应事件参数。 +2. 在业务模块的应用启动函数StartAbility()中,调用打点接口并传入对应事件参数。 ```c++ #include "hisysevent.h" @@ -164,9 +273,40 @@ kernel事件埋点开发能力如下: } ``` -#### kernel埋点开发实例 +#### C打点开发实例 + +假设业务模块需要在应用启动时进行打点来记录应用启动事件,且需要记录应用的包名信息,完整使用示例如下所示: + +1. 首先,需要在业务模块的在BUILD.gn里增加HiSysEvent部件依赖。 + + ```c++ + external_deps = [ "hisysevent_native:libhisysevent" ] + ``` + +2. 在业务模块的应用启动函数StartAbility()中,调用打点接口并传入对应事件参数。 + + ```c + #include "hisysevent_c.h" + + int StartAbility() + { + ... // 其他业务逻辑 + char packageName[] = "com.ohos.demo"; + HiSysEventParam param = { + .name = "APP_NAME", + .t = HISYSEVENT_STRING, + .v = { .s = packageName }, + .arraySize = 0, + }; + HiSysEventParam params[] = { param }; + int ret = OH_HiSysEvent_Write("AAFWK", "START_APP", HISYSEVENT_BEHAVIOR, params, sizeof(params) / sizeof(params[0])); + ... // 其他业务逻辑 + } + ``` + +#### kernel打点开发实例 -假设内核业务模块需要在设备启动时进行埋点来记录设备启动事件,完整使用示例如下所示: +假设内核业务模块需要在设备启动时进行打点来记录设备启动事件,完整使用示例如下所示: 1. 在设备启动函数device_boot()中,构建一个启动事件对象,然后将事件进行上报,最后销毁事件对象。 @@ -204,7 +344,6 @@ kernel事件埋点开发能力如下: - 假设业务模块中,需要在某个cpp文件中屏蔽名称分别为AAFWK和POWER的事件领域的打点,在该cpp文件引入hisysevent.h头文件之前,定义名称为DOMAIN_MASKS的宏: ```c++ - #define DOMAIN_MASKS "AAFWK|POWER" #include "hisysevent.h" @@ -212,14 +351,13 @@ kernel事件埋点开发能力如下: HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::AAFWK, "JS_ERROR", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "MODULE", "com.ohos.module"); // 该HiSysEvent打点操作不会执行 ... // 其他业务逻辑 HiSysEventWrite(OHOS:HiviewDFX::HiSysEvent::Domain::POWER, "POWER_RUNNINGLOCK", OHOS:HiviewDFX::HiSysEvent::EventType::FAULT, "NAME", "com.ohos.module"); // 该HiSysEvent打点操作不会执行 - ``` - 假设需要在整个业务模块中屏蔽名称分别为AAFWK和POWER的事件领域的打点,在模块的BUILG.gn文件中定义名称为DOMAIN_MASKS的宏: ```gn config("module_a") { - ... // 其他配置项 - cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""] + ... // 其他配置项 + cflags_cc += ["-DDOMAIN_MASKS=\"AAFWK|POWER\""] } ``` @@ -231,4 +369,4 @@ kernel事件埋点开发能力如下: # 参考 -HiSysEvent模块会将埋点数据写入到节点文件中,而埋点数据的解析处理会在Hiview模块中统一进行,详细处理过程可参考[Hiview开发指导](subsys-dfx-hiview.md)。 +HiSysEvent模块会将打点数据写入到节点文件中,而打点数据的解析处理会在Hiview模块中统一进行,详细处理过程可参考[Hiview开发指导](subsys-dfx-hiview.md)。 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-query.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-query.md index 180706d7e409c2fed9046ce5d0402c2c969e9192..9ea8b3859494f92ee72d5d291bfa13b45ebf4854 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-query.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-query.md @@ -8,105 +8,380 @@ HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事 ## 开发指导 - ### 接口说明 +#### C++接口说明 + +C++ HiSysEvent查询开发能力如下:HiSysEventManager类,具体API详见接口目录(/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/)。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > -> HiSysEventQueryCallback查询回调对象OnQuery方法中的形参类型HiSysEventRecord请参考[HiSysEvent订阅](subsys-dfx-hisysevent-listening.md)中的**表5**HiSysEventRecord系统事件对象说明 +> HiSysEventQueryCallback查询回调对象OnQuery方法中的形参类型HiSysEventRecord请参考[HiSysEvent订阅](subsys-dfx-hisysevent-listening.md)中的“表5 HiSysEventRecord系统事件对象”说明。 **表1** HiSysEvent查询接口 -| 接口名 | 描述 | +| 接口名称 | 描述 | | -------- | -------- | -| int32_t HiSysEventManager::Query(struct QueryArg& arg,
 std::vector<QueryRule>& rules,
 std::shared_ptr<HiSysEventQueryCallback> callback) | 接口功能:支持设置时间段,事件领域,事件名称等,查询满足条件的HiSysEvent事件。
输入参数:
- arg:查询参数。
- rules:事件过滤规则。
- callback:查询接口回调对象。
返回值:
- 0:查询成功。
- 负值:查询失败。 | +| int32_t Query(struct QueryArg& arg,
std::vector<QueryRule>& rules,
std::shared_ptr<HiSysEventQueryCallback> callback) | 接口功能:支持根据时间段、事件领域、事件名称等条件,查询满足条件的HiSysEvent事件。
输入参数:
- arg:查询参数。
- rules:事件过滤规则。
- callback:查询接口回调对象。
返回值:
- 0:查询成功。
- 负值:查询失败。 | **表2** QueryArg查询参数对象 -| 属性名称 | 描述 | -| -------- | -------- | -| beginTime | long long int类型,用于指定查询事件的开始时间。 | -| endTime | long long int类型,用于指定查询事件的结束时间。 | -| maxEvents | int类型,用于指定查询返回事件查询的最多条数。 | +| 属性名称 | 属性类型 | 描述 | +| -------- | -------- | -------- | +| beginTime | long long | 用于指定查询事件的开始时间,格式为Unix毫秒级时间戳。 | +| endTime | long long | 用于指定查询事件的结束时间,格式为Unix毫秒级时间戳。 | +| maxEvents | int | 用于指定查询返回事件的最多条数。 | **表3** QueryRule查询规则对象 | 接口名称 | 描述 | | -------- | -------- | -| QueryRule(const std::string& domain,
 const std::vector<std::string>& eventList) | 接口功能:查询规则构造函数,创建查询规则对象。
输入参数:
- domain:string类型,用来标识查询规则对象的事件所属领域,如果传入的是空字符串,则默认事件领域字段匹配成功。
- eventList:std::vector<std::string>类型,事件名称的列表,如果传入的是空字符串,则默认事件名称字段匹配成功。 | +| QueryRule(const std::string& domain,
const std::vector<std::string>& eventList) | 接口功能:查询规则构造函数,创建查询规则对象。
输入参数:
- domain:string类型,用来标识查询规则对象的事件所属领域,如果传入的是空字符串,则默认事件领域字段匹配成功。
- eventList:std::vector<std::string>类型,事件名称的列表,如果传入的是空字符串,则默认事件名称字段匹配成功。 | **表4** HiSysEventQueryCallback查询回调对象 | 接口名称 | 描述 | | -------- | -------- | -| void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) | 接口功能:事件查询的回调。
输入参数:
- sysEvents:返回的事件集合。
返回值:
无。 | -| void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | 接口功能:事件查询完成的回调。
输入参数:
- reason:查询结束返回原因,目前默认是0。
- total:本次查询总共返回的事件总数量。
返回值:
无。 | +| void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) | 接口功能:事件查询的回调。
输入参数:
- sysEvents:返回的事件集合。 | +| void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | 接口功能:事件查询完成的回调。
输入参数:
- reason:查询结束的返回原因,0表示查询正常结束,其他值表示查询异常结束。
- total:本次查询返回的事件的总数量。 | -### 开发实例 +#### C接口说明 -C++接口实例。 +C HiSysEvent查询开发能力如下:具体API详见接口目录(/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/)。 -1. 源代码开发: - 引入对应的头文件: + **表5** HiSysEvent查询接口 - ``` +| 接口名称 | 描述 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | 接口功能:支持根据时间段、事件领域、事件名称、事件参数等条件,查询满足条件的HiSysEvent事件。
输入参数:
- arg:查询参数。
- rules:事件过滤规则。
- ruleSize:事件过滤规则数量。
- callback:查询接口回调。
返回值:
- 0:查询成功。
- 负值:查询失败。 | + + **表6** HiSysEventQueryArg查询参数结构体 + +| 属性名称 | 属性类型 | 描述 | +| --------- | -------- | ---------------------------------------------------- | +| beginTime | int64_t | 用于指定查询事件的开始时间,格式为Unix毫秒级时间戳。 | +| endTime | int64_t | 用于指定查询事件的结束时间,格式为Unix毫秒级时间戳。 | +| maxEvents | int32_t | 用于指定查询返回事件的最多条数。 | + +**表7** HiSysEventQueryRule查询规则结构体 + +| 属性名称 | 属性类型 | 描述 | +| ------------- | --------- | ---------------------------------- | +| domain | char[] | 用来指定查询的事件领域。 | +| eventList | char\[][] | 用于指定查询的事件名称列表。 | +| eventListSize | size_t | 用于指定查询的事件名称列表大小。 | +| condition | char* | 用于指定查询的自定义事件参数条件。 | + +对于condition参数需要按照指定的JSON字符串格式传入,使用实例如下: + +```json +{ + "version":"V1", + "condition":{ + "and":[ + {"param":"type_","op":">","value":0}, + {"param":"uid_","op":"=","value":1201} + ], + "or":[ + {"param":"NAME","op":"=","value":"SysEventService"}, + {"param":"NAME","op":"=","value":"SysEventSource"} + ] + } +} +``` + +- version字段是必选字段,表示传入条件的支持版本,当前只支持V1版本。 +- condition字段是必选字段,表示传入条件的具体内容。 + - and字段是可选字段,表示条件之间是与的关系。 + - or字段是可选字段,表示条件之间是或的关系。 + - param字段是必选字段,表示条件匹配的参数名称,必须为字符串类型。 + - op字段是必选字段,表示条件匹配的参数比较符,必须为字符串类型,支持的比较符包括=、>、<、>=、<=。 + - value字段是必选字段,表示条件匹配的参数值,必须为字符串类型或整型。 + +**表8** HiSysEventQueryCallback查询回调结构体 + +| 属性名称 | 属性类型 | 描述 | +| ---------- | -------------------------------------------------- | ------------------------------------------------------------ | +| OnQuery | void (*)(HiSysEventRecord records[], size_t size); | 接口功能:事件查询的回调。
输入参数:
- records:返回的事件集合。
- size:返回的事件集合大小。 | +| OnComplete | void (*)(int32_t reason, int32_t total); | 接口功能:事件查询完成的回调。
输入参数:
- reason:查询结束的返回原因,0表示查询正常结束,其他值表示查询异常结束。
- total:本次查询返回的事件的总数量。 | + +**表9** HiSysEventRecord事件结构体 + +| 属性名称 | 属性类型 | 描述 | +| --------- | ------------------- | -------------------------- | +| domain | char[] | 事件的领域名称。 | +| eventName | char\[] | 事件的名称。 | +| type | HiSysEventEventType | 事件的类型。 | +| time | uint64_t | 事件的时间戳。 | +| tz | char\[] | 事件的时区。 | +| pid | int64_t | 事件的进程ID。 | +| tid | int64_t | 事件的线程ID。 | +| uid | int64_t | 事件的用户ID。 | +| traceId | uint64_t | 事件的分布式跟踪链ID。 | +| spandId | uint64_t | 事件的分布式跟踪分支ID。 | +| pspanId | uint64_t | 事件的分布式跟踪父分支ID。 | +| traceFlag | int | 事件的分布式跟踪标志位。 | +| level | char* | 事件的级别。 | +| tag | char* | 事件的标签。 | +| jsonStr | char* | 事件的内容。 | + +**表10** HiSysEventRecord解析接口 + +| 接口名称 | | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| void OH_HiSysEvent_GetParamNames(const HiSysEventRecord& record, char*** params, size_t& len); | 接口功能:获取该事件的所有的参数名。
输入参数:
- record:事件结构体。
- params:参数名数组。
- len:数组大小。 | +| int OH_HiSysEvent_GetParamInt64Value(const HiSysEventRecord& record, const char* name, int64_t& value); | 接口功能:将该事件中参数名为name的参数值,解析为int64_t类型并赋值到value。
输入参数:
- record:事件结构体。
- name:参数名。
- value:int64_t类型的参数值。 | +| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | 接口功能:将该事件中参数名为name的参数值,解析为uint64_t类型并赋值到value。
输入参数:
- record:事件结构体。
- name:参数名。
- value:uint64_t类型的参数值。 | +| int OH_HiSysEvent_GetParamDoubleValue(const HiSysEventRecord& record, const char* name, double& value); | 接口功能:将该事件中参数名为name的参数值,解析为double类型并赋值到value。
输入参数:
- record:事件结构体。
- name:参数名。
- value:double类型的参数值。 | +| int OH_HiSysEvent_GetParamStringValue(const HiSysEventRecord& record, const char* name, char** value); | 接口功能:将该事件中参数名为name的参数值,解析为char数组类型并赋值到value,value在使用完成后需要手动释放内存。
输入参数:
- record:事件结构体。
- name:参数名。
- value:char\*类型引用。 | +| int OH_HiSysEvent_GetParamInt64Values(const HiSysEventRecord& record, const char* name, int64_t** value, size_t& len); | 接口功能:将该事件中参数名为name的参数值,解析为int64_t数组类型并赋值到value,value在使用完成后需要手动释放内存。
输入参数:
- record:事件结构体。
- name:参数名。
- value:int64_t\*类型引用。
- len:数组大小。 | +| int OH_HiSysEvent_GetParamUint64Values(const HiSysEventRecord& record, const char* name, uint64_t** value, size_t& len); | 接口功能:将该事件中参数名为name的参数值,解析为uint64_t数组类型并赋值到value,value在使用完成后需要手动释放内存。
输入参数:
- record:事件结构体。
- name:参数名。
- value:uint64_t\*类型引用。
- len:数组大小。 | +| int OH_HiSysEvent_GetParamDoubleValues(const HiSysEventRecord& record, const char* name, double** value, size_t& len); | 接口功能:将该事件中参数名为name的参数值,解析为double数组类型并赋值到value,value在使用完成后需要手动释放内存。
输入参数:
- record:事件结构体。
- name:参数名。
- value:double\*类型引用。
- len:数组大小。 | +| int OH_HiSysEvent_GetParamStringValues(const HiSysEventRecord& record, const char* name, char*** value, size_t& len); | 接口功能:将该事件中参数名为name的参数值,解析为char*数组类型并赋值到value,value在使用完成后需要手动释放内存。
输入参数:
- record:事件结构体。
- name:参数名。
- value:char\*\*类型引用。
- len:数组大小。 | + +HiSysEventRecord解析接口的返回值说明如下: + +- 0,表示解析成功; +- -1,表示该事件初始化失败; +- -2,表示参数名不存在; +- -3,表示要解析的参数值类型与传入的参数值类型不匹配。 + +### 开发步骤 + +#### C++ HiSysEvent查询开发步骤 + +1. 首先,需要引入对应的头文件。 + + ```c++ #include "hisysevent_manager.h" ``` - 实现对应的查询回调接口: +2. 然后,业务领域需要实现对应的查询回调接口。 - ``` - void HiSysEventQueryCallback::OnQuery(std::shared_ptr> sysEvents) - void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) + ```c++ + class TestQueryCallback : public HiSysEventQueryCallback { + public: + void OnQuery(std::shared_ptr> sysEvents) override + { + if (sysEvents == nullptr) { + return; + } + for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { + std::cout << event.AsJson() << std::endl; + }); + } + + void OnComplete(int32_t reason, int32_t total) override + { + std::cout << "Query completed" << std::endl; + return; + } + }; ``` - 在相应的业务逻辑里面调用查询接口: +3. 最后,在需要查询的地方调用查询接口,并传入相应的查询参数、查询规则、查询回调参数。 + ```c++ + // 创建查询参数对象 + long long startTime = 0; + long long endTime = 1668245644000; //2022-11-12 09:34:04 + int queryCount = 10; + QueryArg arg(startTime, endTime, queryCount); + + // 创建查询规则对象 + QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" }); + std::vector queryRules = { rule }; + + // 创建查询回调对象 + auto queryCallback = std::make_shared(); + + // 调用查询接口 + HiSysEventManager::Query(arg, queryRules, queryCallback); ``` - HiSysEventManager::Query(struct QueryArg& queryArg, - std::vector& queryRules, std::shared_ptr queryCallBack) - ``` - 以下是查询所有系统事件的应用例子: +#### C HiSysEvent查询开发步骤 + +1. 首先,需要引入对应的头文件。 + ```c++ + #include "hisysevent_manager_c.h" ``` - #include "hisysevent_manager.h" - #include - namespace OHOS { - namespace HiviewDFX { - // 实现查询回调的接口 - void HiSysEventToolQuery::OnQuery(std::shared_ptr> sysEvents) +2. 然后,业务领域需要实现对应的查询回调接口。 + + ```c++ + void OnQueryTest(HiSysEventRecord records[], size_t size) { - if (sysEvents == nullptr) { - return; + for (size_t i = 0; i < size; i++) { + printf("OnQuery: event=%s", records[i].jsonStr); } - for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { - std::cout << event.AsJson() << std::endl; - }); } - - void HiSysEventToolQuery::OnComplete(int32_t reason, int32_t total) + + void OnCompleteTest(int32_t reason, int32_t total) { - return; + printf("OnCompleted, res=%d, total=%d\n", reason, total); } - } // namespace HiviewDFX - } // namespace OHOS - - // 调用查询接口获取HiSysEvent事件 - auto queryCallBack = std::make_shared(); - struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents); - std::vector rules; - HiSysEventManager::QueryHiSysEvent(args, rules, queryCallBack); ``` -2. 编译设置: - 在BUILD.gn编译文件中,需要添加依赖hisysevent_native部件的libhisysevent及libhisyseventmanager库。 - +3. 最后,在需要查询的地方调用查询接口,并传入相应的查询参数、查询规则、查询回调参数。 + + ```c++ + // 创建查询参数对象 + HiSysEventQueryArg arg; + arg.beginTime = 0; + arg.endTime = 1668245644000; //2022-11-12 09:34:04 + arg.maxEvents = 10; + + // 创建查询规则对象 + constexpr char TEST_DOMAIN[] = "HIVIEWDFX"; + constexpr char TEST_NAME[] = "PLUGIN_LOAD"; + HiSysEventQueryRule rule; + (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); + (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); + rule.eventListSize = 1; + rule.condition = nullptr; + HiSysEventQueryRule rules[] = { rule }; + + // 创建查询回调对象 + HiSysEventQueryCallback callback; + callback.OnQuery = OnQueryTest; + callback.OnComplete = OnCompleteTest; + + // 调用查询接口 + OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback); ``` + +### 开发实例 + +#### C++ HiSysEvent查询开发实例 + +假设业务模块需要查询截止至当前时间、事件领域为HIVIEWDFX、事件名称为PLUGIN_LOAD的所有事件,其完整使用示例如下所示: + +1. 首先,需要在业务模块的在BUILD.gn里增加hisysevent_native部件的libhisysevent及libhisyseventmanager依赖。 + + ```c++ external_deps = [ "hisysevent_native:libhisysevent", "hisysevent_native:libhisyseventmanager", ] ``` +2. 在业务模块的TestQuery()函数中,调用查询接口去查询事件。 + + ```c++ + #include "hisysevent_manager.h" + #include + #include + + using namespace OHOS::HiviewDFX; + + class TestQueryCallback : public HiSysEventQueryCallback { + public: + void OnQuery(std::shared_ptr> sysEvents) override + { + if (sysEvents == nullptr) { + return; + } + for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) { + std::cout << event.AsJson() << std::endl; + }); + } + + void OnComplete(int32_t reason, int32_t total) override + { + std::cout << "Query completed" << std::endl; + return; + } + }; + + int64_t GetMilliseconds() + { + auto now = std::chrono::system_clock::now(); + auto millisecs = std::chrono::duration_cast(now.time_since_epoch()); + return millisecs.count(); + } + + void TestQuery() + { + // 创建查询参数对象 + long long startTime = 0; + long long endTime = GetMilliseconds(); + int maxEvents = 100; + QueryArg arg(startTime, endTime, maxEvents); + + // 创建查询规则对象 + QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" }); + std::vector queryRules = { rule }; + + // 创建查询回调对象 + auto queryCallback = std::make_shared(); + + // 调用查询接口 + int ret = HiSysEventManager::Query(arg, queryRules, queryCallback); + } + ``` + +#### C HiSysEvent查询开发实例 + +假设业务模块需要查询截止至当前时间、事件领域为HIVIEWDFX、事件名称为PLUGIN_LOAD的所有事件,其完整使用示例如下所示: + +1. 首先,需要在业务模块的在BUILD.gn里增加hisysevent_native部件的libhisyseventmanager依赖。 + + ```c++ + external_deps = [ "hisysevent_native:libhisyseventmanager" ] + + // for strcpy_s + deps = [ "//third_party/bounds_checking_function:libsec_shared" ] + ``` + +2. 在业务模块的TestQuery()函数中,调用查询接口去查询事件。 + + ```c++ + #include "hisysevent_manager_c.h" + #include + #include + + void OnQueryTest(HiSysEventRecord records[], size_t size) + { + for (size_t i = 0; i < size; i++) { + printf("OnQuery: event=%s", records[i].jsonStr); + } + } + + void OnCompleteTest(int32_t reason, int32_t total) + { + printf("OnCompleted, res=%d, total=%d\n", reason, total); + } + + int64_t GetMilliseconds() + { + return time(NULL); + } + + void TestQuery() + { + // 创建查询参数对象 + HiSysEventQueryArg arg; + arg.beginTime = 0; + arg.endTime = GetMilliseconds(); + arg.maxEvents = 100; + + // 创建查询规则对象 + constexpr char TEST_DOMAIN[] = "HIVIEWDFX"; + constexpr char TEST_NAME[] = "PLUGIN_LOAD"; + HiSysEventQueryRule rule; + (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN); + (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME); + rule.eventListSize = 1; + rule.condition = nullptr; + HiSysEventQueryRule rules[] = { rule }; + + // 创建查询回调对象 + HiSysEventQueryCallback callback; + callback.OnQuery = OnQueryTest; + callback.OnComplete = OnCompleteTest; + + // 调用查询接口 + int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback); + } + ``` diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index 331435b5f81ec543bba4016d032cebad71894e39..d0dc921dad971457087241c77ff4e71ba34b256d 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -83,6 +83,31 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 当同时通过-t、-o及-n指定了相关订阅规则参数设置,则判断设置的事件标签是否为空,若不为空,则使用事件标签规则进行订阅,否则使用事件领域及事件名称订阅规则进行订阅。 +- 通过事件类型的方式实时订阅HiSysEvent事件: + + ``` + hisysevent -r -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -g | 设置实时订阅的HiSysEvent事件类型,用来过滤订阅的HiSysEvent事件,有“FAULT”、“STATISTIC”、“SECURITY”及“BEHAVIOR”四种事件类型。 | + + 命令实例: + + ``` + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "POWER\w{0,8}" -n "POWER_RUNNINGLOCK" -c REGULAR -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -r -o "ACCOU\w+" -c REGULAR -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -r -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` + ## 查询历史HiSysEvent事件相关命令 @@ -139,6 +164,56 @@ {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501964222980,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201702","HAPPEN_TIME":1501964222980,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"10435592800188571430","info_":""} ``` +- 通过事件领域及事件名称的方式查询历史HiSysEvent事件: + + ``` + hisysevent -l -o -n [-c WHOLE_WORD] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -o | 设置查询历史HiSysEvent事件领域,用来过滤查询的HiSysEvent事件。 | + | -n | 设置查询历史HiSysEvent事件名称,用来过滤查询的HiSysEvent事件。 | + | -c | 设置查询历史HiSysEvent事件领域及事件名称的匹配规则,查询只支持“WHOLE_WORD”匹配规则。 | + + 命令实例: + + ``` + # hisysevent -l -n "APP_FREEZE" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -r -o "RELIABILITY" + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201544","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"13456525196455104060","info_":""} + # hisysevent -r -o "RELIABILITY" -n "APP_FREEZE" -c WHOLE_WORD + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201633","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"12675246910904037271","info_":""} + ``` + +- 通过事件类型的方式查询历史HiSysEvent事件: + + ``` + hisysevent -l -g [FAULT|STATISTIC|SECURITY|BEHAVIOR] + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | -------- | + | -g | 设置查询历史HiSysEvent事件类型,用来过滤查询的HiSysEvent事件,有“FAULT”、“STATISTIC”、“SECURITY”及“BEHAVIOR”四种事件类型。 | + + 命令实例: + + ``` + # hisysevent -l -o "RELIABILITY" -g FAULT + {"domain_":"RELIABILITY","name_":"APP_FREEZE","type_":1,"time_":1501963989773,"pid_":1505,"uid_":10002,"FAULT_TYPE":"4","MODULE":"com.ohos.screenlock","REASON":"NO_DRAW","SUMMARY":"SUMMARY:\n","LOG_PATH":"/data/log/faultlog/faultlogger/appfreeze-com.ohos.screenlock-10002-20170805201309","HAPPEN_TIME":1501963989773,"VERSION":"1.0.0","level_":"CRITICAL","tag_":"STABILITY","id_":"16367997008075110557","info_":""} + # hisysevent -l -n "POWER_RUNNINGLOCK" -c WHOLE_WORD -g STATISTIC + {"domain_":"POWER","name_":"POWER_RUNNINGLOCK","type_":2,"time_":1667485283785,"tz_":"+0000","pid_":538,"tid_":684,"uid_":5523,"PID":360,"UID":1001,"STATE":0,"TYPE":1,"NAME":"telRilRequestRunningLock","LOG_LEVEL":2,"TAG":"DUBAI_TAG_RUNNINGLOCK_REMOVE","MESSAGE":"token=25956496","level_":"MINOR","tag_":"PowerStats","id_":"11994072552538324655","info_":""} + # hisysevent -l -g SECURITY + {"domain_":"ACCOUNT","name_":"PERMISSION_EXCEPTION","type_":3,"time_":1667484405993,"tz_":"+0000","pid_":614,"tid_":614,"uid_":3058,"CALLER_UID":1024,"CALLER_PID":523,"PERMISSION_NAME":"ohos.permission.MANAGE_LOCAL_ACCOUNTS","level_":"CRITICAL","tag_":"security","id_":"15077995598140341422","info_":""} + # hisysevent -l -o MULTIMODALINPUT -g BEHAVIOR + {"domain_":"MULTIMODALINPUT","name_":"Z_ORDER_WINDOW_CHANGE","type_":4,"time_":1667549852735,"tz_":"+0000","pid_":2577,"tid_":2588,"uid_":6696,"OLD_ZORDER_FIRST_WINDOWID":-1,"NEW_ZORDER_FIRST_WINDOWID":2,"OLD_ZORDER_FIRST_WINDOWPID":-1,"NEW_ZORDER_FIRST_WINDOWPID":1458,"MSG":"The ZorderFirstWindow changing succeeded","level_":"MINOR","tag_":"PowerStats","id_":"16847308118559691400","info_":""} + ``` + ## 系统事件合法性校验模式 - 打开系统事件合法性校验模式 diff --git a/zh-cn/device-dev/subsystems/subsys-testguide-test.md b/zh-cn/device-dev/subsystems/subsys-testguide-test.md deleted file mode 100644 index 8077908ac54c057971c53c8ff3535682d407f2f0..0000000000000000000000000000000000000000 --- a/zh-cn/device-dev/subsystems/subsys-testguide-test.md +++ /dev/null @@ -1,949 +0,0 @@ -# 测试子系统 -OpenHarmony为开发者提供了一套全面的自测试框架,开发者可根据测试需求开发相关测试用例,开发阶段提前发现缺陷,大幅提高代码质量。 - -本文从基础环境构建,用例开发,编译以及执行等方面介绍OpenHarmony测试框架如何运行和使用。 -## 基础环境构建 -- 测试框架依赖于python运行环境,在使用测试框架之前可参阅以下方式进行配置。 -- 获取源码的方式请参考[源码获取](../get-code/sourcecode-acquire.md)。 -### 环境配置 -#### 测试框架基础环境依赖 - -|环境依赖|操作系统|Linux系统扩展组件|python|python插件|NFS Server|HDC| -|------------|------------|------------|------------|------------|------------|------------| -|版本型号|Ubuntu18.04及以上|libreadline-dev|3.7.5版本及以上|pyserial 3.3及以上、paramiko2.7.1及以上、setuptools40.8.0及以上、rsa4.0及以上|haneWIN NFS Server 1.2.50及以上或者 NFS v4及以上| 1.1.0版本及以上 | -|详细说明|代码编译环境|命令行读取插件|测试框架语言 |pyserial:支持python的串口通信;paramiko:支持python使用SSH协议;setuptools:支持python方便创建和分发python包;rsa:支持python rsa加密 |支持设备通过串口连接| 支持设备通过HDC连接 | - -#### 安装流程 -1. 安装Linux扩展组件readline,安装命令如下: - ``` - sudo apt-get install libreadline-dev - ``` - 安装成功提示如下: - ``` - Reading package lists... Done - Building dependency tree - Reading state information... Done - libreadline-dev is already the newest version (7.0-3). - 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. - ``` -2. 安装setuptools插件,安装命令如下: - ``` - pip3 install setuptools - ``` - 安装成功提示如下: - ``` - Requirement already satisfied: setuptools in d:\programs\python37\lib\site-packages (41.2.0) - ``` -3. 安装paramiko插件,安装命令如下: - ``` - pip3 install paramiko - ``` - 安装成功提示如下: - ``` - Installing collected packages: pycparser, cffi, pynacl, bcrypt, cryptography, paramiko - Successfully installed bcrypt-3.2.0 cffi-1.14.4 cryptography-3.3.1 paramiko-2.7.2 pycparser-2.20 pynacl-1.4.0 - ``` -4. 安装python的rsa插件,安装命令如下: - ``` - pip3 install rsa - ``` - 安装成功提示如下: - ``` - Installing collected packages: pyasn1, rsa - Successfully installed pyasn1-0.4.8 rsa-4.7 - ``` -5. 安装串口插件pyserial,安装命令如下: - ``` - pip3 install pyserial - ``` - 安装成功提示如下: - ``` - Requirement already satisfied: pyserial in d:\programs\python37\lib\site-packages\pyserial-3.4-py3.7.egg (3.4) - ``` -6. 如果设备仅支持串口输出测试结果,则需要安装NFS Server - - Windows环境下安装,例如安装haneWIN NFS Server1.2.50。 - - Linux环境下安装,安装命令如下: - ``` - sudo apt install nfs-kernel-server - ``` - 安装成功提示如下: - ``` - Reading package lists... Done - Building dependency tree - Reading state information... Done - nfs-kernel-server is already the newest version (1:1.3.4-2.1ubuntu5.3). - 0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded. - ``` -7. 如果设备支持HDC连接,则需要安装HDC工具,安装流程请参考如下链接 - - https://gitee.com/openharmony/developtools_hdc_standard/blob/master/README_zh.md - -## 安装环境检查 - -| 检查项 |操作 |满足环境 | -| --- | --- | --- | -| 检查python安装成功 |命令行窗口执行命令:python --version |版本不小于3.7.5即可 | -| 检查python扩展插件安装成功 |打开test/developertest目录,执行start.bat或start.sh| 可进入提示符“>>>”界面即可 | -|检查NFS Server启动状态(被测设备仅支持串口时检测) |通过串口登录开发板,执行mount命令挂载NFS |可正常挂载文件目录即可 | -|检查HDC安装成功 |命令行窗口执行命令:hdc_std -v |版本不小于1.1.0即可 | - - - -## 测试框架目录简介 -以下是测试框架的目录层级架构,在使用测试框架过程中可在相应目录查找对应组件。 -``` -test # 测试子系统 -├── developertest # 开发者测试组件 -│ ├── aw # 测试框架的静态库 -│ ├── config # 测试框架配置 -│ │ │ ... -│ │ └── user_config.xml # 用户使用配置 -│ ├── examples # 测试用例示例 -│ ├── src # 测试框架源码 -│ ├── third_party # 测试框架依赖第三方组件适配 -│ ├── reports # 测试结果报告 -│ ├── BUILD.gn # 测试框架编译入口 -│ ├── start.bat # 开发者测试入口(Windows) -│ └── start.sh # 开发者测试入口(Linux) -└── xdevice # 测试框架依赖组件 -``` -## 测试用例编写 -### 测试用例目录规划 -使用测试框架过程中,可根据以下层级关系规划测试用例目录。 -``` -subsystem # 子系统 -├── partA # 部件A -│ ├── moduleA # 模块A -│ │ ├── include -│ │ ├── src # 业务代码 -│ │ └── test # 测试目录 -│ │ ├── unittest # 单元测试 -│ │ │ ├── common # 公共用例 -│ │ │ │ ├── BUILD.gn # 测试用例编译配置 -│ │ │ │ └── testA_test.cpp # 单元测试用例源码 -│ │ │ ├── phone # 手机形态用例 -│ │ │ ├── ivi # 车机形态用例 -│ │ │ └── liteos-a # ipcamera使用liteos内核的用例 -│ │ ├── moduletest # 模块测试 -│ │ ... -│ │ -│ ├── moduleB # 模块B -│ ├── test -│ │ └── resource # 依赖资源 -│ │ ├── moduleA # 模块A -│ │ │ ├── ohos_test.xml # 资源配置文件 -│ │ ... └── 1.txt # 资源 -│ │ -│ ├── ohos_build # 编译入口配置 -│ ... -│ -... -``` -> **注意:** 测试用例根据不同设备形态差异分为通用用例和非通用用例,建议将通用用例存放在common目录下,非通用用例存放在相应设备形态目录下。 - -### 测试用例编写 -本测试框架支持多种语言用例编写,针对不同语言提供了不同的模板以供编写参考。 - -**C++参考示例** - -- 用例源文件命名规范 - - 测试用例源文件名称和测试套内容保持一致,文件命名采用全小写+下划线方式命名,以test结尾,具体格式为:[功能]_[子功能]_test,子功能支持向下细分。 -示例: - ``` - calculator_sub_test.cpp - ``` - -- 用例示例 - ``` - /* - * Copyright (c) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #include "calculator.h" - #include - - using namespace testing::ext; - - class CalculatorSubTest : public testing::Test { - public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - }; - - void CalculatorSubTest::SetUpTestCase(void) - { - // input testsuit setup step,setup invoked before all testcases - } - - void CalculatorSubTest::TearDownTestCase(void) - { - // input testsuit teardown step,teardown invoked after all testcases - } - - void CalculatorSubTest::SetUp(void) - { - // input testcase setup step,setup invoked before each testcases - } - - void CalculatorSubTest::TearDown(void) - { - // input testcase teardown step,teardown invoked after each testcases - } - - /** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: Issue Number - */ - HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) - { - // step 1:调用函数获取结果 - int actual = Sub(4,0); - - // Step 2:使用断言比较预期与实际结果 - EXPECT_EQ(4, actual); - } - ``` - 详细内容介绍: - 1. 添加测试用例文件头注释信息 - ``` - /* - * Copyright (c) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - ``` - 2. 引用测试框架头文件和命名空间 - ``` - #include - - using namespace testing::ext; - ``` - 3. 添加被测试类的头文件 - ``` - #include "calculator.h" - ``` - 4. 定义测试套(测试类) - ``` - class CalculatorSubTest : public testing::Test { - public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); - }; - - void CalculatorSubTest::SetUpTestCase(void) - { - // input testsuit setup step,setup invoked before all testcases - } - - void CalculatorSubTest::TearDownTestCase(void) - { - // input testsuit teardown step,teardown invoked after all testcases - } - - void CalculatorSubTest::SetUp(void) - { - // input testcase setup step,setup invoked before each testcases - } - - void CalculatorSubTest::TearDown(void) - { - // input testcase teardown step,teardown invoked after each testcases - } - ``` - > **注意:** 在定义测试套时,测试套名称应与编译目标保持一致,采用大驼峰风格。 - - 5. 测试用例实现,包含用例注释和逻辑实现 - ``` - /** - * @tc.name: integer_sub_001 - * @tc.desc: Verify the sub function. - * @tc.type: FUNC - * @tc.require: Issue Number - */ - HWTEST_F(CalculatorSubTest, integer_sub_001, TestSize.Level1) - { - //step 1:调用函数获取结果 - int actual = Sub(4,0); - - //Step 2:使用断言比较预期与实际结果 - EXPECT_EQ(4, actual); - } - ``` - 在编写用例时,我们提供了三种用例模板供您选择。 - - | 类型 | 描述 | - | ------------| ------------| - | HWTEST(A,B,C)| 用例执行不依赖Setup&Teardown时,可选取| - | HWTEST_F(A,B,C)| 用例执行(不含参数)依赖于Setup&Teardown时,可选取| - | HWTEST_P(A,B,C)| 用例执行(含参数)依赖于Set&Teardown时,可选取| - - 其中,参数A,B,C的含义如下: - - 参数A为测试套名。 - - 参数B为测试用例名,其命名必须遵循[功能点]_[编号]的格式,编号为3位数字,从001开始。 - - 参数C为测试用例等级,具体分为门禁level0 以及非门禁level1-level4共五个等级,其中非门禁level1-level4等级的具体选取规则为:测试用例功能越重要,level等级越低。 - - **注意:** - - 测试用例的预期结果必须有对应的断言。 - - 测试用例必须填写用例等级。 - - 测试体建议按照模板分步实现。 - - 用例描述信息按照标准格式@tc.xxx value书写,注释信息必须包含用例名称,用例描述,用例类型,需求编号四项。其中用例测试类型@tc.type参数的选取,可参考下表。 - - | 测试类型名称|类型编码| - | ------------|------------| - |功能测试 |FUNC| - |性能测试 |PERF| - |可靠性测试 |RELI| - |安全测试 |SECU| - |模糊测试 |FUZZ| - - -**JavaScript参考示例** - -- 用例源文件命名规范 - - 测试用例原文件名称采用大驼峰风格,以TEST结尾,具体格式为:[功能][子功能]TEST,子功能支持向下细分。 -示例: - ``` - AppInfoTest.js - ``` - -- 用例示例 - ``` - /* - * Copyright (C) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - import app from '@system.app' - - import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - - describe("AppInfoTest", function () { - beforeAll(function() { - // input testsuit setup step,setup invoked before all testcases - console.info('beforeAll called') - }) - - afterAll(function() { - // input testsuit teardown step,teardown invoked after all testcases - console.info('afterAll called') - }) - - beforeEach(function() { - // input testcase setup step,setup invoked before each testcases - console.info('beforeEach called') - }) - - afterEach(function() { - // input testcase teardown step,teardown invoked after each testcases - console.info('afterEach called') - }) - - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - */ - it("appInfoTest001", 0, function () { - //step 1:调用函数获取结果 - var info = app.getInfo() - - //Step 2:使用断言比较预期与实际结果 - expect(info != null).assertEqual(true) - }) - }) - ``` - 详细内容介绍: - 1. 添加测试用例文件头注释信息 - ``` - /* - * Copyright (C) 2022 XXXX Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - ``` - 2. 导入被测api和jsunit测试库 - ``` - import app from '@system.app' - - import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' - ``` - 3. 定义测试套(测试类) - ``` - describe("AppInfoTest", function () { - beforeAll(function() { - // input testsuit setup step,setup invoked before all testcases - console.info('beforeAll called') - }) - - afterAll(function() { - // input testsuit teardown step,teardown invoked after all testcases - console.info('afterAll called') - }) - - beforeEach(function() { - // input testcase setup step,setup invoked before each testcases - console.info('beforeEach called') - }) - - afterEach(function() { - // input testcase teardown step,teardown invoked after each testcases - console.info('afterEach called') - }) - ``` - 4. 测试用例实现 - ``` - /* - * @tc.name:appInfoTest001 - * @tc.desc:verify app info is not null - * @tc.type: FUNC - * @tc.require: Issue Number - */ - it("appInfoTest001", 0, function () { - //step 1:调用函数获取结果 - var info = app.getInfo() - - //Step 2:使用断言比较预期与实际结果 - expect(info != null).assertEqual(true) - }) - ``` - -### 测试用例编译文件编写 -根据测试用例目录规划,当执行某一用例时,测试框架会根据编译文件逐层查找,最终找到所需用例进行编译。下面通过不同示例来讲解gn文件如何编写。 - -#### 测试用例编译配置文件 -针对不同语言,下面提供不同的编译模板以供参考。 - -- **C++用例编译配置示例** - ``` - # Copyright (c) 2022 XXXX Device Co., Ltd. - - import("//build/test.gni") - - module_output_path = "subsystem_examples/calculator" - - config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ "../../../include" ] - } - - ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path - - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - ] - - sources += [ "calculator_sub_test.cpp" ] - - configs = [ ":module_private_config" ] - - deps = [ "//third_party/googletest:gtest_main" ] - } - - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` - 详细内容如下: - - 1. 添加文件头注释信息 - ``` - # Copyright (c) 2022 XXXX Device Co., Ltd. - ``` - 2. 导入编译模板文件 - ``` - import("//build/test.gni") - ``` - 3. 指定文件输出路径 - ``` - module_output_path = "subsystem_examples/calculator" - ``` - > **说明:** 此处输出路径为部件/模块名。 - - 4. 配置依赖包含目录 - - ``` - config("module_private_config") { - visibility = [ ":*" ] - - include_dirs = [ "../../../include" ] - } - ``` - > **说明:** 一般在此处对相关配置进行设置,在测试用例编译脚本中可直接引用。 - - 5. 指定测试用例编译目标输出的文件名称 - - ``` - ohos_unittest("CalculatorSubTest") { - } - ``` - 6. 编写具体的测试用例编译脚本(添加需要参与编译的源文件、配置和依赖) - ``` - ohos_unittest("CalculatorSubTest") { - module_out_path = module_output_path - sources = [ - "../../../include/calculator.h", - "../../../src/calculator.cpp", - "../../../test/calculator_sub_test.cpp" - ] - sources += [ "calculator_sub_test.cpp" ] - configs = [ ":module_private_config" ] - deps = [ "//third_party/googletest:gtest_main" ] - } - ``` - - > **说明:根据测试类型的不同,在具体编写过程中可选择不同的测试类型:** - > - ohos_unittest:单元测试 - > - ohos_moduletest:模块测试 - > - ohos_systemtest:系统测试 - > - ohos_performancetest:性能测试 - > - ohos_securitytest:安全测试 - > - ohos_reliabilitytest:可靠性测试 - > - ohos_distributedtest:分布式测试 - - 7. 对目标测试用例文件进行条件分组 - - ``` - group("unittest") { - testonly = true - deps = [":CalculatorSubTest"] - } - ``` - > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 - -- **JavaScript用例编译配置示例** - - ``` - # Copyright (C) 2022 XXXX Device Co., Ltd. - - import("//build/test.gni") - - module_output_path = "subsystem_examples/app_info" - - ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" - } - - group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] - } - ``` - - 详细内容如下: - - 1. 添加文件头注释信息 - - ``` - # Copyright (C) 2022 XXXX Device Co., Ltd. - ``` - 2. 导入编译模板文件 - - ``` - import("//build/test.gni") - ``` - 3. 指定文件输出路径 - - ``` - module_output_path = "subsystem_examples/app_info" - ``` - > **说明:** 此处输出路径为部件/模块名。 - - 4. 指定测试用例编译目标输出的文件名称 - - ``` - ohos_js_unittest("GetAppInfoJsTest") { - } - ``` - > **说明:** - >- 使用模板ohos_js_unittest定义js测试套,注意与C++用例区分。 - >- js测试套编译输出文件为hap类型,hap名为此处定义的测试套名,测试套名称必须以JsTest结尾。 - - 5. 指定hap包配置文件config.json和签名文件,两个配置为必选项 - - ``` - ohos_js_unittest("GetAppInfoJsTest") { - module_out_path = module_output_path - - hap_profile = "./config.json" - certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" - } - ``` - config.json为hap编译所需配置文件,需要开发者根据被测sdk版本配置“target”项,其余项可默认,具体如下所示: - - ``` - { - "app": { - "bundleName": "com.example.myapplication", - "vendor": "example", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 4, - "target": 5 // 根据被测sdk版本进行修改,此例为sdk5 - } - }, - "deviceConfig": {}, - "module": { - "package": "com.example.myapplication", - "name": ".MyApplication", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "entry", - "moduleType": "entry" - }, - "abilities": [ - { - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ], - "name": "com.example.myapplication.MainAbility", - "icon": "$media:icon", - "description": "$string:mainability_description", - "label": "MyApplication", - "type": "page", - "launchType": "standard" - } - ], - "js": [ - { - "pages": [ - "pages/index/index" - ], - "name": "default", - "window": { - "designWidth": 720, - "autoDesignWidth": false - } - } - ] - } - } - ``` - 6. 对目标测试用例文件进行条件分组 - ``` - group("unittest") { - testonly = true - deps = [ ":GetAppInfoJsTest" ] - } - ``` - > **说明:** 进行条件分组的目的在于执行用例时可以选择性的执行某一种特定类型的用例。 - -#### 编译入口配置文件ohos.build - -当完成用例编译配置文件编写后,需要进一步编写部件编译配置文件,以关联到具体的测试用例。 -``` -"partA": { - "module_list": [ - - ], - "inner_list": [ - - ], - "system_kits": [ - - ], - "test_list": [ - "//system/subsystem/partA/calculator/test:unittest" //配置模块calculator下的test - ] - } -``` -> **说明:** test_list中配置的是对应模块的测试用例。 - -### 测试用例资源配置 -测试依赖资源主要包括测试用例在执行过程中需要的图片文件,视频文件、第三方库等对外的文件资源。 - -依赖资源文件配置步骤如下: -1. 在部件的test目录下创建resource目录,在resource目录下创建对应的模块,在模块目录中存放该模块所需要的资源文件。 - -2. 在resource目录下对应的模块目录中创建一个ohos_test.xml文件,文件内容格式如下: - ``` - - - - - - - - ``` -3. 在测试用例的编译配置文件中定义resource_config_file进行指引,用来指定对应的资源文件ohos_test.xml。 - ``` - ohos_unittest("CalculatorSubTest") { - resource_config_file = "//system/subsystem/partA/test/resource/calculator/ohos_test.xml" - } - ``` - >**说明:** - >- target_name: 测试套的名称,定义在测试目录的BUILD.gn中。preparer: 表示该测试套执行前执行的动作。 - >- src="res": 表示测试资源位于test目录下的resource目录下,src="out":表示位于out/release/$(部件)目录下。 - -## 测试用例执行 -在执行测试用例之前,针对用例使用设备的不同,需要对相应配置进行修改,修改完成即可执行测试用例。 - -### user_config.xml配置 -``` - - - - false - - false - - true - - - - - - - - - - - - - cmd - 115200 - 8 - 1 - 1 - - - - - - - - - - - - - - - - - - -``` ->**说明:** 在执行测试用例之前,若使用HDC连接设备,用例仅需配置设备IP和端口号即可,其余信息均默认不修改。 - -### Windows环境执行 -#### 测试用例编译 - -由于Windows环境下无法实现用例编译,因此执行用例前需要在Linux环境下进行用例编译,用例编译命令: -``` -./build.sh --product-name hispark_taurus_standard --build-target make_test -``` ->说明: ->- product-name:指定编译产品名称,例如hispark_taurus_standard。 ->- build-target:指定所需要编译的用例,make_test表示指定全部用例,实际开发中可指定特定用例。 - -编译完成后,测试用例将自动保存在out/hispark_taurus/packages/phone/tests目录下。 - -#### 搭建执行环境 -1. 在Windows环境创建测试框架目录Test,并在此目录下创建testcase目录 - -2. 从Linux环境拷贝测试框架developertest和xdevice到创建的Test目录下,拷贝编译好的测试用例到testcase目录下 - >**说明:** 将测试框架及测试用例从Linux环境移植到Windows环境,以便后续执行。 - -3. 修改user_config.xml - ``` - - - false - - - - D:\Test\testcase\tests - - ``` - >**说明:** ``标签表示是否需要编译用例;``标签表示测试用例查找路径。 - -#### 执行用例 -1. 启动测试框架 - ``` - start.bat - ``` -2. 选择产品形态 - - 进入测试框架,系统会自动提示您选择产品形态,请根据实际的开发板进行选择。例如:Hi3516DV300。 - -3. 执行测试用例 - - 当选择完产品形态,可参考如下指令执行测试用例。 - ``` - run -t UT -ts CalculatorSubTest -tc integer_sub_00l - ``` - 执行命令参数说明: - ``` - -t [TESTTYPE]: 指定测试用例类型,有UT,MST,ST,PERF等。(必选参数) - -tp [TESTPART]: 指定部件,可独立使用。 - -tm [TESTMODULE]: 指定模块,不可独立使用,需结合-tp指定上级部件使用。 - -ts [TESTSUITE]: 指定测试套,可独立使用。 - -tc [TESTCASE]: 指定测试用例,不可独立使用,需结合-ts指定上级测试套使用。 - -h : 帮助命令。 - ``` -### Linux环境执行 -#### 远程端口映射 -为了在Linux远程服务器以及Linux虚拟机两种环境下执行测试用例,需要对端口进行远程映射,以实现与设备的数据通路连接。具体操作如下: -1. HDC Server指令: - ``` - hdc_std kill - hdc_std -m -s 0.0.0.0:8710 - ``` - >**说明:** IP和端口号为默认值。 - -2. HDC Client指令: - ``` - hdc_std -s xx.xx.xx.xx:8710 list targets - ``` - >**说明:** 此处IP填写设备侧IP地址。 - -#### 执行用例 -1. 启动测试框架 - ``` - ./start.sh - ``` -2. 选择产品形态 - - 进入测试框架,系统会自动提示您选择产品形态,请根据实际的开发板进行选择。例如:Hi3516DV300。 - -3. 执行测试用例 - - 测试框架在执行用例时会根据指令找到所需用例,自动实现用例编译,执行过程,完成自动化测试。 - ``` - run -t UT -ts CalculatorSubTest -tc integer_sub_00l - ``` - 执行命令参数说明: - ``` - -t [TESTTYPE]: 指定测试用例类型,有UT,MST,ST,PERF等。(必选参数) - -tp [TESTPART]: 指定部件,可独立使用。 - -tm [TESTMODULE]: 指定模块,不可独立使用,需结合-tp指定上级部件使用。 - -ts [TESTSUITE]: 指定测试套,可独立使用。 - -tc [TESTCASE]: 指定测试用例,不可独立使用,需结合-ts指定上级测试套使用。 - -h : 帮助命令。 - ``` - -## 测试报告日志 -当执行完测试指令,控制台会自动生成测试结果,若需要详细测试报告您可在相应的数据文档中进行查找。 - -### 测试结果 -测试结果输出根路径如下: -``` -test/developertest/reports/xxxx_xx_xx_xx_xx_xx -``` ->**说明:** 测试报告文件目录将自动生成。 - -该目录中包含以下几类结果: -| 类型 | 描述| -| ------------ | ------------ | -| result/ |测试用例格式化结果| -| log/plan_log_xxxx_xx_xx_xx_xx_xx.log | 测试用例日志 | -| summary_report.html | 测试报告汇总 | -| details_report.html | 测试报告详情 | - -### 测试框架日志 -``` -reports/platform_log_xxxx_xx_xx_xx_xx_xx.log -``` - -### 最新测试报告 -``` -reports/latest -``` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 181e52c7768c353051b8e2780a125d79a4dd9128..84d2960c20fa39e0820acd66d26d6afcb6090acf 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -60,8 +60,6 @@ - [Hi3516标准系统入门(命令行方式)](quick-start/quickstart-appendix-hi3516-pkg.md) - [获取源码](get-code/sourcecode-acquire.md) - - [隐私保护](security/security-privacy-protection.md) - - [安全指南](security/security-guidelines-overall.md) - 隐私和安全 - [隐私保护](security/security-privacy-protection.md) - [安全指南](security/security-guidelines-overall.md) @@ -155,6 +153,7 @@ - 子系统开发 - 内核 + - [内核概述](kernel/kernel-overview.md) - 轻量系统内核(LiteOS-M) - [轻量系统内核概述](kernel/kernel-mini-overview.md) - 基础内核 @@ -380,18 +379,18 @@ - [构建系统编码规范与最佳实践](subsystems/subsys-build-gn-coding-style-and-best-practice.md) - [编译构建Kconfig可视化配置指导](subsystems/subsys-build-gn-kconfig-visual-config-guide.md) - 编译构建参考 - - [子系统配置规则](subsystems/subsys-build-subsystem.md#子系统配置规则) - - [产品配置规则](subsystems/subsys-build-product.md#产品配置规则) - - [子系统配置规则](subsystems/subsys-build-subsystem.md#子系统配置规则) - - [部件配置规则](subsystems/subsys-build-component.md#部件配置规则) - - [模块配置规则](subsystems/subsys-build-module.md#模块配置规则) - - [芯片解决方案配置规则](subsystems/subsys-build-chip_solution.md#芯片解决方案配置规则) - - [特性配置规则](subsystems/subsys-build-feature.md#特性配置规则) - - [系统能力配置规则](subsystems/subsys-build-syscap.md#如何按需配置部件的系统能力) - - [关于deps、external_deps的使用](subsystems/subsys-build-reference.md#关于deps、external_deps的使用) - - [开源软件Notice收集策略说明](subsystems/subsys-build-reference.md#开源软件notice收集策略说明) - - [加快本地编译的一些参数](subsystems/subsys-build-reference.md#加快本地编译的一些参数) - - [查看NinjaTrace](subsystems/subsys-build-reference.md#查看ninjatrace) + - [子系统配置规则](subsystems/subsys-build-subsystem.md) + - [产品配置规则](subsystems/subsys-build-product.md) + - [子系统配置规则](subsystems/subsys-build-subsystem.md) + - [部件配置规则](subsystems/subsys-build-component.md) + - [模块配置规则](subsystems/subsys-build-module.md) + - [芯片解决方案配置规则](subsystems/subsys-build-chip_solution.md) + - [特性配置规则](subsystems/subsys-build-feature.md) + - [系统能力配置规则](subsystems/subsys-build-syscap.md) + - [关于deps、external_deps的使用](subsystems/subsys-build-reference.md) + - [开源软件Notice收集策略说明](subsystems/subsys-build-reference.md) + - [加快本地编译的一些参数](subsystems/subsys-build-reference.md) + - [查看NinjaTrace](subsystems/subsys-build-reference.md) - [HAP编译构建指导](subsystems/subsys-build-gn-hap-compilation-guide.md) - [常见问题](subsystems/subsys-build-FAQ.md) - [分布式远程启动](subsystems/subsys-remote-start.md) @@ -517,12 +516,13 @@ - 调测 - - [测试用例开发](subsystems/subsys-testguide-test.md) + - [developer_test开发者自测试执行框架使用指导](device-test/developer_test.md) + - [xdevice测试调度框架使用指导](device-test/xdevice.md) - 调测工具 - [bytrace使用指导](subsystems/subsys-toolchain-bytrace-guide.md) - [hdc\_std 使用指导](subsystems/subsys-toolchain-hdc-guide.md) - [hiperf 使用指南](subsystems/subsys-toolchain-hiperf.md) -- [XTS认证](subsystems/subsys-xts-guide.md) +- [XTS认证](device-test/xts.md) - 工具 - [Docker编译环境](get-code/gettools-acquire.md) - [IDE集成开发环境](get-code/gettools-ide.md) diff --git a/zh-cn/glossary.md b/zh-cn/glossary.md index f4598e5e23224dc24a35c485c5cf97a0cf5e2751..6b64d3dca5e379db12fa92249aecd00d21606d27 100644 --- a/zh-cn/glossary.md +++ b/zh-cn/glossary.md @@ -4,20 +4,35 @@ - ### Ability - 应用的重要组成部分,是应用所具备能力的抽象。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。 - + 应用的基本组成部分,是应用所具备能力的抽象。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件,一个应用可以包含一个或多个Ability。 在FA模型与Stage模型,分别定义了不同类型的Ability。 - ### AMS Ability Manager Service,Ability管理服务。 +- ### App Pack + + 上架应用市场的应用包的组织方式,包含一个或多个hap包,后缀名为.app。 + +- ### App Component + + 应用组件,每个Ability就是一个应用级组件。 + - ### ArkCompiler 方舟编译器,是OpenHarmony内置的组件化、可配置的多语言编译和运行平台,包含编译器、工具链、运行时等关键部件,支持高级语言在多种芯片平台的编译与运行,并支撑OpenHarmony标准操作系统及其应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。 +- ### ArkTS + + OpenHarmony生态的应用开发语言。它在TypeScript(简称 TS)的基础上,扩展了声明式UI、状态管理等能力,让开发者可以以更简洁、更自然的方式开发应用。 + - ### ArkUI - 方舟开发框架,是一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。详情可参考[方舟开发框架开发指导](application-dev/ui/arkui-overview.md)。 + OpenHarmony上原生UI框架。是一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。详情可参考[方舟开发框架开发指导](application-dev/ui/arkui-overview.md)。 + +- ### Atomic Service + + 原子化服务,OpenHarmony提供的一种全新应用形态。具有独立入口,用户可通过点击、碰一碰、扫一扫等方式直接触发,无需显示安装,由系统静默安装后即可使用,为用户提供便捷服务。 ## B @@ -26,9 +41,22 @@ Bundle Manager Service,包管理服务。 +## C + +- ### C API + + OpenHarmony SDK 提供的native开发接口。 + +- ### Continuation + + 流转,OpenHarmony系统提供的分布式操作,包括了跨端迁移和多端协同两种场景。 ## D +- ### Derivative Framework + + 衍生框架,指桥接到原生框架上的三方框架。 + - ### DevEco Device Tool 面向智能设备开发者,提供一站式的开发环境、一站式资源获取通道,实现了从芯片模板工程创建到开发资源挑选定制,再到编码、编译、调试、调优、烧录环节的全流程覆盖,帮助开发者实现智能硬件设备的高效开发。 @@ -37,7 +65,6 @@ Distributed Management Service,分布式管理服务。 - ## F - ### FA @@ -46,8 +73,7 @@ - ### FA模型 - Ability开发框架支持的开发模型中的一种。API Version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/ability/fa-brief.md)。 - + Ability框架提供的一种开发模型。API version 8及更早版本的应用开发仅支持FA模型。FA模型将Ability分为[FA(Feature Ability)](#fa)和[PA(Particle Ability)](#pa)两种类型,其中FA支持Page Ability模板,PA支持Service ability、Data ability、以及Form ability模板。详情可参考[FA模型综述](application-dev/ability/fa-brief.md)。 ## H @@ -55,6 +81,10 @@ OpenHarmony Ability Package,一个HAP文件包含应用的所有内容,由代码、资源、三方库及应用配置文件组成,其文件后缀名为.hap。 +- ### HAR + + OpenHarmony Archive文件。包含代码、资源和配置文件的中间格式。 + - ### HCS HDF Configuration Source是HDF驱动框架的配置描述语言,是为了实现配置代码与驱动代码解耦,以及便于配置的管理而设计的一种Key-Value为主体的文本格式。 @@ -80,6 +110,12 @@ Intelligent Distributed Networking,是OpenHarmony特有的分布式组网能力单元。开发者可以通过IDN获取分布式网络内的设备列表和设备状态信息,以及注册分布式网络内设备的在网状态变化信息。 +## N + +- ### Native Framework + + 原生框架,指系统自带的开发框架。非原生的框架即三方框架。 + ## P @@ -87,18 +123,41 @@ Particle Ability,是在FA模型的Ability框架下无界面的Ability,主要为Feature Ability提供服务与支持,例如作为后台服务提供计算能力,或作为数据仓库提供数据访问能力。Particle Ability有三种模板,分别为Service模板(Service Ability)、Data模板(Data Ability)、以及Form模板(Form Ability)。 - ## S +- ### SA + + System Ability的简称,这是由系统开发者编写的系统级组件。 + +- ### Secondary Framework + + 次生框架,指不依赖原生框架实现的三方开框架。 + +- ### Stage模型 + + Ability框架自API version 9提供的开发模型。Stage模型将Ability分为UIAbility和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility。 + - ### Super virtual device,超级虚拟终端 亦称超级终端,通过分布式技术将多个终端的能力进行整合,存放在一个虚拟的硬件资源池里,根据业务需要统一管理和调度终端能力,来对外提供服务。 -- ### Stage模型 +- ### SysCap - Ability开发框架支持的开发模型中的一种。从API Version 9起应用开发开始支持Stage模型。Stage模型将Ability分为Ability和ExtensionAbility两大类,其中ExtensionAbility又被扩展为ServiceExtensionAbility、FormExtensionAbility、DataShareExtensionAbility等等一系列ExtensionAbility。 + 全称是System Capability,指OpenHarmony中每个相对独立的特性,如蓝牙,WiFi,NFC,摄像头等,都是系统能力之一。每个系统能力对应多个API,每个API定义上包含了相应的SysCap标签。 - ### System Type,系统类型 - - MiniSystem,轻量系统:面向MCU(Microcontroller Unit,微控制单元)类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 + - Mini System,轻量系统:面向MCU(Microcontroller Unit,微控制单元)类处理器,例如ARM Cortex-M、RISC-V 32位的设备,资源极其有限,参考内存≥128KiB,提供丰富的近距连接能力以及丰富的外设总线访问能力。典型产品有智能家居领域的联接类模组、传感器设备等。 - Small System,小型系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥1MiB,提供更高的安全能力,提供标准的图形框架,提供视频编解码的多媒体能力。典型产品有智能家居领域的IPCamera、电子猫眼、路由器以及智慧出行域的行车记录仪等。 - Standard System,标准系统:面向应用处理器,例如Arm Cortex-A的设备,参考内存≥128MiB,提供增强的交互能力,提供3D GPU以及硬件合成能力,提供更多控件以及动效更丰富的图形能力,提供完整的应用框架。典型产品有高端的冰箱显示屏等。 + +## U + +- ### UI Component + + UI组件,组成用户界面的一部分,可提供用户交互的能力。 + +## X + +- ### XComponent + + ArkUI提供的组件接口,满足开发者自渲染的需求。 diff --git a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md index 219299721d153e1bef8724a85e7ca96145e7dcec..514bbb14842b9aa7846e18e4aa209d2b699f86bd 100644 --- a/zh-cn/readme/ARK-Runtime-Subsystem-zh.md +++ b/zh-cn/readme/ARK-Runtime-Subsystem-zh.md @@ -8,79 +8,74 @@ ## 简介 -方舟编译器\(ArkCompiler\)是OpenHarmony内置的组件化、可配置的多语言编译和运行平台,包含编译器、工具链、运行时等核心部件,支持高级编程语言在多种芯片平台上编译与运行,并支撑OpenHarmony标准操作系统及其应用和服务运行在手机、个人电脑、平板、电视、汽车和智能穿戴等多种设备上的需求。开源的ArkCompiler JS Runtime提供的能力是在OpenHarmony操作系统中编译和运行JavaScript语言\(本文后面简称JS\)。 +方舟编译器\(ArkCompiler\)是为支持多种编程语言、多种芯片平台的联合编译、运行而设计的统一编译运行时平台。它支持包括动态类型和静态类型语言在内的多种编程语言,如JS、TS、ArkTS;它是支撑鸿蒙系统成为打通手机、PC、平板、电视、车机和智能穿戴等多种设备的操作系统的编译运行时底座。 -ArkCompiler JS Runtime分成两个部分,分别是JS编译工具链与JS运行时。JS工具链将JS源码编译成方舟字节码\(ArkCompiler Bytecode\),JS运行时负责执行生成的方舟字节码\(后续如无特殊说明,字节码特指方舟字节码\)。 - -**图1** JS编译工具链架构: +ArkCompiler主要分成两个部分:编译工具链与运行时. +**图1** 编译工具链架构 ![](figures/zh-cn_image_ark_frontend.png) -ArkCompiler JS Runtime的源码编译器接收JS源码的输入,再由ts2abc(将JavaScript文件转换为字节码的工具)生成abc文件。 +ArkCompiler的编译工具链以ArkTS/TS/JS源码作为输入,将其编译生成为abc(ArkCompiler Bytecode,即方舟字节码)文件。 -**图2** JS运行时\(Ark-JS-Runtime\)架构: +**图2** 运行时架构 -![](figures/zh-cn_image_ark-js-arch.png) +![](figures/zh-cn_image_ark-ts-arch.png) -ArkCompiler JS Runtime以方舟字节码文件作为输入并直接运行字节码文件,实现对应的JS语义逻辑。 +ArkCompiler运行时直接运行字节码文件,实现对应语言规范的语义逻辑。 -JS Runtime主要由四个子系统组成: +主要由四个子系统组成: - Core Subsystem - Core Subsystem主要由与语言无关的基础运行库组成,包括承载字节码的ArkCompiler File组件、支持Debugger的Tooling组件、负责对应系统调用的ArkCompiler Base库组件等。 + Core Subsystem主要由与语言无关的基础运行库组成,包括承载字节码的File组件、支持Debugger的Tooling组件、负责适配系统调用的Base库组件等。 -- JS Execution Subsystem +- Execution Subsystem - 执行引擎包含执行字节码的解释器、缓存隐藏类和内联缓存、以及剖析记录运行时类型的Profiler。 + Execution Subsystem包含执行字节码的解释器、快速路径内联缓存、以及抓取运行时信息的Profiler。 -- JS Compiler Subsystem +- Compiler Subsystem - 编译子系统包含Stub编译器、基于Circuit IR的优化编译框架和代码生成器。 + Compiler Subsystem包含Stub编译器、基于IR的编译优化框架和代码生成器。 -- JS Runtime subsystem +- Runtime subsystem - 运行时子系统包含了各种JS运行相关的模块: + Runtime Subsystem包含了ArkTS/TS/JS运行相关的模块。 - 内存管理:对象分配器与垃圾回收器\(并发标记和部分内存压缩的CMS-GC和Partial-Compressing-GC\) - 分析工具:DFX工具、cpu和heap的profiling工具 - 并发管理:actor并发模型中的abc文件管理器 - 标准库:Ecmascript规范定义的标准库、高效的container容器库与对象模型 - 其他:异步工作队列、TypeScript类型加载、跟C++交互的JSNAPI接口等。 -**ArkCompiler-JS的设计特点:** - -- ArkCompiler JS Runtime的主要设计目标: +**ArkCompiler eTS Runtime的设计特点:** - 为OpenHarmony操作系统提供JavaScript/TypeScript应用程序执行引擎,而不是作为浏览器中的JavaScript执行引擎。 +- 原生支持类型 + 目前业界引擎执行TS的方式是先把TS转化为JS,再运行JS源码来完成对应的语义逻辑。ArkCompiler的编译工具链编译TS源码时,会分析推导TS的类型信息并将其传递给运行时。运行时直接使用类型信息在运行前预生成内联缓存(Inline Cache)以加速字节码执行。另外,TSAOT (Ahead-of-Time) Compiler,可以利用字节码文件中的类型信息,直接编译生成优化机器码,使得应用可以直接运行优化机器码,获得高性能运行体验。 -- 为了提升应用的执行性能和安全性: +- 并发:并发模型优化与并发API - ArkCompiler JS Runtime选择将JavaScript/TypeScript程序预先静态编译为方舟字节码(带上静态类型信息),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler JS Runtime选择不支持eval和只支持strict模式的代码。 + ArkCompiler eTS Runtime选择将ArkTS程序预先静态编译为方舟字节码\(带上静态类型信息\),从而减少运行时的编译和类型信息收集开销。另外出于安全性和性能的考虑,ArkCompiler eTS Runtime选择不支持eval和只支持strict模式的代码。 - 原生支持TypeScript: + ECMAScript规范没有提供并发语义表述;业界引擎,如浏览器或者Node.js,通常会提供基于Actor并发模型的Worker API来支持多线程开发。Actor模型下执行体之间不共享任何数据对象,通过消息机制进行通信。因此Web引擎或者Node.js引擎的Worker都有启动速度慢、内存占用高这些缺陷。 针对这些缺陷,ArkCompiler的运行时已经实现了Actor实例中的不可变或者不易变的对象(方法和字节码)的共享,较大程度地优化了Actor的启动性能和启动内存。 + 方舟编译运行时不只提供了业界通用的Worker API,还提供了TaskPool作为并发API的增强。TaskPool是一个支持优先级调度、工作线程自动扩缩容的任务池功能库。开发者无需关心并发实例的生命周期,也无需关心任务负载变化时需要创建或者销毁并发实例,极大地简化了高性能多线程鸿蒙应用的开发。 - 目前业界通用的执行方式是把TS转化为JS,再通过JS运行时来执行。ArkJS规划在ts2abc编译TS源码时,会推导分析TS的类型信息并传递给ArkCompiler JS运行时。运行时直接利用类型信息静态生成内联缓存(inline caching)从而加速字节码执行。另外,ArkJS规划中的TSAOT \(Ahead-of-Time\) Compiler,可以利用ts2abc传递的类型信息,直接编译生成高质量的机器码,使得应用可以直接以机器码形式运行,提升运行性能。 - -- 轻量级Actor并发模型: - ECMAScript没有提供并发规范,业界JS引擎的实现中常用Actor并发模型。此模型下执行体之间不共享任何数据,通过消息机制进行通信。业界当前实现的JS Actor模型(web-worker)有启动速度慢、内存占用高这些缺陷。为了利用设备的多核能力获得更好的性能提升,ArkCompiler JS Runtime需要提供启动快、内存占用少的Actor实现。目前ArkCompiler JS运行时已经实现在Actor内存隔离模型的基础上,共享actor实例中的不可变或者不易变的对象(方法和字节码),后续继续共享内建代码块、常量字符串等等,来提升JS Actor的启动性能和节省内存开销,达到实现轻量级Actor并发模型的目标。 - -- TypeScript/C++的跨语言交互: - - 在OpenHarmony操作系统平台API实现中,通常需要面临C/C++代码访问和操作TS对象的场景。对这个业务场景,Ark-JS规划可以根据TS程序中的class声明和运行时约定,静态生成包含TS对象布局描述的C/C++头文件,以及操作这些TS对象的C/C++实现库。在C/C++代码中,通过包含TS对象描述头文件以及链接对应实现库,实现直接操作TS对象的效果。由于TS类型或其内在布局并非总是固定不变的,因此在TS对象操作的代码实现中,会插入类型检查,如果对象类型或布局在运行时发生变化,则回退执行通用的慢速路径。 +- 安全 + ArkCompiler前端编译工具链将ArkTS/TS/JS程序预先静态编译为方舟字节码,并且还提供了多重混淆能力的增强,有效地提升了开发者代码资产的安全强度。另外出于安全的考虑,ArkCompiler不支持sloppy模式的JS代码,也不支持eval等运行动态字符串的功能。 ## 目录 ``` -/ark -├── ets_runtime # JS运行时组件 +/arkcompiler +├── ets_runtime # ArkTS运行时组件 ├── runtime_core # 运行时公共组件 -└── ets_frontend # JS语言的前端工具 +├── ets_frontend # ArkTS语言的前端工具 +└── toolchain # ArkTS工具链 ``` ## 使用指南 -[方舟运行时使用指南](https://gitee.com/openharmony/ark_js_runtime/blob/master/docs/ARK-Runtime-Usage-Guide-zh.md) +[方舟运行时使用指南](https://gitee.com/openharmony/arkcompiler_ets_runtime/blob/master/docs/ARK-Runtime-Usage-Guide-zh.md) ## 相关仓 @@ -88,4 +83,6 @@ JS Runtime主要由四个子系统组成: [arkcompiler\_ets\_runtime](https://gitee.com/openharmony/arkcompiler_ets_runtime) -[arkcompiler\_ets\_frontend](https://gitee.com/openharmony/arkcompiler_ets_frontend) \ No newline at end of file +[arkcompiler\_ets\_frontend](https://gitee.com/openharmony/arkcompiler_ets_frontend) + +[arkcompiler\_toolchain](https://gitee.com/openharmony/arkcompiler_toolchain) \ No newline at end of file diff --git a/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png b/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png deleted file mode 100644 index 4e34094c9c82cd80881078df9b5e5904dbe98a61..0000000000000000000000000000000000000000 Binary files a/zh-cn/readme/figures/zh-cn_image_ark-js-arch.png and /dev/null differ diff --git a/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png b/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png new file mode 100644 index 0000000000000000000000000000000000000000..37e189f25c9e0f491e94356baa497e314ab289c1 Binary files /dev/null and b/zh-cn/readme/figures/zh-cn_image_ark-ts-arch.png differ diff --git a/zh-cn/readme/figures/zh-cn_image_ark_frontend.png b/zh-cn/readme/figures/zh-cn_image_ark_frontend.png index e8e9951f3f2dc5b566a3d9b36229def46c41aecd..bfd39d9ddfd5f0566331e0447fea05b9ecbba177 100644 Binary files a/zh-cn/readme/figures/zh-cn_image_ark_frontend.png and b/zh-cn/readme/figures/zh-cn_image_ark_frontend.png differ diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md new file mode 100644 index 0000000000000000000000000000000000000000..c2cb5e5f9bc6f025538a0d3a3ceca64b3d782dff --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.4-release.md @@ -0,0 +1,137 @@ +# OpenHarmony 3.1.4 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.3 Release的基础上,修复了linux kernel等开源组件的已知漏洞,增强了系统安全性。更新配套的SDK版本,修复了预览器相关的问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.4 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.9.7 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.9.7 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.1 Preview for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.4-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二** + +通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.4-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + +| 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/code-v3.1.4-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/code-v3.1.4-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_rk3568.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.4 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-full.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.9.7 | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-public.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.4/ohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.3 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +### API变更 + +3.1.4 Release对比3.1.3 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +### 修复缺陷列表 + +**表3** 修复缺陷issue列表 + +| 子系统 | 问题描述 | +| --------- | ------------------------------------------------------------ | +| SDK子系统 | 解决了预览器相关的一些问题([I59433](https://gitee.com/openharmony/arkui_ace_engine/issues/I59433)、[I5K6B1](https://gitee.com/openharmony/arkui_ace_engine/issues/I5K6B1)、[I5C9XJ](https://gitee.com/openharmony/arkui_ace_engine/issues/I5C9XJ)、[I5AVZT](https://gitee.com/openharmony/arkui_ace_engine/issues/I5AVZT)) | +| Demo应用 | 修复小型系统退出设置后应用无法再进入的问题([I5KTI8](https://gitee.com/openharmony/applications_sample_camera/issues/I5KTI8)) | + + + + +### 修复安全漏洞列表 + +**表4** 修复安全问题列表 + +| ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5SD5S | 修复组件expat上的CVE-2022-40674安全漏洞 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/20) | +| I5XTS9 | 修复组件expat上的CVE-2022-43680安全漏洞 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/23) | +| I5VNM9 | 修复组件skia上的CVE-2022-27405安全漏洞 | [PR](https://gitee.com/openharmony/third_party_skia/pulls/24) | +| I5VGM0 | 修复组件kernel_linux_5.10上的CVE-2022-20421、CVE-2022-42719、CVE-2022-42720、CVE-2022-42721、CVE-2022-42722、CVE-2022-41674、CVE-2022-3535、CVE-2022-3521、CVE-2022-3565、CVE-2022-3594、CVE-2022-3435、CVE-2022-41849、CVE-2022-3524、CVE-2022-3542、CVE-2022-3534安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/502) | +| I5SBWK | 修复组件kernel_linux_5.10上的CVE-2022-3202、CVE-2022-40307安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/463) | +| I5QBUR | 修复组件kernel_linux_5.10上的CVE-2022-1184安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/474) | +| I5WSJ5 | 修复组件chromium上的CVE-2022-3199、CVE-2022-3046、CVE-2022-3041、CVE-2022-3040、CVE-2022-3039、CVE-2022-3038、CVE-2022-3057、CVE-2022-3195、CVE-2022-3054、CVE-2022-3075安全漏洞,并同步更新webview hap包 | [PR](https://gitee.com/openharmony/web_webview/pulls/349) | +| I5UF8Z | 修复标准系统上的dhd_linux.c中泄露MAC地址的安全问题 | [PR](https://gitee.com/openharmony/kernel_linux_patches/pulls/315) | +| I5VISW | 修复标准系统上的蓝牙日志中存在明文打印Mac地址的安全问题 | [PR](https://gitee.com/openharmony/communication_bluetooth/pulls/626) | +| I5WJU0 | 修复标准系统上的分布式组网日志中出现设备udid敏感信息的安全问题 | [PR](https://gitee.com/openharmony/security_access_token/pulls/761) | diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 36430bb2fd1f920166bfe0f29e88ac42d02c5035..984e715246614522f5be8011bed7a25195794ab0 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -5,6 +5,7 @@ - [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) - [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) - [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.4 Release (2022-11-02)](OpenHarmony-v3.1.4-release.md) - [OpenHarmony v3.1.3 Release (2022-09-30)](OpenHarmony-v3.1.3-release.md) - [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) - [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md) diff --git a/zh-cn/release-notes/changelogs/weekly-20221025/changelogs-ability.md b/zh-cn/release-notes/changelogs/weekly-20221025/changelogs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..5d2efae259ce81f686f324053750ef89ac5205b5 --- /dev/null +++ b/zh-cn/release-notes/changelogs/weekly-20221025/changelogs-ability.md @@ -0,0 +1,128 @@ +# 元能力子系统ChangeLog + +## cl.ability.1 应用组件启动规则变更 + +元能力子系统应用组件启动规则在如下场景中存在变更: + + - 应用位于后台启动应用组件 + - 跨应用启动invisible应用组件 + - 跨应用启动FA模型的serviceAbility与dataAbility + - 使用startAbilityByCall接口 + +开发者需要根据以下说明对应用进行适配。 + + +**变更影响** + +若未适配新规则,在上述场景下将无法启动应用组件 +> **注意,启动应用组件是指一切启动或连接Ability的行为:** +
1. 启动Ability,如使用startAbility、startServiceExtensionAbility、startAbilityByCall等接口。 +
2. 连接Ability,如使用connectAbility、connectServiceExtensionAbility、acquireDataAbilityHelper、createDataShareHelper等接口。 + +**关键的接口/组件变更** + + - 涉及的应用组件 + - Stage模型 + - Ability + - ServiceExtension + - DataShareExtension + - FA模型 + - PageAbility + - ServiceAbility + - DataAbility + - 涉及接口 + - Stage模型 + - startAbility(want: Want, callback: AsyncCallback): void; + - startAbility(want: Want, options: StartOptions, callback: AsyncCallback): void; + - startAbility(want: Want, options?: StartOptions): Promise; + - startAbilityByCall(want: Want): Promise; + - startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; + - startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback): void; + - startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise; + - startAbilityForResult(want: Want, callback: AsyncCallback): void; + - startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback): void; + - startAbilityForResult(want: Want, options?: StartOptions): Promise; + - startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; + - startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback): void; + - startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise; + - startServiceExtensionAbility(want: Want, callback: AsyncCallback): void; + - startServiceExtensionAbility(want: Want): Promise; + - startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; + - startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise; + - stopServiceExtensionAbility(want: Want, callback: AsyncCallback): void; + - stopServiceExtensionAbility(want: Want): Promise; + - stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; + - stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise; + - connectAbility(want: Want, options: ConnectOptions): number; + - connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; + - createDataShareHelper(context: Context, uri: string, callback: AsyncCallback): void + - FA模型 + - startAbility(parameter: StartAbilityParameter, callback: AsyncCallback): void; + - startAbility(parameter: StartAbilityParameter): Promise; + - startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback): void; + - startAbilityForResult(parameter: StartAbilityParameter): Promise; + - acquireDataAbilityHelper(uri: string): DataAbilityHelper; + - connectAbility(request: Want, options:ConnectOptions ): number; + +**适配指导** + +不同场景下的启动规则说明如下: + - **应用后台启动应用组件** + - OpenHarmony 3.2-beta3 版本规则: + - 应用位于后台时,启动应用组件不受任何限制。 + - OpenHarmony 3.2-Release 版本新规则: + - 当应用位于后台时,启动应用组件需鉴权,需申请的权限如下: + - ```json + { + "name": "ohos.permission.START_ABILITIES_FROM_BACKGROUND", + "grantMode": "system_grant", + "availableLevel": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + } + ``` + > **注:** +
1. 即使启动同应用的组件,也受该规则限制。 +
2. 对于API8以及之前的SDK,启动serviceAbility和dataAbility不受此规则限制。 + + - **跨应用启动invisible应用组件** + - OpenHarmony 3.2.beta3 版本规则: + - 对于APL为normal的应用,无法跨应用启动invisible的应用组件 + - OpenHarmony 3.2-Release 版本新规则: + - 所有应用,若需要跨应用启动invisible的应用组件,需鉴权,需申请的权限如下: + - ```json + { + "name": "ohos.permission.START_INVISIBLE_ABILITY", + "grantMode": "system_grant", + "availableLevel": "system_core", + "provisionEnable": true, + "distributedSceneEnable": false + } + ``` + + - **跨应用启动FA模型的serviceAbility与dataAbility** + + - OpenHarmony 3.2.beta3 版本规则: + - 可任意跨应用启动serviceAbility与dataAbility + - OpenHarmony 3.2-Release 版本新规则: + - serviceAbility与dataAbility的提供方应用需配置关联启动,否则无法被跨应用拉起。(普通应用无法配置关联启动) + + + - **startAbilityByCall接口** + - OpenHarmony 3.2.beta3 版本规则: + - 可任意进行Call调用 + - OpenHarmony 3.2-Release 版本新规则: + - 不支持同应用startAbilityByCall调用 + - 跨应用startAbilityByCall调用需鉴权,需申请的权限如下: + + - ```json + { + "name": "ohos.permission.ABILITY_BACKGROUND_COMMUNICATION", + "grantMode": "system_grant", + "availableLevel": "system_basic", + "provisionEnable": true, + "distributedSceneEnable": false + } + ``` + > **注:** +
使用startAbilityByCall接口同时也受上述后台启动、跨应用启动invisible规则的限制。 \ No newline at end of file