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/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/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/device/device-location-info.md b/en/application-dev/device/device-location-info.md index f3572352e718bb77493d7dd2d097d2d7a82058c9..a153f69fbfe2b71362a4b7e5808fe57c1b7a4216 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -66,7 +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. - You can declare the required permission in your application's configuration file. For details, 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/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/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/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/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..6e564f2518cf3ce6f083da66d8d72c0b8310f650 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) @@ -146,6 +147,7 @@ - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.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 +215,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 +264,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-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-call.md b/en/application-dev/reference/apis/js-apis-call.md index 34fe47f45abe436abf986da809e343fd638540d7..a04f49f6d46bd886af5b23c01e65ce7d0b689e85 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -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-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-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 4502b4cd9601bf0ae050f972a674028fb271a86a..31414ab325572d7ed25a31b1b3a78a725dce39e6 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -309,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 @@ -337,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 @@ -351,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** @@ -370,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 @@ -398,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 @@ -412,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** @@ -521,7 +529,7 @@ This is a system API. | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -570,7 +578,7 @@ This is a system API. | Type | Description | | ------------------------------------------- | ----------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** @@ -888,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-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 206ad668b6dbdaf8f12d74423a92c5d6ebaf2853..a5515dadfbd141dc16bfa44b2edffea5013109f4 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -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)}`); 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-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/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-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/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/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/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/location.md b/en/readme/location.md index 369f272c6ec8d1af651f9b69ae4db2d893df464e..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,7 +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. - You can declare the required permission in your application's configuration file. For details, 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..2a05a5db1a6cda5f2b97c562af51df1fd084b999 100644 --- a/zh-cn/application-dev/ability/stage-ability.md +++ b/zh-cn/application-dev/ability/stage-ability.md @@ -320,8 +320,4 @@ struct Index { } } } -``` - -## 相关实例 -针对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 781cdee7fa99ea7233d166edd67984b9c52f47f6..a1f9a5d5d54e54dfec706dcd4823d8384a5b8641 100644 --- a/zh-cn/application-dev/ability/stage-call.md +++ b/zh-cn/application-dev/ability/stage-call.md @@ -46,8 +46,7 @@ Caller及Callee功能如下:具体的API详见[接口文档](../reference/apis Call调用的开发步骤: - 创建Callee被调用端。 - 访问Callee被调用端。 -> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 开发步骤章节中的示例代码片段是开发过程的步骤化展示,部分代码可能无法单独运行,完整工程代码请参考[相关实例](#相关实例)。 + ### 创建Callee被调用端 Callee被调用端,需要实现指定方法的数据接收回调函数、数据的序列化及反序列化方法。在需要接收数据期间,通过on接口注册监听,无需接收数据时通过off接口解除监听。 **1. 配置Ability的启动模式** @@ -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/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/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/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-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 63686d8842829834e58cc92e6b95ff3a0db754db..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。 ## 运作机制 @@ -39,13 +40,11 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 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 @@ -86,54 +85,53 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 ```js import fileio from '@ohos.fileio'; + import audio from '@ohos.multimedia.audio'; - async function writeBuffer(buf) { - let state = audioRenderer.state; - // 写入数据时,渲染器的状态必须为STATE_RUNNING - if (state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - this.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'); - } - } + 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(); - const path = '/data/file_example_WAV_2MG.wav'; // 需要渲染的音乐文件 - 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; + // 此处是渲染器的合理的最小缓冲区大小(也可以选择其它大小的缓冲区) + 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 (this.isRelease) { // 如果渲染器状态为release,停止渲染 - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - if (this.isPlay) { - if (rlen >= totalSize) { // 如果音频文件已经被读取完,停止渲染 - 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); // 定时器区间根据音频格式设置,单位为毫秒 + 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()方法暂停/停止渲染音频数据。 @@ -269,6 +267,8 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 在某些情况下,框架会采取暂停播放、降低音量等强制操作,并通过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('audioInterrupt', (interruptEvent) => { @@ -360,11 +360,184 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 } catch (err) { console.info(`Call on function error, ${err}`); // 程序抛出401异常 } - try { audioRenderer.on(1, () => { // 入参类型错误 }) } catch (err) { console.info(`Call on function error, ${err}`); // 程序抛出6800101异常 } - ``` \ No newline at end of file + ``` + +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 + } + + //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); // 定时器区间根据音频格式设置,单位为毫秒 + } + + 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 + } + + //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); // 定时器区间根据音频格式设置,单位为毫秒 + } + + 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'); + } + } + + //综合调用入口 + async test(){ + await runningAudioRender1(); + await runningAudioRender2(); + } + + ``` \ No newline at end of file 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/notification/notification-guidelines.md b/zh-cn/application-dev/notification/notification-guidelines.md index 05e9e97a51132ca686c0a27aebb3e44ed2327f04..8f2df9f689bd3ae019f779516c90ac121947fa60 100644 --- a/zh-cn/application-dev/notification/notification-guidelines.md +++ b/zh-cn/application-dev/notification/notification-guidelines.md @@ -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/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index f2249cb4417dce2228fa045e7c90304e92ebf3a1..b0acbfbbdeca2001712ad83c4002d04b5cfb96c0 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -65,30 +65,16 @@ - [@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) @@ -269,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/js-apis-Bundle-BundleStatusCallback.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md index c3011990c82f4521be8ace3d68561bce6c90f7c3..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,7 +1,5 @@ # BundleStatusCallback - - > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > 从API version 9开始不再支持。建议使用[bundleMonitor](js-apis-bundleMonitor.md)替代。 @@ -18,9 +16,6 @@ | 监听类型 | 注册回调 | 说明 | | ------ | --------------------------------------------- | -------------------------------------- | -| 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.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-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 3bf7786bb7175ba951fbce561abe33050f5d8e52..d22d8041b6e7b65857880d58423d02439a4eb57a 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 | 是 | 查询的权限名称。 | **返回值:** @@ -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..e2a83d75a2b15810ca6afc19cf1f3ec8ec60601b 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 @@ -44,6 +44,5 @@ constructor(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..0639e6939b1cf40624385e039195a7f564d0503e 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 @@ -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..e4c42fbf76f3f226625d33223e8fa11e7c482aa5 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 @@ -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 @@ -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; @@ -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)); @@ -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)); }; ``` @@ -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)); }; ``` @@ -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)); @@ -437,12 +427,8 @@ off(callback?: Callback<T>): void; **示例:** ```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.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md index b36394fe89ced28ce55eb7b16a5e8a74899a1df7..030d38e87283e565e7dbc266f74a39ded410e21f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md @@ -171,16 +171,10 @@ on(type: 'enableChange', callback: Callback<boolean>): void; **示例:** ```ts -let result = false; let captionsManager = accessibility.getCaptionsManager(); try { - captionsManager.on('enableChange', (err, data) => { - 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)); @@ -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)); @@ -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)); } ``` @@ -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)); } ``` @@ -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异步回调。 @@ -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)); @@ -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)); @@ -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)); @@ -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)); } ``` @@ -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)); } ``` 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 95% 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..71058a3a8c86c7c6c54067cd6f9ea7c2705de741 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-appControl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md @@ -57,7 +57,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { @@ -119,7 +119,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { @@ -186,7 +186,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { @@ -245,7 +245,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { @@ -310,7 +310,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { @@ -369,7 +369,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; var bundleName = 'com.example.myapplication'; var appId; try { - bundleManager.getBundleInfo(bundleName, BundleManager.BundleFlags.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) + bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO) .then((data) => { appId = data.signatureInfo.appId; }, error => { 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 880420e98324d3e6432c85e7df709d5d37815cf6..44d9ce297359623bc6c77ffc43fe33bfb8575d75 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -422,8 +422,6 @@ 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)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 } catch(err) { 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 633b9aff701fdfc7309aeb6aaf1a84f1b3ed31a4..fd8c5a68e0bbcb5bc50bd0dec63377c551e66f84 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 **参数:** @@ -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) | 是 | 配置的音调类型。 | **返回值:** @@ -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-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..b4c6f557599e3617bd94282366b0d41f03261933 --- /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 | 设置禁用使能所需的权限 | + +权限等级参考[权限等级说明](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) + +## 枚举 + +### 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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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-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 49111b648c5c66fa8846e16561160dfe97fee3a6..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 @@ -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 221f6ae908a9831104324c9579232c191e29595b..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 **参数:** @@ -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 **参数:** @@ -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 **返回值:** @@ -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 **返回值:** @@ -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 **返回值:** @@ -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 **返回值:** @@ -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,13 +993,17 @@ 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 **示例:** 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-effectKit.md b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md index 7231f0e6ed98c792dfdc695ae7fbad2bb86e07a4..37e09247632690faf9128bcbfc2cc558dd897427 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-effectKit.md +++ b/zh-cn/application-dev/reference/apis/js-apis-effectKit.md @@ -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) => { 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 da0b5ea904f03fd13c5a39a04654d2c03560cdc9..c835160acbbd11c07a24985a49fb4887d67690e9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-featureAbility.md @@ -271,8 +271,8 @@ featureAbility.terminateSelfWithResult( } }, }, - (err, data) => { - console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + (err) => { + console.info("err: " + JSON.stringify(err)) } ); ``` @@ -470,8 +470,8 @@ terminateSelf(callback: AsyncCallback\): void ```javascript import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf( - (err, data) => { - console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)) + (err) => { + console.info("err: " + JSON.stringify(err)) } ) ``` @@ -601,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) }, ); ``` 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..7a3d08fbd358af5a3d91672125854554fc5db1a8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -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); }); 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..b3ef0bd3551af1d94ab8fc12c8e57306eb9d4be9 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-freeInstall.md @@ -0,0 +1,451 @@ +# 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 | 可安装、卸载应用 | + +权限等级参考[权限等级说明](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) + +## 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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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-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..ecd2d4b1968e32a6ab1c990538bc57c4e898e6f4 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`])}`); } 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 6f381f501ab77c7b76e03734dd6311fe61801b7c..aa6d25ec0cd7d5f234d36895b749b883ccb64844 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 @@ -4,11 +4,11 @@ > **说明:** > ->本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` +```js import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; ``` @@ -16,12 +16,11 @@ import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; **系统能力:** SystemCapability.MiscServices.InputMethodFramework -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------- | -------- | -------- | -------- | -------- | -| context | [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) | 是 | 否 | InputMethodExtension的上下文环境,继承自ExtensionContext。 | - +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------- | -----------------| --- | ---- | -------------------- | +| context | [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) | 是 | 否 | InputMethodExtension的上下文环境,继承自ExtensionContext。 | -## InputMethodExtensionAbility.onCreate() +## InputMethodExtensionAbility.onCreate onCreate(want: Want): void @@ -31,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名称等。 | **示例:** @@ -45,8 +44,7 @@ class InputMethodExt extends InputMethodExtensionAbility { } ``` - -## InputMethodExtensionAbility.onDestroy() +## InputMethodExtensionAbility.onDestroy onDestroy(): void @@ -62,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 08383f51ffe342900ed135280352af89b4b31b0f..3a82fbdbae70fc44f158e06df7eaa463d351dbd0 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 | 错误码信息 | | -------- | -------------------------------------- | @@ -126,7 +126,7 @@ switchInputMethod(target: InputMethodProperty, callback: AsyncCallback<boolea ```js try{ - inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}, (err, result) => { + inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard', extra: {}}, (err, result) => { if (err) { console.error('switchInputMethod err: ' + JSON.stringify(err)); return; @@ -164,7 +164,7 @@ switchInputMethod(target: InputMethodProperty): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -175,7 +175,7 @@ switchInputMethod(target: InputMethodProperty): Promise<boolean> ```js try { - inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => { + inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard', extra: {}}).then((result) => { if (result) { console.info('Success to switchInputMethod.'); } else { @@ -228,7 +228,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -240,7 +240,14 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallb ```js let inputMethodSubtype = { id: "com.example.kikainput", - label: "ServiceExtAbility" + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} } try { inputMethod.switchCurrentInputMethodSubtype(inputMethodSubtype, (err, result) => { @@ -283,7 +290,7 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean& **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -295,7 +302,14 @@ switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean& ```js let inputMethodSubtype = { id: "com.example.kikainput", - label: "ServiceExtAbility" + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} } try { inputMethod.switchCurrentInputMethodSubtype(inputMethodSubtype).then((result) => { @@ -352,7 +366,7 @@ switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inp **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -363,12 +377,20 @@ switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inp ```js let inputMethodProperty = { - packageName:"com.example.kikakeyboard", - methodId:"ServiceExtAbility" + packageName: "com.example.kikakeyboard", + methodId: "ServiceExtAbility", + extra: {} } let inputMethodSubProperty = { id: "com.example.kikainput", - label: "ServiceExtAbility" + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} } try { inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, inputMethodSubProperty, (err,result) => { @@ -412,7 +434,7 @@ switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inp **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -515,7 +537,7 @@ stopInputSession(callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -558,7 +580,7 @@ stopInputSession(): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -601,7 +623,7 @@ showSoftKeyboard(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -638,7 +660,7 @@ showSoftKeyboard(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -673,7 +695,7 @@ hideSoftKeyboard(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -710,7 +732,7 @@ hideSoftKeyboard(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -861,7 +883,7 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: Async **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -873,7 +895,8 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: Async ```js let inputMethodProperty = { packageName:'com.example.kikakeyboard', - methodId:'com.example.kikakeyboard' + methodId:'com.example.kikakeyboard', + extra:{} } try { InputMethodSetting.listInputMethodSubtype(inputMethodProperty, (err,data) => { @@ -910,7 +933,7 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty): Promise<Arr **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -923,6 +946,7 @@ listInputMethodSubtype(inputMethodProperty: InputMethodProperty): Promise<Arr let inputMethodProperty = { packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard', + extra:{} } try { InputMethodSetting.listInputMethodSubtype(inputMethodProperty).then((data) => { @@ -951,7 +975,7 @@ listCurrentInputMethodSubtype(callback: AsyncCallback<Array<InputMethodSub **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -990,7 +1014,7 @@ listCurrentInputMethodSubtype(): Promise<Array<InputMethodSubtype>> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -1028,7 +1052,7 @@ getInputMethods(enable: boolean, callback: AsyncCallback<Array<InputMethod **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -1067,7 +1091,7 @@ getInputMethods(enable: boolean): Promise<Array<InputMethodProperty>> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -1112,7 +1136,7 @@ showOptionalInputMethods(callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------------------- | @@ -1152,7 +1176,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 d98281b3b4215925417165965c8982f2723f0164..21a731926282a8f66412a5e7fec8de00c91bfb60 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,6 +1,6 @@ # 输入法服务 -本模块的作用是拉通普通应用和输入法应用,功能包括:普通应用通过输入法应用进行文本输入、普通应用与输入法服务绑定、普通应用对输入法应用进行显示请求和隐藏请求、普通应用对输入法应用当前状态进行监听等等。 +本模块的作用是拉通输入法应用和其他三方应用(联系人、微信等),功能包括:将三方应用与输入法应用的服务进行绑定、三方应用通过输入法应用进行文本输入、三方应用对输入法应用进行显示键盘请求和隐藏键盘请求、三方应用对输入法应用当前状态进行监听等。 > **说明:** > @@ -69,7 +69,7 @@ getInputMethodAbility(): InputMethodAbility **示例:** ```js -let InputMethodAbility = inputMethodAbility.getInputMethodAbility(); +let InputMethodAbility = inputMethodEngine.getInputMethodAbility(); ``` ## inputMethodEngine.getKeyboardDelegate9+ @@ -89,7 +89,7 @@ getKeyboardDelegate(): KeyboardDelegate **示例:** ```js -let KeyboardDelegate = inputMethodAbility.getKeyboardDelegate(); +let KeyboardDelegate = inputMethodEngine.getKeyboardDelegate(); ``` ## inputMethodEngine.getInputMethodEngine(deprecated) @@ -183,8 +183,6 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC | type | string | 是 | 设置监听类型。
-type为‘inputStart’时表示订阅输入法绑定。 | | callback | [KeyboardController](#keyboardcontroller), [TextInputClient](#textinputclient) | 否 | 回调函数,返回取消订阅的KeyboardController和TextInputClient实例。 | - - **示例:** ```js @@ -193,98 +191,6 @@ inputMethodEngine.getInputMethodEngine().off('inputStart', (kbController, textIn }); ``` -### on('inputStop')9+ - -on(type: 'inputStop', callback: () => void): void - -订阅停止输入法应用事件。使用callback异步回调。 - -**系统能力:** SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 设置监听类型。
-type为‘inputStop’时表示订阅停止输入法应用事件。 | -| callback | void | 是 | 回调函数。 | - -**示例:** - -```js -inputMethodEngine.getInputMethodEngine().on('inputStop', () => { - console.log('inputMethodEngine inputStop'); -}); -``` - -### off('inputStop')9+ - -off(type: 'inputStop', callback: () => void): void - -取消订阅停止输入法应用事件。使用callback异步回调。 - -**系统能力:** SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 设置监听类型。
-type为‘inputStop’时表示订阅停止输入法应用事件。 | -| callback | void | 是 | 回调函数。 | - -**示例:** - -```js -inputMethodEngine.getInputMethodEngine().off('inputStop', () => { - console.log('inputMethodEngine delete inputStop notification.'); -}); -``` - -### on('setCallingWindow')9+ - -on(type: 'setCallingWindow', callback: (wid:number) => void): void - -订阅设置调用窗口事件。使用callback异步回调。 - -**系统能力:** SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | -| callback | number | 是 | 回调函数,返回调用方window id。 | - -**示例:** - -```js -inputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { - console.log('inputMethodEngine setCallingWindow'); -}); -``` - -### off('setCallingWindow')9+ - -off(type: 'setCallingWindow', callback: (wid:number) => void): void - -取消订阅设置调用窗口事件。使用callback异步回调。 - -**系统能力:** SystemCapability.MiscServices.InputMethodFramework - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | 是 | 设置监听类型。
-type为‘setCallingWindow’时表示订阅设置调用窗口事件。 | -| callback | number | 是 | 回调函数,返回调用方window id。 | - -**示例:** - -```js -inputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { - console.log('inputMethodEngine delete setCallingWindow notification.'); -}); -``` - ### on('keyboardShow'|'keyboardHide') on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void @@ -806,7 +712,7 @@ hide(callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -840,7 +746,7 @@ hide(): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -849,13 +755,11 @@ hide(): Promise<void> **示例:** ```js -async function InputMethodEngine() { - await KeyboardController.hide().then(() => { - console.info('hide success.'); - }).catch((err) => { - console.info('hide err: ' + JSON.stringify(err)); - }); -} +KeyboardController.hide().then(() => { + console.info('hide success.'); +}).catch((err) => { + console.info('hide err: ' + JSON.stringify(err)); +}); ``` ### hideKeyboard(deprecated) @@ -909,13 +813,11 @@ hideKeyboard(): Promise<void> **示例:** ```js -async function InputMethodEngine() { - await KeyboardController.hideKeyboard().then(() => { - console.info('hideKeyboard success.'); - }).catch((err) => { - console.info('hideKeyboard err: ' + JSON.stringify(err)); - }); -} +KeyboardController.hideKeyboard().then(() => { + console.info('hideKeyboard success.'); +}).catch((err) => { + console.info('hideKeyboard err: ' + JSON.stringify(err)); +}); ``` ## InputClient9+ @@ -939,7 +841,7 @@ sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -951,7 +853,7 @@ sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void try { InputClient.sendKeyFunction(keyFunction, (err, result) => { if (err) { - console.error('sendKeyFunction err: ' + JSON.stringify(err)JSON.stringify(err)); + console.error('sendKeyFunction err: ' + JSON.stringify(err)); return; } if (result) { @@ -987,7 +889,7 @@ sendKeyFunction(action:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1028,7 +930,7 @@ getForward(length:number, callback: AsyncCallback<string>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1074,7 +976,7 @@ getForward(length:number): Promise<string> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1084,17 +986,15 @@ getForward(length:number): Promise<string> **示例:** ```js -async function InputMethodAbility() { - let length = 1; - try { - await InputClient.getForward(length).then((text) => { - console.info('getForward resul: ' + text); - }).catch((err) => { - console.error('getForward err: ' + JSON.stringify(err)); - }); - } catch (err) { +let length = 1; +try { + InputClient.getForward(length).then((text) => { + console.info('getForward resul: ' + text); + }).catch((err) => { console.error('getForward err: ' + JSON.stringify(err)); - } + }); +} catch (err) { + console.error('getForward err: ' + JSON.stringify(err)); } ``` @@ -1115,7 +1015,7 @@ getBackward(length:number, callback: AsyncCallback<string>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1161,7 +1061,7 @@ getBackward(length:number): Promise<string> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | ------------------------------ | @@ -1171,17 +1071,15 @@ getBackward(length:number): Promise<string> **示例:** ```js -async function InputMethodAbility() { - let length = 1; - try { - await InputClient.getBackward(length).then((text) => { - console.info('getBackward result: ' + text); - }).catch((err) => { - console.error('getBackward err: ' + JSON.stringify(err)); - }); - } catch (err) { +let length = 1; +try { + InputClient.getBackward(length).then((text) => { + console.info('getBackward result: ' + text); + }).catch((err) => { console.error('getBackward err: ' + JSON.stringify(err)); - } + }); +} catch (err) { + console.error('getBackward err: ' + JSON.stringify(err)); } ``` @@ -1202,7 +1100,7 @@ deleteForward(length:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1252,7 +1150,7 @@ deleteForward(length:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1262,21 +1160,19 @@ deleteForward(length:number): Promise<boolean> **示例:** ```js -async function InputMethodAbility() { - let length = 1; - try { - await InputClient.deleteForward(length).then((result) => { - if (result) { - console.info('Success to deleteForward. '); - } else { - console.error('Failed to deleteForward. '); - } - }).catch((err) => { - console.error('deleteForward err: ' + JSON.stringify(err)); - }); - } catch (err) { +let length = 1; +try { + InputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Success to deleteForward. '); + } else { + console.error('Failed to deleteForward. '); + } + }).catch((err) => { console.error('deleteForward err: ' + JSON.stringify(err)); - } + }); +} catch (err) { + console.error('deleteForward err: ' + JSON.stringify(err)); } ``` @@ -1297,7 +1193,7 @@ deleteBackward(length:number, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1347,7 +1243,7 @@ deleteBackward(length:number): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1357,18 +1253,16 @@ deleteBackward(length:number): Promise<boolean> **示例:** ```js -async function InputMethodAbility() { - let length = 1; - await InputClient.deleteBackward(length).then((result) => { - if (result) { - console.info('Success to deleteBackward. '); - } else { - console.error('Failed to deleteBackward. '); - } - }).catch((err) => { - console.error('deleteBackward err: ' + JSON.stringify(err)); - }); -} +let length = 1; +InputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Success to deleteBackward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}).catch((err) => { + console.error('deleteBackward err: ' + JSON.stringify(err)); +}); ``` ### insertText9+ @@ -1388,7 +1282,7 @@ insertText(text:string, callback: AsyncCallback<boolean>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1433,7 +1327,7 @@ insertText(text:string): Promise<boolean> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1443,20 +1337,18 @@ insertText(text:string): Promise<boolean> **示例:** ```js -async function InputMethodAbility() { - try { - await InputClient.insertText('test').then((result) => { - if (result) { - console.info('Success to insertText. '); - } else { - console.error('Failed to insertText. '); - } - }).catch((err) => { - console.error('insertText err: ' + JSON.stringify(err)); - }); - } catch (e) { +try { + InputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } + }).catch((err) => { console.error('insertText err: ' + JSON.stringify(err)); - } + }); +} catch (err) { + console.error('insertText err: ' + JSON.stringify(err)); } ``` @@ -1476,7 +1368,7 @@ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1511,7 +1403,7 @@ getEditorAttribute(): Promise<EditorAttribute> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1520,14 +1412,12 @@ getEditorAttribute(): Promise<EditorAttribute> **示例:** ```js -async function InputMethodEngine() { - await InputClient.getEditorAttribute().then((editorAttribute) => { - console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); - console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); - }).catch((err) => { - console.error('getEditorAttribute err: ' + JSON.stringify(err)); - }); -} +InputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}).catch((err) => { + console.error('getEditorAttribute err: ' + JSON.stringify(err)); +}); ``` ### moveCursor9+ @@ -1547,7 +1437,7 @@ moveCursor(direction: number, callback: AsyncCallback<void>): void **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1557,7 +1447,7 @@ moveCursor(direction: number, callback: AsyncCallback<void>): void ```js try { - InputClient.moveCursor(inputMethodAbility.CURSOR_xxx, (err) => { + InputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { if (err) { console.error('moveCursor err: ' + JSON.stringify(err)); return; @@ -1591,7 +1481,7 @@ moveCursor(direction: number): Promise<void> **错误码:** -以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errcode-inputmethod-framework.md)。 +以下错误码的详细介绍请参见[输入法框架错误码](../errorcodes/errorcode-inputmethod-framework.md)。 | 错误码ID | 错误码信息 | | -------- | -------------------------- | @@ -1600,20 +1490,14 @@ moveCursor(direction: number): Promise<void> **示例:** ```js -async function InputMethodAbility() { - try { - await InputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then((err) => { - if (err) { - console.log('moveCursor err: ' + JSON.stringify(err)); - return; - } - console.log('moveCursor success'); - }).catch((err) => { - console.error('moveCursor success err: ' + JSON.stringify(err)); - }); - } catch (err) { - console.log('moveCursor err: ' + JSON.stringify(err)); - } +try { + InputClient.moveCursor(inputMethodEngine.CURSOR_UP).then(() => { + console.log('moveCursor success'); + }).catch((err) => { + console.error('moveCursor success err: ' + JSON.stringify(err)); + }); +} catch (err) { + console.log('moveCursor err: ' + JSON.stringify(err)); } ``` @@ -1706,14 +1590,12 @@ getForward(length:number): Promise<string> **示例:** ```js -async function InputMethodEngine() { - let length = 1; - await TextInputClient.getForward(length).then((text) => { - console.info('getForward result---res: ' + text); - }).catch((err) => { - console.error('getForward err: ' + JSON.stringify(err)); - }); -} +let length = 1; +TextInputClient.getForward(length).then((text) => { + console.info('getForward result: ' + JSON.stringify(text)); +}).catch((err) => { + console.error('getForward err: ' + JSON.stringify(err)); +}); ``` ### getBackward(deprecated) @@ -1775,14 +1657,12 @@ getBackward(length:number): Promise<string> **示例:** ```js -async function InputMethodEngine() { - let length = 1; - await TextInputClient.getBackward(length).then((text) => { - console.info('getBackward result---res: ' + text); - }).catch((err) => { - console.error('getBackward err: ' + JSON.stringify(err)); - }); -} +let length = 1; +TextInputClient.getBackward(length).then((text) => { + console.info('getBackward result: ' + JSON.stringify(text)); +}).catch((err) => { + console.error('getBackward err: ' + JSON.stringify(err)); +}); ``` ### deleteForward(deprecated) @@ -1848,18 +1728,16 @@ deleteForward(length:number): Promise<boolean> **示例:** ```js -async function InputMethodEngine() { - let length = 1; - await TextInputClient.deleteForward(length).then((result) => { - if (result) { - console.info('Success to deleteForward. '); - } else { - console.error('Failed to deleteForward. '); - } - }).catch((err) => { - console.error('deleteForward err: ' + JSON.stringify(err)); - }); -} +let length = 1; +TextInputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Succeed in deleting forward. '); + } else { + console.error('Failed to delete forward. '); + } +}).catch((err) => { + console.error('Failed to delete forward err: ' + JSON.stringify(err)); +}); ``` ### deleteBackward(deprecated) @@ -1925,18 +1803,16 @@ deleteBackward(length:number): Promise<boolean> **示例:** ```js -async function InputMethodEngine() { - let length = 1; - await TextInputClient.deleteBackward(length).then((result) => { - if (result) { - console.info('Success to deleteBackward. '); - } else { - console.error('Failed to deleteBackward. '); - } - }).catch((err) => { - console.error('deleteBackward err: ' + JSON.stringify(err)); - }); -} +let length = 1; +TextInputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Success to deleteBackward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}).catch((err) => { + console.error('deleteBackward err: ' + JSON.stringify(err)); +}); ``` ### sendKeyFunction(deprecated) @@ -2000,17 +1876,15 @@ sendKeyFunction(action:number): Promise<boolean> **示例:** ```js -async function InputMethodEngine() { - await client.sendKeyFunction(keyFunction).then((result) => { - if (result) { - console.info('Success to sendKeyFunction. '); - } else { - console.error('Failed to sendKeyFunction. '); - } - }).catch((err) => { - console.error('sendKeyFunction err:' + JSON.stringify(err)); - }); -} +TextInputClient.sendKeyFunction(keyFunction).then((result) => { + if (result) { + console.info('Success to sendKeyFunction. '); + } else { + console.error('Failed to sendKeyFunction. '); + } +}).catch((err) => { + console.error('sendKeyFunction err:' + JSON.stringify(err)); +}); ``` ### insertText(deprecated) @@ -2075,17 +1949,15 @@ insertText(text:string): Promise<boolean> **示例:** ```js -async function InputMethodEngine() { - await TextInputClient.insertText('test').then((result) => { - if (result) { - console.info('Success to insertText. '); - } else { - console.error('Failed to insertText. '); - } - }).catch((err) => { - console.error('insertText err: ' + JSON.stringify(err)); - }); -} +TextInputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText. '); + } else { + console.error('Failed to insertText. '); + } +}).catch((err) => { + console.error('insertText err: ' + JSON.stringify(err)); +}); ``` ### getEditorAttribute(deprecated) @@ -2140,12 +2012,10 @@ getEditorAttribute(): Promise<EditorAttribute> **示例:** ```js -async function InputMethodEngine() { - await TextInputClient.getEditorAttribute().then((editorAttribute) => { - console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); - console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); - }).catch((err) => { - console.error('getEditorAttribute err: ' + JSON.stringify(err)); - }); -} +TextInputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}).catch((err) => { + console.error('getEditorAttribute err: ' + JSON.stringify(err)); +}); ``` \ No newline at end of file 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..242b63a32ab5337185af44603502d634ae068b2b 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`])}`); } 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..9dcb496371bb59a6fcafc7e8f9554cf05f6bef97 --- /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/errcode-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/errcode-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/errcode-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/errcode-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/errcode-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-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-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-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index 19f1b797cbcf589420db7330d30aca5e35c09084..27b1bfc3f827854304bb83ebe8cd7e643491d11e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -465,7 +465,6 @@ 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)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 @@ -509,7 +508,6 @@ 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)(); // bind为JS标准内置对象Function的方法,用于改变this的指向,测试异常捕获 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-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index 7a2a4623d5e4aab2f9f49985e87d25e2d00c09ab..74dead2958ab76019eeea847595d14c3648d074e 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; @@ -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; 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 9bda491c7367701b952ea81a493c6ae73dbb0d41..1bf99a5114ee2ff91fdf710eedb6aae38c0442fe 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 @@ -1284,7 +1284,7 @@ getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------------- | | path | string | 是 | rawfile文件路径 | -| callback | AsyncCallback<[getRawFd](#getrawfd9)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | +| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | 是 | 异步回调,用于返回获取的rawfile文件的descriptor | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 @@ -1325,7 +1325,7 @@ getRawFd(path: string): Promise<RawFileDescriptor> **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------------- | -| Promise<[getRawFd](#getrawfd9-1)> | rawfile文件descriptor | +| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | rawfile文件descriptor | 以下错误码的详细介绍请参见[资源管理错误码](../errorcodes/errorcode-resource-manager.md)。 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-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\ { + mgr.createPhotoAsset('testFile.jpg', album.albumUri, (err, fileAsset) => { if (fileAsset != undefined) { console.info('createPhotoAsset file displayName' + fileAsset.displayName); console.info('createPhotoAsset successfully'); @@ -221,7 +222,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 +262,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) { @@ -308,8 +309,9 @@ async function example() { console.info('album is undefined, err = ', err); } }) + } else { + console.info('getPhotoAlbums fail, message = ', err); } - console.info('getPhotoAlbums fail, message = ', err); }) } ``` @@ -457,7 +459,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(); @@ -505,7 +507,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 +525,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 @@ -570,7 +572,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 @@ -637,10 +639,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 +684,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"); + } } ``` 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 e96cd51d7dbf06eb49834227d954ee730f02d6fb..164f69a071584ae837c07a4ee960e0a553bbd3c7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vector.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -285,7 +285,6 @@ vector.add(4); vector.add(5); vector.add(4); vector.removeByRange(2,4); -vector.removeByRange(2,6); ``` ### replaceAllElements 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..e34b009be8fc8155eab680bf66c8eded0ab086bf 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+ @@ -223,7 +261,7 @@ try { | 名称 | 默认值 | 说明 | | -------- | ------ | ------------------------------ | | type | "time" | 按照指定持续时间触发马达振动。 | -| duration | - | 马达振动时长, 单位ms。 | +| duration | - | 马达持续振动时长, 单位ms。 | ## VibratePreset9+ @@ -246,7 +284,7 @@ try { | 名称 | 默认值 | 说明 | | ----- | ------ | -------------- | | 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 8b74f1843c10dcc4f3c767f44b08c464372a2b07..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 @@ -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"); + } } ``` 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 71ea2ca0e4557091cb279f2e8a23663cd5d5771d..162f75d0804a942d1d97097dbfcc6c006a7b63fb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -1221,7 +1221,7 @@ 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.'); }) ``` @@ -1329,7 +1329,7 @@ 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)); }) @@ -1856,7 +1856,7 @@ try { getWindowAvoidArea(type: AvoidAreaType): AvoidArea -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 **系统能力:** SystemCapability.WindowManager.WindowManager.Core @@ -4590,7 +4590,7 @@ promise.then((data)=> { getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void -获取窗口内容规避的区域,如系统的系统栏区域、刘海屏区域、手势区域、软键盘区域等。 +获取窗口内容规避的区域;如系统栏区域、刘海屏区域、手势区域、软键盘区域等与窗口内容重叠时,需要窗口内容避让的区域。 > **说明:** > @@ -4622,11 +4622,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 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-zlib.md b/zh-cn/application-dev/reference/apis/js-apis-zlib.md index 3c85311c4ba3748b49b6d4ce1764531a94f26dcc..84b3499495eba387eea6c99683c21506144be1d8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-zlib.md +++ b/zh-cn/application-dev/reference/apis/js-apis-zlib.md @@ -160,7 +160,7 @@ let options = { try { zlib.compressFile(inFile, outFile, options, (errData) => { - if (erData !== null) { + if (errData !== null) { console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) @@ -257,7 +257,7 @@ let options = { try { zlib.decompressFile(inFile, outFile, options, (errData) => { - if (erData !== null) { + if (errData !== null) { console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); } }) @@ -301,8 +301,8 @@ let options = { }; try { - zlib.deCompressFile(inFile, outFile, options).then((data) => { - console.info('deCompressFile success'); + zlib.decompressFile(inFile, outFile, options).then((data) => { + console.info('decompressFile success'); }).catch((errData) => { console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); }) 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/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-qrcode.md b/zh-cn/application-dev/reference/arkui-js/js-components-basic-qrcode.md index 5b156b7bffefe8b1e34d718c789e38d4dc1c4249..eb7e960a47abd94b5d13ad9f12f15f4440210a89 100644 --- a/zh-cn/application-dev/reference/arkui-js/js-components-basic-qrcode.md +++ b/zh-cn/application-dev/reference/arkui-js/js-components-basic-qrcode.md @@ -58,8 +58,6 @@
- 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-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 7414bbdc09505ec7ba9523eeaf200349bbcb1fbd..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 } | 返回表冠旋转角度增量值,仅智能穿戴支持。 | ## 方法 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-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/ts-basic-components-image.md b/zh-cn/application-dev/reference/arkui-ts/ts-basic-components-image.md index 95ea376b2a4dec554b07cc11bcb75c95eff7dbf1..d4136b03993cd98bc773b7f905499e4146e20f50 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 | 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 5e5b34dd01d28eda65afd2d00ebfacd037055eb3..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) @@ -771,7 +742,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) = onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) -刷新或关闭场景下,在即将离开当前页面时触发此回调。刷新当前页面应先通过点击等方式获取焦点,才会触发此回调。 +刷新或关闭场景下,在即将离开当前页面时触发此回调。刷新或关闭当前页面应先通过点击等方式获取焦点,才会触发此回调。 **参数:** @@ -2057,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)。 @@ -3898,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)。 @@ -5155,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+ @@ -5365,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 2f819a5c110bac78019962d02fae5e773d7e1a4f..54fb54c658025a7089ef86bb7faf31aad8b5edea 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枚举说明 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-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-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-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-textpicker-dialog.md b/zh-cn/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 981e3657b58f26359fe17d126a73a4763836f6f4..5772b95f5602c0706b4baaa5fa4f2e7c82060c07 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 @@ -15,22 +15,22 @@ show(options?: 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-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-transition-animation-component.md b/zh-cn/application-dev/reference/arkui-ts/ts-transition-animation-component.md index 6e397391f91cbc5681d9be59b70b1c91f2b4ae10..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,7 +20,7 @@ | -------- | -------- | -------- | -------- | | type | [TransitionType](ts-appendix-enums.md#transitiontype) | 否 | 默认包括组件新增和删除。
默认值:TransitionType.All
**说明:**
不指定Type时说明插入删除使用同一种效果。 | | opacity | number | 否 | 设置组件转场时的透明度效果,为插入时起点和删除时终点的值。
默认值:1 | -| translate | {
x? : number,
y? : number,
z? : number
} | 否 | 设置组件转场时的平移效果,为插入时起点和删除时终点的值。
-x:横向的平移距离。
-y:纵向的平移距离。
-z:竖向的平移距离。 | +| 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-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/errcode-Account.md b/zh-cn/application-dev/reference/errorcodes/errcode-Account.md index b7c29b43401ba05a1bf6a4d0b908271f6ba701d2..0894a278080b8ac2be19eb4b7ccade4a82c324d5 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-Account.md +++ b/zh-cn/application-dev/reference/errorcodes/errcode-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/errcode-bundle.md index 509944b152d70c4c7062af64456e1bd82a7d9f18..23752692a6dd21cf67de3ba36d5ff94f5a93b94f 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md +++ b/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md @@ -29,7 +29,7 @@ The specified module name is not found. 2. 系统中对应的应用没有安装该模块。 **处理步骤**
-1. 检查bundleName拼写是否正确。 +1. 检查moduleName拼写是否正确。 2. 确认对应的应用是否安装该模块。 ## 17700003 指定的abilityName不存在 @@ -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. **错误描述**
-签名校验失败失败导致应用安装失败。 +签名校验失败导致应用安装失败。 **可能原因**
+ 1. hap包没有签名。 2. hap签名信息来源不可靠。 3. 升级的hap包与已安装的hap包签名信息不一致。 @@ -146,49 +147,23 @@ 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 since the path of the hap is invalid or too large size. **错误描述**
-安装包路径无效导致应用安装失败。 +安装包路径无效或者文件过大导致应用安装失败。 **可能原因**
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包配置信息不同导致应用安装失败 @@ -365,3 +340,32 @@ The distributed service is not running. **处理步骤**
确认输入的ability和type拼写是否正确。 + +## 17700029 指定的ability被禁用 + +**错误信息**
+The specified ability is disabled. + +**错误描述**
+指定的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 cache files. + +**错误描述**
+指定的应用不支持清除缓存文件。 + +**可能原因**
+指定的应用为系统应用且在签名证书中配置了不能清除数据(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/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/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/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 b616de50c2dbfe461af73e4b5e288604420c7f87..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"中做声明如下: 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 84% 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..fe74ba5402db55668d8a8b6e54c9f43907921135 100644 --- a/zh-cn/application-dev/quick-start/app-provision-structure.md +++ b/zh-cn/application-dev/security/app-provision-structure.md @@ -63,20 +63,20 @@ 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。 | 字符串 | 必选 | 不可缺省 | +| apl | 表示应用程序的[apl级别](accesstoken-overview.md),系统预定义的apl包括:normal、system_basic和system_core。 | 字符串 | 必选 | 不可缺省 | | app-feature | 表示应用程序的类型,系统预定义的app-feature包括hos_system_app (系统应用)和hos_normal_app(普通应用)。 | 字符串 | 必选 | 不可缺省 | ### 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属性中。 @@ -84,7 +84,7 @@ permissions对象包含允许使用的受限敏感权限。不同于acls对象 表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 53e9dd5e8656813eebb9c420e92afb6fc5e1e8d1..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 | 允许系统应用访问权限使用记录。 | 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/device-dev/Readme-CN.md b/zh-cn/device-dev/Readme-CN.md index 146d5484f274750a806173175d7d628cb7c68cb6..677035cc831d7956b4a79354aaf2a9139775bde1 100644 --- a/zh-cn/device-dev/Readme-CN.md +++ b/zh-cn/device-dev/Readme-CN.md @@ -54,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-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-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/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..eacb6fcc14080bdab991b4e8343ea8a63932d156 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 @@ -184,8 +184,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 +196,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 +245,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 +258,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 +266,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 +274,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 ![zh-cn_image_0000001275802150](figures/zh-cn_image_0000001275802150.png) -9. 烧录成功后,请根据运行章节进行操作,启动系统。 +8. 烧录成功后,请根据运行章节进行操作,启动系统。 ## 运行 @@ -294,12 +297,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 +310,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 4. 保存参数设置。 - ``` + ```shell save ``` @@ -315,7 +318,7 @@ Hi3516DV300开发板标准系统的烧录方式包括USB烧录、网口烧录两 5. 重启开发板,完成系统启动。 - ``` + ```shell reset ``` 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-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 2f86d43843784a3c5098eb7bb54b852167657e3f..acd1c7b4da051bbc6736ed35ffa32f92f2d00f8f 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -90,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) @@ -112,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-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-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-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..5a3906b2e8355b14d365fad31b77f3349a837913 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -516,13 +516,15 @@ - [外设驱动开发示例](guide/device-outerdriver-demo.md) -- 调测 - - [测试用例开发](subsystems/subsys-testguide-test.md) +- 调测工具 + - 设备测试 + - [developer_test开发者自测试执行框架使用指导](device-test/developer_test.md) + - [xdevice测试调度框架使用指导](device-test/xdevice.md) + - [XTS用例开发指导](device-test/xts.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) - 工具 - [Docker编译环境](get-code/gettools-acquire.md) - [IDE集成开发环境](get-code/gettools-ide.md)